@organizaone/o1-code 0.20.3 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/bundled/qc-helper/docs/common-workflow.md +2 -2
  2. package/bundled/qc-helper/docs/extension/getting-started-extensions.md +1 -1
  3. package/bundled/qc-helper/docs/features/commands.md +15 -1
  4. package/chunks/{MaxSizedBox-EZERR2VP.js → MaxSizedBox-UVDDWU7T.js} +21 -20
  5. package/chunks/{StandaloneSessionPicker-JNWXQZWK.js → StandaloneSessionPicker-BMP4CROY.js} +42 -41
  6. package/chunks/{acp-subagent-executor-SWU2HEK2.js → acp-subagent-executor-FV3XBATE.js} +19 -19
  7. package/chunks/{acpAgent-KBGZCBFV.js → acpAgent-6QL2DRXT.js} +114 -112
  8. package/chunks/{agent-IXG5INIW.js → agent-7RIITHH6.js} +9 -9
  9. package/chunks/{agent-headless-SY563G4Y.js → agent-headless-V7G74ZRT.js} +9 -9
  10. package/chunks/{all-providers-GEEOO5NG.js → all-providers-NUAV373L.js} +2 -2
  11. package/chunks/{anthropicContentGenerator-QPZOYWP7.js → anthropicContentGenerator-IMMO2JES.js} +5 -5
  12. package/chunks/{bridge-RCKHVFJ3.js → bridge-NOBAHBIW.js} +19 -19
  13. package/chunks/{ca-6DKW436A.js → ca-EMDHXMDN.js} +6 -2
  14. package/chunks/{chunk-VWOLZXSN.js → chunk-2327FMUY.js} +4 -4
  15. package/chunks/{chunk-FRXXYR4K.js → chunk-24LWP4WE.js} +2 -2
  16. package/chunks/chunk-2EFFEOP5.js +5043 -0
  17. package/chunks/{chunk-HDVWETU2.js → chunk-3QWBMA3B.js} +12 -12
  18. package/chunks/{chunk-CH4NSUSE.js → chunk-3ZEBS4OE.js} +9 -9
  19. package/chunks/{chunk-UCXFJKY7.js → chunk-4NXPUJJK.js} +2 -2
  20. package/chunks/{chunk-PRHAZ5WA.js → chunk-4VB7VM7K.js} +1 -1
  21. package/chunks/{chunk-SKAH52QV.js → chunk-4XTPBUUX.js} +1 -1
  22. package/chunks/{chunk-5KLLG2CZ.js → chunk-5ZH7V5XA.js} +1 -1
  23. package/chunks/{chunk-KV5NXG3S.js → chunk-6LZG7Y6K.js} +2 -2
  24. package/chunks/{chunk-URHRCX4D.js → chunk-6YVU3VTW.js} +2 -2
  25. package/chunks/{chunk-RBNHPCLB.js → chunk-A3Z6ZU7I.js} +2 -2
  26. package/chunks/{chunk-MBJJLPMX.js → chunk-AFFISWZB.js} +32 -30
  27. package/chunks/{chunk-VQYBOX6T.js → chunk-B4XD2AVP.js} +2 -2
  28. package/chunks/{chunk-XVYLALS6.js → chunk-B5BMQDN6.js} +2 -2
  29. package/chunks/{chunk-6YH4HZFZ.js → chunk-BCCQP2PA.js} +3 -3
  30. package/chunks/{chunk-K6XWNSG7.js → chunk-BDXSHKWM.js} +1 -1
  31. package/chunks/{chunk-PFOXLZCP.js → chunk-BG5FFE5T.js} +9 -9
  32. package/chunks/{chunk-RATJ5RDQ.js → chunk-BJIFDJVV.js} +2 -2
  33. package/chunks/{chunk-L5MVOG3F.js → chunk-BYQ4WWVG.js} +1 -1
  34. package/chunks/{chunk-3DMPE7V6.js → chunk-BZXX2MRG.js} +1 -1
  35. package/chunks/{chunk-OMBM5PM7.js → chunk-COZEN7HG.js} +6 -6
  36. package/chunks/{chunk-ZKBTWORX.js → chunk-CUGVJRCO.js} +2 -2
  37. package/chunks/{chunk-7EXAMT2I.js → chunk-DAZ4E2KL.js} +2 -2
  38. package/chunks/{chunk-6F6GDT4W.js → chunk-DEEUE6NL.js} +9 -9
  39. package/chunks/{chunk-23MB6DC2.js → chunk-EDYCC6T6.js} +5 -5
  40. package/chunks/{chunk-KMIBUJJV.js → chunk-FJVTBMTU.js} +3 -3
  41. package/chunks/{chunk-4WQOE2IB.js → chunk-FSM6MGRH.js} +2 -2
  42. package/chunks/{chunk-R3QWLJJF.js → chunk-G2GNLDQS.js} +13 -13
  43. package/chunks/{chunk-QTKR2GD7.js → chunk-GB6XUAYL.js} +1 -1
  44. package/chunks/{chunk-CX4XYMNF.js → chunk-GWAPD4WA.js} +7 -7
  45. package/chunks/{chunk-E6FTSEFU.js → chunk-HG2CPZUM.js} +3 -3
  46. package/chunks/{chunk-4B3VOPKW.js → chunk-HJRDPASY.js} +5 -5
  47. package/chunks/{chunk-CN7MCAV5.js → chunk-HVCQOHA6.js} +4 -4
  48. package/chunks/{chunk-2DFFYJGZ.js → chunk-HXOUCS5U.js} +4 -4
  49. package/chunks/{chunk-LPP5I5D7.js → chunk-IAW6OPW2.js} +3 -3
  50. package/chunks/{chunk-SAA7VWPH.js → chunk-IOUCJCNS.js} +1 -1
  51. package/chunks/{chunk-EW76FWYR.js → chunk-ISDTLMDF.js} +1 -1
  52. package/chunks/{chunk-P6YI66SA.js → chunk-J3I2P6J4.js} +1 -1
  53. package/chunks/{chunk-2FDD7R4M.js → chunk-J4JE4YP3.js} +6 -6
  54. package/chunks/{chunk-VJWTK75T.js → chunk-J5RKE7HJ.js} +8 -8
  55. package/chunks/{chunk-2HLFWCUP.js → chunk-JEI2AYFD.js} +1 -1
  56. package/chunks/{chunk-Q6RYNLZS.js → chunk-JJNBSJTF.js} +2 -2
  57. package/chunks/{chunk-4ABEICOS.js → chunk-JYBDW4YQ.js} +1 -1
  58. package/chunks/{chunk-TR4DEKSP.js → chunk-KK2WC2WS.js} +2 -2
  59. package/chunks/{chunk-SLIL7BEZ.js → chunk-KRPFK75A.js} +2 -2
  60. package/chunks/{chunk-QKL4LXBU.js → chunk-KZ6OFUYM.js} +8 -8
  61. package/chunks/chunk-LRHUT6ZW.js +880 -0
  62. package/chunks/{chunk-Q6OW4P7O.js → chunk-LU3L67JW.js} +1 -1
  63. package/chunks/{chunk-EZ3OQPXV.js → chunk-MJFHIUKG.js} +2 -2
  64. package/chunks/{chunk-QAWZUGTG.js → chunk-NXQOTJAA.js} +2 -2
  65. package/chunks/{chunk-GDRFBPU5.js → chunk-NZYHDUMN.js} +1 -1
  66. package/chunks/{chunk-AY7TZ56V.js → chunk-O7V7JWOM.js} +86 -43
  67. package/chunks/{chunk-FG53SLIP.js → chunk-OK7GPGMS.js} +2 -2
  68. package/chunks/{chunk-RHZORPOC.js → chunk-ONTIVYTW.js} +3 -3
  69. package/chunks/{chunk-GFSDXCA6.js → chunk-P4OBMVRT.js} +3 -3
  70. package/chunks/{chunk-VFSP4ZUZ.js → chunk-P7RO4QSF.js} +28 -938
  71. package/chunks/{chunk-GVELMYCX.js → chunk-PK3MLBOH.js} +1 -1
  72. package/chunks/{chunk-ZJ3GFM2U.js → chunk-PP3G5KXH.js} +1 -1
  73. package/chunks/{chunk-CIQ2CLQ2.js → chunk-QAJ7AQSA.js} +1 -1
  74. package/chunks/{chunk-AP5DFANZ.js → chunk-QKZVYY6J.js} +5 -5
  75. package/chunks/{chunk-NTUVIB2G.js → chunk-R5HO4EJV.js} +1 -1
  76. package/chunks/{chunk-IUFEZVEZ.js → chunk-RMYDHM23.js} +3 -3
  77. package/chunks/{chunk-LNWFWFJ4.js → chunk-SL3PHYCR.js} +3 -3
  78. package/chunks/{chunk-2GPRQW4P.js → chunk-SYZ5WTE6.js} +2 -2
  79. package/chunks/{chunk-CEQQIJ45.js → chunk-T7MXEOXM.js} +2 -2
  80. package/chunks/{chunk-DSAFH5CY.js → chunk-TJQTTY4F.js} +1 -1
  81. package/chunks/{chunk-RI3VQTAX.js → chunk-TMYTIDVN.js} +3 -3
  82. package/chunks/{chunk-TBVRYAVY.js → chunk-TZRF4LY7.js} +3 -3
  83. package/chunks/{chunk-YPR43UHE.js → chunk-UKCKAG2F.js} +39 -39
  84. package/chunks/{chunk-FBHAG372.js → chunk-UUT7HQPM.js} +3 -3
  85. package/chunks/{chunk-7UME3BB3.js → chunk-UWSO6VOM.js} +1 -1
  86. package/chunks/{chunk-N2JEPFUF.js → chunk-UXJP6322.js} +3 -3
  87. package/chunks/{chunk-MDJ4DEEJ.js → chunk-V5QHABRY.js} +1 -1
  88. package/chunks/chunk-VDSY3ODQ.js +2405 -0
  89. package/chunks/{chunk-3TLBRQSX.js → chunk-VT5GZKMO.js} +1 -1
  90. package/chunks/{chunk-FDKCSPGD.js → chunk-W3XJPDIO.js} +13 -13
  91. package/chunks/{chunk-GNZQPESW.js → chunk-WKGMAUE7.js} +1 -1
  92. package/chunks/{chunk-LYYJBCAH.js → chunk-WOAI6G73.js} +3 -3
  93. package/chunks/{chunk-TQ65TNCT.js → chunk-WQYJ72JS.js} +1 -1
  94. package/chunks/{chunk-RTTJOKFS.js → chunk-WTC5HDJJ.js} +10 -10
  95. package/chunks/{chunk-VLAUXCTV.js → chunk-WU7DQB4Q.js} +4 -4
  96. package/chunks/{chunk-LFMK5B3W.js → chunk-X7Q5L62S.js} +1 -1
  97. package/chunks/{chunk-WILZABQC.js → chunk-XCWRCCIS.js} +1 -1
  98. package/chunks/{chunk-KSXF26WD.js → chunk-XHHPCZOZ.js} +2 -2
  99. package/chunks/{chunk-GLHPVNIZ.js → chunk-XIYHMMHO.js} +4 -4
  100. package/chunks/{chunk-ME6C5KAY.js → chunk-XMEAEIT7.js} +1 -1
  101. package/chunks/{chunk-LKRP2YCP.js → chunk-XXPXFR7S.js} +48 -48
  102. package/chunks/chunk-YQQ7QFC5.js +945 -0
  103. package/chunks/{chunk-A5JZKZ6Q.js → chunk-YXRFXEIU.js} +5 -5
  104. package/chunks/{chunk-F5OH2PNI.js → chunk-ZGHZRHUW.js} +1 -1
  105. package/chunks/{codex-subagent-executor-WNFU67G7.js → codex-subagent-executor-3MIEB3VJ.js} +19 -19
  106. package/chunks/{contextCommand-6LFH2YPP.js → contextCommand-H6YVYBS3.js} +19 -19
  107. package/chunks/{core-runtime-MFXIMNSH.js → core-runtime-2HHFL26H.js} +17 -17
  108. package/chunks/{create-sub-session-NUE3R5WZ.js → create-sub-session-ALKLKZWI.js} +18 -18
  109. package/chunks/{daemon-git-worktree-guard-PQ3SE2KI.js → daemon-git-worktree-guard-FKKXZKOZ.js} +17 -17
  110. package/chunks/{daemon-status-provider-Z5OUOPTR.js → daemon-status-provider-L3JVFUFB.js} +24 -24
  111. package/chunks/{daemon-trust-policy-TX4QULOJ.js → daemon-trust-policy-UKZ4URR5.js} +24 -24
  112. package/chunks/{daemon-trust-policy-monitor-CNBHLZT7.js → daemon-trust-policy-monitor-O3BAF5WQ.js} +24 -24
  113. package/chunks/{de-E75VCQRZ.js → de-OMV463ND.js} +6 -2
  114. package/chunks/{deferred-core-runtime-XDE6DRBZ.js → deferred-core-runtime-TX4M62JC.js} +17 -17
  115. package/chunks/{edit-QONTKKDS.js → edit-URCTP3DW.js} +11 -11
  116. package/chunks/{en-TS3SF6KR.js → en-EEVIOXSR.js} +6 -2
  117. package/chunks/{enterPlanMode-A3NZ5LMR.js → enterPlanMode-JGAWYT7U.js} +9 -9
  118. package/chunks/{environment-6FE7XGAC.js → environment-5NRP4NYH.js} +19 -19
  119. package/chunks/{errors-R5Y7H2GW.js → errors-7BX5N6WH.js} +19 -19
  120. package/chunks/{execution-tool-BTPXNHGK.js → execution-tool-4MAOTD33.js} +11 -11
  121. package/chunks/{execution-worker-Q2WOKDYJ.js → execution-worker-FE64M6YB.js} +14 -14
  122. package/chunks/{exitPlanMode-FWVAIF2G.js → exitPlanMode-MRIMIR7S.js} +9 -9
  123. package/chunks/{fast-path-ADV46XXY.js → fast-path-PI7IUZO5.js} +5 -5
  124. package/chunks/foreground-runner-ODCBQ62T.js +1496 -0
  125. package/chunks/{fr-KWQ6T7MX.js → fr-ZHVJMULM.js} +6 -2
  126. package/chunks/{glob-7C5LFIFY.js → glob-VVMTH2FZ.js} +9 -9
  127. package/chunks/{goal-tools-ZBOA3S6T.js → goal-tools-PIZJOC5V.js} +9 -9
  128. package/chunks/{handleAutoUpdate-OZFXXZGE.js → handleAutoUpdate-7CYUYIFT.js} +20 -20
  129. package/chunks/{i18n-ETDHGUAS.js → i18n-DZGPXZHL.js} +18 -18
  130. package/chunks/{initializer-3TGPNDS6.js → initializer-6MWLCO6O.js} +26 -25
  131. package/chunks/{installationInfo-53FUD2SP.js → installationInfo-2YFHIA4G.js} +17 -17
  132. package/chunks/{ja-NLAMHYSV.js → ja-MQ3LTDXD.js} +6 -2
  133. package/chunks/{list-D2SFACP2.js → list-2PCYJ5KG.js} +26 -26
  134. package/chunks/{llm-6JBUAXKT.js → llm-QVOVDL2Q.js} +70 -70
  135. package/chunks/{llm-content-generator-X2YXGOCB.js → llm-content-generator-P4MM2G4V.js} +4 -4
  136. package/chunks/{loadedSettingsAdapter-S2OW76SD.js → loadedSettingsAdapter-6DG3R23U.js} +24 -24
  137. package/chunks/{local-execution-environment-TCIIK3JA.js → local-execution-environment-RQZE5ZPQ.js} +14 -14
  138. package/chunks/{loggingContentGenerator-GDJB7R3H.js → loggingContentGenerator-T5HYYF2G.js} +9 -9
  139. package/chunks/{managed-npm-update-I3YZBNY7.js → managed-npm-update-FKD3RX22.js} +17 -17
  140. package/chunks/{mcp-6GZRGYAG.js → mcp-CONKBRY3.js} +24 -24
  141. package/chunks/{model-call-collection-YAUSBU5N.js → model-call-collection-L6GU4PEV.js} +1 -1
  142. package/chunks/{model-configuration-SMKT6PVP.js → model-configuration-TBFXQOP6.js} +25 -25
  143. package/chunks/{modelConfigUtils-FEON5T3Z.js → modelConfigUtils-ID2MFVCP.js} +19 -19
  144. package/chunks/{monitor-RNGWRP7C.js → monitor-ETBC2KHX.js} +9 -9
  145. package/chunks/{nonInteractiveCli-5N55OFDF.js → nonInteractiveCli-QPKDUFGH.js} +62 -60
  146. package/chunks/{nonInteractiveToolExecutor-EURXYN6L.js → nonInteractiveToolExecutor-7ZDYEIOV.js} +10 -10
  147. package/chunks/{notebook-edit-DMEOTACP.js → notebook-edit-PBP4CLHC.js} +10 -10
  148. package/chunks/{omni-A6J5PKS7.js → omni-EBPCPKLP.js} +9 -9
  149. package/chunks/{openaiContentGenerator-2ZU6S23B.js → openaiContentGenerator-FJJDGKFI.js} +6 -6
  150. package/chunks/{openaiResponsesContentGenerator-4RE34Y4W.js → openaiResponsesContentGenerator-Y27KA4YJ.js} +4 -4
  151. package/chunks/{processUtils-VBBXC2KT.js → processUtils-EUHGQHUQ.js} +2 -2
  152. package/chunks/{prompt-terminal-ledger-6DE5MRV3.js → prompt-terminal-ledger-XV4MIV4H.js} +18 -18
  153. package/chunks/{pt-F6OOJLH6.js → pt-AVWESYKZ.js} +6 -2
  154. package/chunks/pty-host-process-PKCVFICX.js +29 -0
  155. package/chunks/{reactive-degrade-S3SQRQ4D.js → reactive-degrade-LL5MSPMK.js} +8 -8
  156. package/chunks/{read-file-HDY4MSJE.js → read-file-HQVTDGX5.js} +1 -1
  157. package/chunks/{resumeHistoryUtils-BX3CLUM7.js → resumeHistoryUtils-DKTD3ZG2.js} +26 -25
  158. package/chunks/{ripGrep-4E63BMST.js → ripGrep-WA7AGEV7.js} +1 -1
  159. package/chunks/{ru-QXDK3EHQ.js → ru-CSBDIXDS.js} +6 -2
  160. package/chunks/{run-o1-code-serve-FR3YWC7D.js → run-o1-code-serve-27EWAN7V.js} +49 -49
  161. package/chunks/{sandboxConfig-7D6ZZBBU.js → sandboxConfig-B4Z7RRB6.js} +17 -17
  162. package/chunks/{scheduled-tasks-FEV7YG7C.js → scheduled-tasks-KBBSAL7T.js} +22 -22
  163. package/chunks/{scheduler-OOZEZWGT.js → scheduler-WUFLFLZX.js} +19 -19
  164. package/chunks/{serve-5CZRH2NI.js → serve-GHD5P7VM.js} +24 -24
  165. package/chunks/{server-AIIM3MRX.js → server-O7S2DL3A.js} +141 -141
  166. package/chunks/{session-5IHMC2GA.js → session-4COCQNXM.js} +63 -61
  167. package/chunks/{session-FZ3NBZYB.js → session-74Z72LNM.js} +1 -1
  168. package/chunks/{session-attachments-root-ANZOYK7U.js → session-attachments-root-QTVKHZO3.js} +17 -17
  169. package/chunks/{session-pr-refresh-CJLDHDTN.js → session-pr-refresh-4XWL7OWU.js} +22 -22
  170. package/chunks/{settings-35ADR3M3.js → settings-LKHHDZ22.js} +23 -23
  171. package/chunks/{shell-T7WI2AB4.js → shell-MBJWYI6H.js} +9 -9
  172. package/chunks/{skill-3J334MPG.js → skill-P47GW76V.js} +1 -1
  173. package/chunks/{skill-settings-VGNIJ4ZG.js → skill-settings-OOKHO2VX.js} +23 -23
  174. package/chunks/{spawnChannel-4GZBVZWY.js → spawnChannel-BCCGOYBS.js} +18 -18
  175. package/chunks/{standalone-update-3MMGTOKU.js → standalone-update-GFWLCIJA.js} +19 -19
  176. package/chunks/{startInteractiveUI-ACAXKMOW.js → startInteractiveUI-4U37J3U3.js} +227 -133
  177. package/chunks/supervisor-runner-JHRQ2FCR.js +24 -0
  178. package/chunks/{team-create-OL5P2TT3.js → team-create-V7TS7YKU.js} +9 -9
  179. package/chunks/{team-plan-approval-AVOMP63W.js → team-plan-approval-AZFDDNWX.js} +9 -9
  180. package/chunks/{terminal-image-renderer-YIP3F3SW.js → terminal-image-renderer-VKFNJYLX.js} +17 -17
  181. package/chunks/{theme-manager-WGBSECIC.js → theme-manager-NJUI6CSB.js} +19 -18
  182. package/chunks/{tool-result-media-43B2V5GK.js → tool-result-media-PNMKSY4I.js} +9 -9
  183. package/chunks/{tool-search-D4CTJZQZ.js → tool-search-G775WYWX.js} +1 -1
  184. package/chunks/{total-session-admission-5AVX4GWU.js → total-session-admission-EU3OANCQ.js} +19 -19
  185. package/chunks/{trustedFolders-A3EQT2KU.js → trustedFolders-SHDE6P4A.js} +18 -18
  186. package/chunks/{update-relaunch-ZFQ3KKWC.js → update-relaunch-WO4XSFPM.js} +5 -5
  187. package/chunks/{updateCheck-6WIKLTOC.js → updateCheck-VXMUIJQI.js} +19 -19
  188. package/chunks/{upload-config-CYAXYVA5.js → upload-config-W3I5KJ6Z.js} +6 -6
  189. package/chunks/{useAutoAcceptIndicator-WQCDJ3GF.js → useAutoAcceptIndicator-RVZ7NA4T.js} +27 -27
  190. package/chunks/{validateNonInterActiveAuth-YAKY5TIW.js → validateNonInterActiveAuth-Z6VWDBAU.js} +59 -57
  191. package/chunks/{version-2JL37LTE.js → version-BAIHAZMG.js} +1 -1
  192. package/chunks/{web-fetch-3RS7AC6O.js → web-fetch-UVYCFIDA.js} +1 -1
  193. package/chunks/{web-search-32AOEQHL.js → web-search-2HZLV7U7.js} +7 -7
  194. package/chunks/{workflow-N6HB4M7K.js → workflow-MH5F52EN.js} +10 -10
  195. package/chunks/{workspace-providers-status-ZWERGC3Q.js → workspace-providers-status-QGZHLTTK.js} +28 -28
  196. package/chunks/{workspace-registration-store-CCUU3WMT.js → workspace-registration-store-ZOS5W3KI.js} +1 -1
  197. package/chunks/{workspace-registry-HWKUKITM.js → workspace-registry-S5UI2GMP.js} +19 -19
  198. package/chunks/{workspace-runtime-coordinator-7I7MNHER.js → workspace-runtime-coordinator-3VT4F7QU.js} +19 -19
  199. package/chunks/{workspace-service-YYLFPQLW.js → workspace-service-FPIDJZQX.js} +27 -27
  200. package/chunks/{workspace-skills-status-ZW3EQWQ6.js → workspace-skills-status-3NDFOQ7X.js} +24 -24
  201. package/chunks/{workspace-trust-reconciler-G777OJEA.js → workspace-trust-reconciler-MIYMY5WA.js} +28 -28
  202. package/chunks/{write-file-IL2RFUQS.js → write-file-RLFFQHIF.js} +11 -11
  203. package/chunks/{zh-5CH77RQJ.js → zh-6TC2VRKR.js} +6 -2
  204. package/chunks/{zh-TW-7ASXOAM2.js → zh-TW-O23FCREL.js} +6 -2
  205. package/chunks/{zoom-image-K4VOMJ5H.js → zoom-image-TGJMTGFW.js} +1 -1
  206. package/cli.js +67 -14
  207. package/examples/starter/README.md +2 -2
  208. package/execution-worker.js +1 -1
  209. package/export-transcript-document.js +1 -1
  210. package/locales/ca.js +9 -2
  211. package/locales/de.js +9 -2
  212. package/locales/en.js +8 -2
  213. package/locales/fr.js +9 -2
  214. package/locales/ja.js +9 -2
  215. package/locales/pt.js +9 -2
  216. package/locales/ru.js +8 -2
  217. package/locales/zh-TW.js +6 -2
  218. package/locales/zh.js +6 -2
  219. package/package.json +2 -2
  220. package/release-notes.json +6 -0
  221. package/web-shell/assets/{abnfDiagram-VCTEODGH-BvS-3VoN.js → abnfDiagram-VCTEODGH-DvRQo4_D.js} +1 -1
  222. package/web-shell/assets/{arc-oqBoN1VH.js → arc-BdiXk54-.js} +1 -1
  223. package/web-shell/assets/{architectureDiagram-5GKGNRK7-BM3vyqvf.js → architectureDiagram-5GKGNRK7-ghhLp2fv.js} +1 -1
  224. package/web-shell/assets/{blockDiagram-NRAW4CY4-S94Kz5ys.js → blockDiagram-NRAW4CY4-D1Mnhplm.js} +1 -1
  225. package/web-shell/assets/{c4Diagram-UCG6FXSJ-wFyXR3PR.js → c4Diagram-UCG6FXSJ-DUXySExV.js} +1 -1
  226. package/web-shell/assets/channel-Dh8nmHXD.js +1 -0
  227. package/web-shell/assets/{chunk-2Q5K7J3B-BXpOLBvy.js → chunk-2Q5K7J3B-emXgDXOn.js} +1 -1
  228. package/web-shell/assets/{chunk-5VM5RSS4-BWnRV7wD.js → chunk-5VM5RSS4-BAe_FRUg.js} +1 -1
  229. package/web-shell/assets/{chunk-F27PBJKO-NJG1XfCH.js → chunk-F27PBJKO-BFNyq3ws.js} +1 -1
  230. package/web-shell/assets/{chunk-G27WJ6UU-D1MDovk_.js → chunk-G27WJ6UU-CsbX0ea1.js} +1 -1
  231. package/web-shell/assets/{chunk-JWPE2WC7-Biw0OjWW.js → chunk-JWPE2WC7-BJsqlFOz.js} +1 -1
  232. package/web-shell/assets/{chunk-LCL6LL3I-CWoypbS8.js → chunk-LCL6LL3I-BhkoNwBC.js} +1 -1
  233. package/web-shell/assets/{chunk-POPQ4Y6H-ZHBPGpI1.js → chunk-POPQ4Y6H-DDHhZe1n.js} +1 -1
  234. package/web-shell/assets/{chunk-SVP7TREG-BmhiTHIA.js → chunk-SVP7TREG-EMrfHdyh.js} +1 -1
  235. package/web-shell/assets/{chunk-XXDRQBXY-Ctjd24gG.js → chunk-XXDRQBXY-B7vzOyPt.js} +1 -1
  236. package/web-shell/assets/classDiagram-DTDB5LWJ-CBwKEPG_.js +1 -0
  237. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBwKEPG_.js +1 -0
  238. package/web-shell/assets/{cose-bilkent-JH36ORCC-CEq9XMDz.js → cose-bilkent-JH36ORCC-C12GhrmQ.js} +1 -1
  239. package/web-shell/assets/{cynefin-OW5HDTMX-3oDMxKvV.js → cynefin-OW5HDTMX-B1PlOkHW.js} +1 -1
  240. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-yGJvzOyq.js → cynefinDiagram-5FMLGOSQ-DqlIu1-5.js} +1 -1
  241. package/web-shell/assets/{dagre-3AP2YEHR-aeyZyzOG.js → dagre-3AP2YEHR-jwha3DyI.js} +1 -1
  242. package/web-shell/assets/{diagram-S7CK7UJ4-BAAcB3gC.js → diagram-S7CK7UJ4-WJo7RwdL.js} +1 -1
  243. package/web-shell/assets/{diagram-UQ7AKVKN-B1_QGLRY.js → diagram-UQ7AKVKN-HNgwz504.js} +1 -1
  244. package/web-shell/assets/{diagram-VSXAHHWV-BiBpaCap.js → diagram-VSXAHHWV-CnSKwatX.js} +1 -1
  245. package/web-shell/assets/{diagram-VX7I27RA-BUzzHihe.js → diagram-VX7I27RA-Bl2_wm4a.js} +1 -1
  246. package/web-shell/assets/{diagram-Z3DM3KII-6JxaEF1R.js → diagram-Z3DM3KII-C-h8dvnx.js} +1 -1
  247. package/web-shell/assets/{ebnfDiagram-PWID7BFC-D1-6Yjiz.js → ebnfDiagram-PWID7BFC-xPu9lOPC.js} +1 -1
  248. package/web-shell/assets/{erDiagram-SSCWMZ5O-DpcEbarm.js → erDiagram-SSCWMZ5O-lL-N4ln4.js} +1 -1
  249. package/web-shell/assets/{flowDiagram-A5DVABFB-DlRnvlQ3.js → flowDiagram-A5DVABFB-DzBl_JGY.js} +1 -1
  250. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-DABNtKOf.js → ganttDiagram-EL5Y4UJY-CaDwMjwZ.js} +1 -1
  251. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Bpq0tIqs.js → gitGraphDiagram-WWUBYQGX-DieKNHv6.js} +1 -1
  252. package/web-shell/assets/{index-Bm3BviDi.js → index-B8kdqIl5.js} +1 -1
  253. package/web-shell/assets/{index-Bjv2-WpQ.js → index-Dh9PvEFA.js} +3 -3
  254. package/web-shell/assets/{infoDiagram-RXCK75RN-D7e7VPRa.js → infoDiagram-RXCK75RN-DAavpH0B.js} +1 -1
  255. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BlOJr8s3.js → ishikawaDiagram-5VMMS53U-UPSFQgsr.js} +1 -1
  256. package/web-shell/assets/{journeyDiagram-EYS64GPL-BJOqE-Ku.js → journeyDiagram-EYS64GPL-tatKO6kZ.js} +1 -1
  257. package/web-shell/assets/{kanban-definition-3QL26DDD-9Jp1HpGG.js → kanban-definition-3QL26DDD-DQVeuSX5.js} +1 -1
  258. package/web-shell/assets/{layout-BXGcWPmh.js → layout-CRt7C8gi.js} +1 -1
  259. package/web-shell/assets/{linear-Bb-3dQRR.js → linear-CtupaiXZ.js} +1 -1
  260. package/web-shell/assets/{mermaid.core-BQ9PYOoO.js → mermaid.core-Pq6FiKYN.js} +6 -6
  261. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BbRVue0a.js → mindmap-definition-FBJOCRG2-C3aBV9q4.js} +1 -1
  262. package/web-shell/assets/{pegDiagram-XKGWAZYB-CLALfcXo.js → pegDiagram-XKGWAZYB-DPC6gXxQ.js} +1 -1
  263. package/web-shell/assets/{pieDiagram-E7YTZNPT-BPa_8owh.js → pieDiagram-E7YTZNPT-Bnulswji.js} +1 -1
  264. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-DTMPh3lk.js → quadrantDiagram-AXDQQJYC-CgN1vgtM.js} +1 -1
  265. package/web-shell/assets/{railroadDiagram-O6MQD6OU-CTqUx3sg.js → railroadDiagram-O6MQD6OU-XdwHEwkM.js} +1 -1
  266. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BMfxMhwk.js → requirementDiagram-EFPCY7ZU-BrptICwx.js} +1 -1
  267. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-ciGAnluT.js → sankeyDiagram-P5KCCOFB-UVmNE7OK.js} +1 -1
  268. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-D6eZeHbE.js → sequenceDiagram-WJ2MYXX4-CbLJdOim.js} +1 -1
  269. package/web-shell/assets/{sizeCapture-X5ZJPWSS-DQPYzdVi.js → sizeCapture-X5ZJPWSS-DHeZCcKI.js} +1 -1
  270. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DkqKm2SL.js → stateDiagram-HBIQ2CUA-oYkdhZ_G.js} +1 -1
  271. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-DbneQiPu.js +1 -0
  272. package/web-shell/assets/{swimlanes-XN3QIQJK-C6XGW_tM.js → swimlanes-XN3QIQJK-CFK29lSu.js} +1 -1
  273. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DxcqGRuT.js +8 -0
  274. package/web-shell/assets/{timeline-definition-24CTP7MA-CExT5Nqx.js → timeline-definition-24CTP7MA-BfAZG1ah.js} +1 -1
  275. package/web-shell/assets/{vennDiagram-4TSXK5OY-DYNNQGHI.js → vennDiagram-4TSXK5OY-x129VjoM.js} +1 -1
  276. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-py3CuGuQ.js → wardleyDiagram-VM6X3IG4-B5aBvbvt.js} +1 -1
  277. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CI5rcSdT.js → xychartDiagram-S5SC5T6Z-DLbk6hf2.js} +1 -1
  278. package/web-shell/index.html +1 -1
  279. package/web-shell/sw.js +1 -1
  280. package/web-shell/assets/channel-QDRh2gO3.js +0 -1
  281. package/web-shell/assets/classDiagram-DTDB5LWJ-CjY5Knq0.js +0 -1
  282. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CjY5Knq0.js +0 -1
  283. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BDHScdF2.js +0 -1
  284. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-CftAjGJO.js +0 -8
@@ -0,0 +1,2405 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import {
4
+ AGENT_VIEW_WORKER_ENV_KEYS,
5
+ bridgeAgentViewTerminal
6
+ } from "./chunk-LRHUT6ZW.js";
7
+ import {
8
+ atomicWriteFile
9
+ } from "./chunk-EPJAMNLS.js";
10
+ import {
11
+ Storage
12
+ } from "./chunk-S3HSUBBN.js";
13
+ import {
14
+ init_esbuild_shims
15
+ } from "./chunk-S2467S6L.js";
16
+ import {
17
+ __name
18
+ } from "./chunk-J2S4EL5Y.js";
19
+
20
+ // packages/cli/src/agent-view/pty-host-process.ts
21
+ init_esbuild_shims();
22
+ import { spawn } from "node:child_process";
23
+ import {
24
+ accessSync,
25
+ closeSync,
26
+ constants as fsConstants,
27
+ lstatSync,
28
+ openSync,
29
+ statSync
30
+ } from "node:fs";
31
+ import * as fs3 from "node:fs/promises";
32
+ import * as net from "node:net";
33
+ import * as os from "node:os";
34
+ import * as path3 from "node:path";
35
+ import { createHash as createHash2, randomUUID, timingSafeEqual } from "node:crypto";
36
+
37
+ // packages/cli/src/agent-view/pty-host-env.ts
38
+ init_esbuild_shims();
39
+ var PTY_HOST_AUTH_TOKEN_ENV = "O1CODE_AGENT_VIEW_PTY_HOST_TOKEN";
40
+ var PTY_HOST_ID_ENV = "O1CODE_AGENT_VIEW_PTY_HOST_ID";
41
+
42
+ // packages/cli/src/agent-view/pty-host.ts
43
+ init_esbuild_shims();
44
+ import { StringDecoder } from "node:string_decoder";
45
+ var DEFAULT_AGENT_VIEW_PTY_OUTPUT_BYTES = 1024 * 1024;
46
+ var INTERNAL_ONLY_WORKER_ENV_KEYS = /* @__PURE__ */ new Set([
47
+ PTY_HOST_AUTH_TOKEN_ENV,
48
+ PTY_HOST_ID_ENV,
49
+ "TMUX",
50
+ "TMUX_PANE",
51
+ "STY",
52
+ "WINDOW",
53
+ "WINDOWID",
54
+ "TERMCAP",
55
+ "COLUMNS",
56
+ "LINES",
57
+ "NO_COLOR",
58
+ "FORCE_COLOR",
59
+ "CI"
60
+ ]);
61
+ var AgentViewPtyUnavailableError = class extends Error {
62
+ static {
63
+ __name(this, "AgentViewPtyUnavailableError");
64
+ }
65
+ constructor() {
66
+ super("Agent View PTY is unavailable in this runtime.");
67
+ this.name = "AgentViewPtyUnavailableError";
68
+ }
69
+ };
70
+ var AgentViewLaunchConfigError = class extends Error {
71
+ constructor(errors) {
72
+ super(`Invalid Agent View launch config: ${errors.join("; ")}`);
73
+ this.errors = errors;
74
+ this.name = "AgentViewLaunchConfigError";
75
+ }
76
+ static {
77
+ __name(this, "AgentViewLaunchConfigError");
78
+ }
79
+ };
80
+ var BoundedOutputRing = class _BoundedOutputRing {
81
+ constructor(maxBytes = DEFAULT_AGENT_VIEW_PTY_OUTPUT_BYTES) {
82
+ this.maxBytes = maxBytes;
83
+ if (!Number.isInteger(maxBytes) || maxBytes < 1) {
84
+ throw new RangeError("maxBytes must be a positive integer");
85
+ }
86
+ }
87
+ static {
88
+ __name(this, "BoundedOutputRing");
89
+ }
90
+ static MAX_CHUNK_BYTES = 8192;
91
+ chunks = [];
92
+ retainedBytesValue = 0;
93
+ totalBytesValue = 0;
94
+ get retainedBytes() {
95
+ return this.retainedBytesValue;
96
+ }
97
+ get totalBytes() {
98
+ return this.totalBytesValue;
99
+ }
100
+ get droppedBytes() {
101
+ return this.totalBytesValue - this.retainedBytesValue;
102
+ }
103
+ append(data) {
104
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, "utf8");
105
+ this.totalBytesValue += chunk.byteLength;
106
+ if (chunk.byteLength >= this.maxBytes) {
107
+ const retained = trimUtf8Start(
108
+ Buffer.from(chunk.subarray(chunk.byteLength - this.maxBytes))
109
+ );
110
+ this.chunks = [retained];
111
+ this.retainedBytesValue = retained.byteLength;
112
+ return;
113
+ }
114
+ this.appendChunk(chunk);
115
+ this.retainedBytesValue += chunk.byteLength;
116
+ this.trim();
117
+ }
118
+ toBuffer() {
119
+ return Buffer.concat(this.chunks, this.retainedBytesValue);
120
+ }
121
+ toString(encoding = "utf8") {
122
+ return this.toBuffer().toString(encoding);
123
+ }
124
+ trim() {
125
+ let trimmed = false;
126
+ while (this.retainedBytesValue > this.maxBytes) {
127
+ trimmed = true;
128
+ const excess = this.retainedBytesValue - this.maxBytes;
129
+ const first = this.chunks[0];
130
+ if (!first) {
131
+ this.retainedBytesValue = 0;
132
+ return;
133
+ }
134
+ if (first.byteLength <= excess) {
135
+ this.chunks.shift();
136
+ this.retainedBytesValue -= first.byteLength;
137
+ } else {
138
+ const retained = trimUtf8Start(first.subarray(excess));
139
+ if (retained.byteLength === 0) {
140
+ this.chunks.shift();
141
+ } else {
142
+ this.chunks[0] = retained;
143
+ }
144
+ this.retainedBytesValue -= first.byteLength - retained.byteLength;
145
+ }
146
+ }
147
+ if (trimmed) this.trimLeadingUtf8ContinuationBytes();
148
+ }
149
+ appendChunk(chunk) {
150
+ const previous = this.chunks[this.chunks.length - 1];
151
+ if (previous && previous.byteLength + chunk.byteLength <= _BoundedOutputRing.MAX_CHUNK_BYTES) {
152
+ this.chunks[this.chunks.length - 1] = Buffer.concat([previous, chunk]);
153
+ return;
154
+ }
155
+ this.chunks.push(chunk);
156
+ }
157
+ trimLeadingUtf8ContinuationBytes() {
158
+ while (this.chunks.length > 0) {
159
+ const first = this.chunks[0];
160
+ const retained = trimUtf8Start(first);
161
+ if (retained.byteLength === first.byteLength) {
162
+ return;
163
+ }
164
+ if (retained.byteLength === 0) {
165
+ this.chunks.shift();
166
+ } else {
167
+ this.chunks[0] = retained;
168
+ }
169
+ this.retainedBytesValue -= first.byteLength - retained.byteLength;
170
+ if (retained.byteLength > 0) return;
171
+ }
172
+ }
173
+ };
174
+ function trimUtf8Start(buffer) {
175
+ let offset = 0;
176
+ while (offset < buffer.byteLength && isUtf8ContinuationByte(buffer[offset])) {
177
+ offset++;
178
+ }
179
+ return offset === 0 ? buffer : buffer.subarray(offset);
180
+ }
181
+ __name(trimUtf8Start, "trimUtf8Start");
182
+ function isUtf8ContinuationByte(value) {
183
+ return value >= 128 && value <= 191;
184
+ }
185
+ __name(isUtf8ContinuationByte, "isUtf8ContinuationByte");
186
+ async function loadAgentViewPty() {
187
+ if ("bun" in process.versions) {
188
+ return null;
189
+ }
190
+ const lydell = await importPty("@lydell/node-pty", "lydell-node-pty");
191
+ if (lydell) {
192
+ return lydell;
193
+ }
194
+ return importPty("node-pty", "node-pty");
195
+ }
196
+ __name(loadAgentViewPty, "loadAgentViewPty");
197
+ function validateAgentViewLaunchConfig(value) {
198
+ const errors = [];
199
+ if (!isRecord(value)) {
200
+ return { ok: false, errors: ["launch config must be an object"] };
201
+ }
202
+ requireLiteral(value, "schemaVersion", 1, errors);
203
+ requireNonEmptyString(value, "sessionId", errors);
204
+ requireStringArray(value, "argv", errors, { nonEmpty: true });
205
+ requireStringRecord(value, "env", errors);
206
+ requireNonEmptyString(value, "entrypoint", errors);
207
+ requireNonEmptyString(value, "projectCwd", errors);
208
+ requireNonEmptyString(value, "activeCwd", errors);
209
+ requireStringArray(value, "includeDirectories", errors);
210
+ validateOptionalString(value, "model", errors);
211
+ validateOptionalString(value, "approvalMode", errors);
212
+ validateOptionalString(value, "sandbox", errors);
213
+ validateOptionalString(value, "initialPrompt", errors);
214
+ validateOptionalString(value, "settingsDigest", errors);
215
+ validateOptionalString(value, "mcpDigest", errors);
216
+ validateTerminal(value["terminal"], errors);
217
+ if (errors.length > 0) {
218
+ return { ok: false, errors };
219
+ }
220
+ return { ok: true, launch: value };
221
+ }
222
+ __name(validateAgentViewLaunchConfig, "validateAgentViewLaunchConfig");
223
+ async function launchAgentViewPtyHost(rawLaunch, options = {}) {
224
+ const validation = validateAgentViewLaunchConfig(rawLaunch);
225
+ if (!validation.ok) {
226
+ throw new AgentViewLaunchConfigError(validation.errors);
227
+ }
228
+ const pty = options.pty === void 0 ? await (options.loadPty ?? loadAgentViewPty)() : options.pty;
229
+ if (!pty) {
230
+ throw new AgentViewPtyUnavailableError();
231
+ }
232
+ const launch = validation.launch;
233
+ const command = options.fakeCommand ?? launch.argv;
234
+ validateCommand(command);
235
+ const output = new BoundedOutputRing(
236
+ options.maxOutputBytes ?? DEFAULT_AGENT_VIEW_PTY_OUTPUT_BYTES
237
+ );
238
+ const inheritedEnv = stringProcessEnv(process.env);
239
+ for (const key of AGENT_VIEW_WORKER_ENV_KEYS) {
240
+ delete inheritedEnv[key];
241
+ }
242
+ const term = launch.env["TERM"] || "xterm-256color";
243
+ const workerEnv = {
244
+ ...inheritedEnv,
245
+ ...launch.env,
246
+ TERM: term
247
+ };
248
+ for (const key of INTERNAL_ONLY_WORKER_ENV_KEYS) {
249
+ delete workerEnv[key];
250
+ }
251
+ const ptyProcess = pty.module.spawn(command[0], command.slice(1), {
252
+ cwd: launch.activeCwd,
253
+ name: term,
254
+ cols: launch.terminal.columns,
255
+ rows: launch.terminal.rows,
256
+ env: workerEnv,
257
+ handleFlowControl: false,
258
+ // Windows: the inbox ConPTY backend orphans a `conhost.exe --headless`
259
+ // per natural worker exit (microsoft/node-pty#965); the bundled backend
260
+ // releases its host reference right after spawn.
261
+ useConptyDll: process.platform === "win32"
262
+ });
263
+ let inputDecoder = new StringDecoder("utf8");
264
+ const disposables = [];
265
+ let settled = false;
266
+ let resolveExit = /* @__PURE__ */ __name(() => {
267
+ }, "resolveExit");
268
+ const resolveExitOnce = /* @__PURE__ */ __name((exit) => {
269
+ if (settled) return;
270
+ settled = true;
271
+ resolveExit(exit);
272
+ }, "resolveExitOnce");
273
+ const dataDisposable = ptyProcess.onData((data) => {
274
+ output.append(data);
275
+ });
276
+ if (dataDisposable) {
277
+ disposables.push(dataDisposable);
278
+ }
279
+ const exited = new Promise((resolve3) => {
280
+ resolveExit = resolve3;
281
+ const exitDisposable = ptyProcess.onExit((event) => {
282
+ resolveExitOnce({ kind: "exited", ...event });
283
+ });
284
+ if (exitDisposable) {
285
+ disposables.push(exitDisposable);
286
+ }
287
+ });
288
+ if (process.platform === "win32" || options.isWorkerProcessAlive) {
289
+ const isAlive = options.isWorkerProcessAlive ?? isProcessAlive;
290
+ const exitPoll = setInterval(() => {
291
+ if (!settled && !isAlive(ptyProcess.pid)) {
292
+ resolveExitOnce({ kind: "exited", exitCode: 1 });
293
+ }
294
+ }, options.exitPollMs ?? 1e3);
295
+ exitPoll.unref?.();
296
+ void exited.then(() => clearInterval(exitPoll));
297
+ }
298
+ return {
299
+ pid: process.pid,
300
+ workerPid: ptyProcess.pid,
301
+ command: [...command],
302
+ output,
303
+ exited,
304
+ write(data) {
305
+ ptyProcess.write(inputDecoder.write(data));
306
+ },
307
+ onData(callback) {
308
+ return ptyProcess.onData(callback);
309
+ },
310
+ resize(size) {
311
+ ptyProcess.resize(size.columns, size.rows);
312
+ },
313
+ kill(signal) {
314
+ ptyProcess.kill(process.platform === "win32" ? void 0 : signal);
315
+ },
316
+ pause() {
317
+ ptyProcess.pause?.();
318
+ },
319
+ resume() {
320
+ ptyProcess.resume?.();
321
+ },
322
+ shutdown() {
323
+ ptyProcess.kill(process.platform === "win32" ? void 0 : "SIGTERM");
324
+ },
325
+ resetInput() {
326
+ inputDecoder = new StringDecoder("utf8");
327
+ },
328
+ dispose() {
329
+ ptyProcess.kill(process.platform === "win32" ? void 0 : "SIGTERM");
330
+ resolveExitOnce({ kind: "unreachable" });
331
+ for (const disposable of disposables.splice(0)) {
332
+ disposable.dispose();
333
+ }
334
+ }
335
+ };
336
+ }
337
+ __name(launchAgentViewPtyHost, "launchAgentViewPtyHost");
338
+ function isProcessAlive(pid) {
339
+ try {
340
+ process.kill(pid, 0);
341
+ return true;
342
+ } catch (error) {
343
+ return error.code !== "ESRCH";
344
+ }
345
+ }
346
+ __name(isProcessAlive, "isProcessAlive");
347
+ async function importPty(specifier, name) {
348
+ try {
349
+ const module = await import(specifier);
350
+ const ptyModule = asPtyModule(module);
351
+ return ptyModule ? { module: ptyModule, name } : null;
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+ __name(importPty, "importPty");
357
+ function asPtyModule(module) {
358
+ if (!isRecord(module) || typeof module["spawn"] !== "function") {
359
+ return void 0;
360
+ }
361
+ return module;
362
+ }
363
+ __name(asPtyModule, "asPtyModule");
364
+ function validateCommand(command) {
365
+ if (command.length === 0 || command.some((part) => part.length === 0)) {
366
+ throw new AgentViewLaunchConfigError([
367
+ "command must contain at least one non-empty string"
368
+ ]);
369
+ }
370
+ }
371
+ __name(validateCommand, "validateCommand");
372
+ function stringProcessEnv(env) {
373
+ return Object.fromEntries(
374
+ Object.entries(env).filter(
375
+ (entry) => typeof entry[1] === "string"
376
+ )
377
+ );
378
+ }
379
+ __name(stringProcessEnv, "stringProcessEnv");
380
+ function isRecord(value) {
381
+ return value !== null && typeof value === "object" && !Array.isArray(value);
382
+ }
383
+ __name(isRecord, "isRecord");
384
+ function requireLiteral(record, key, expected, errors) {
385
+ if (record[key] !== expected) {
386
+ errors.push(`${key} must be ${String(expected)}`);
387
+ }
388
+ }
389
+ __name(requireLiteral, "requireLiteral");
390
+ function requireNonEmptyString(record, key, errors) {
391
+ if (typeof record[key] !== "string" || record[key].length === 0) {
392
+ errors.push(`${key} must be a non-empty string`);
393
+ }
394
+ }
395
+ __name(requireNonEmptyString, "requireNonEmptyString");
396
+ function validateOptionalString(record, key, errors) {
397
+ if (record[key] !== void 0 && typeof record[key] !== "string") {
398
+ errors.push(`${key} must be a string when present`);
399
+ }
400
+ }
401
+ __name(validateOptionalString, "validateOptionalString");
402
+ function requireStringArray(record, key, errors, options = {}) {
403
+ const value = record[key];
404
+ if (!Array.isArray(value)) {
405
+ errors.push(`${key} must be an array of strings`);
406
+ return;
407
+ }
408
+ if (options.nonEmpty && value.length === 0) {
409
+ errors.push(`${key} must not be empty`);
410
+ }
411
+ if (value.some((item) => typeof item !== "string")) {
412
+ errors.push(`${key} must contain only strings`);
413
+ }
414
+ }
415
+ __name(requireStringArray, "requireStringArray");
416
+ function requireStringRecord(record, key, errors) {
417
+ const value = record[key];
418
+ if (!isRecord(value)) {
419
+ errors.push(`${key} must be an object with string values`);
420
+ return;
421
+ }
422
+ if (Object.values(value).some((item) => typeof item !== "string")) {
423
+ errors.push(`${key} must contain only string values`);
424
+ }
425
+ }
426
+ __name(requireStringRecord, "requireStringRecord");
427
+ function validateTerminal(value, errors) {
428
+ if (!isRecord(value)) {
429
+ errors.push("terminal must be an object");
430
+ return;
431
+ }
432
+ if (!isPositiveInteger(value["columns"])) {
433
+ errors.push("terminal.columns must be a positive integer");
434
+ }
435
+ if (!isPositiveInteger(value["rows"])) {
436
+ errors.push("terminal.rows must be a positive integer");
437
+ }
438
+ }
439
+ __name(validateTerminal, "validateTerminal");
440
+ function isPositiveInteger(value) {
441
+ return Number.isInteger(value) && Number(value) > 0;
442
+ }
443
+ __name(isPositiveInteger, "isPositiveInteger");
444
+
445
+ // packages/cli/src/agent-view/supervisor-store.ts
446
+ init_esbuild_shims();
447
+ import * as fs from "node:fs/promises";
448
+ import * as path from "node:path";
449
+ import { createHash } from "node:crypto";
450
+ var rosterMutationQueues = /* @__PURE__ */ new Map();
451
+ var stateMutationQueues = /* @__PURE__ */ new Map();
452
+ var activityMutationQueues = /* @__PURE__ */ new Map();
453
+ var workerMutationQueues = /* @__PURE__ */ new Map();
454
+ function getAgentViewStorePaths(options = {}) {
455
+ const globalDir = options.globalDir ?? Storage.getGlobalO1CodeDir();
456
+ const daemonDir = path.join(globalDir, "daemon");
457
+ return {
458
+ globalDir,
459
+ daemonDir,
460
+ rosterPath: path.join(daemonDir, "roster.json"),
461
+ supervisorPath: path.join(daemonDir, "supervisor.json"),
462
+ daemonLogPath: path.join(daemonDir, "daemon.log"),
463
+ jobsDir: path.join(globalDir, "jobs")
464
+ };
465
+ }
466
+ __name(getAgentViewStorePaths, "getAgentViewStorePaths");
467
+ function getAgentViewSessionPaths(sessionId, options = {}) {
468
+ const safeId = sanitizeSessionId(sessionId);
469
+ const sessionDir = path.join(getAgentViewStorePaths(options).jobsDir, safeId);
470
+ return {
471
+ sessionDir,
472
+ statePath: path.join(sessionDir, "state.json"),
473
+ launchPath: path.join(sessionDir, "launch.json"),
474
+ activityPath: path.join(sessionDir, "activity.json"),
475
+ workerPath: path.join(sessionDir, "worker.json"),
476
+ tmpDir: path.join(sessionDir, "tmp")
477
+ };
478
+ }
479
+ __name(getAgentViewSessionPaths, "getAgentViewSessionPaths");
480
+ async function readAgentViewRoster(options = {}) {
481
+ const raw = await readJsonRecord(getAgentViewStorePaths(options).rosterPath);
482
+ return normalizeRoster(raw);
483
+ }
484
+ __name(readAgentViewRoster, "readAgentViewRoster");
485
+ async function readAgentViewRosterForWrite(options = {}) {
486
+ return readAgentViewRosterStrict(options);
487
+ }
488
+ __name(readAgentViewRosterForWrite, "readAgentViewRosterForWrite");
489
+ async function readAgentViewRosterStrict(options = {}) {
490
+ const rosterPath = getAgentViewStorePaths(options).rosterPath;
491
+ let text;
492
+ try {
493
+ text = await fs.readFile(rosterPath, "utf8");
494
+ } catch (error) {
495
+ if (isNodeError(error) && error.code === "ENOENT") {
496
+ return normalizeRoster(void 0);
497
+ }
498
+ throw error;
499
+ }
500
+ let parsed;
501
+ try {
502
+ parsed = JSON.parse(text);
503
+ } catch (error) {
504
+ throw new Error(`Agent View roster at ${rosterPath} is corrupt.`, {
505
+ cause: error
506
+ });
507
+ }
508
+ if (!isRecord2(parsed)) {
509
+ throw new Error(`Agent View roster at ${rosterPath} is not a JSON object.`);
510
+ }
511
+ if (!Array.isArray(parsed["sessions"])) {
512
+ throw new Error(
513
+ `Agent View roster at ${rosterPath} has no sessions array.`
514
+ );
515
+ }
516
+ for (const entry of parsed["sessions"]) {
517
+ if (isRecord2(entry) && "pinned" in entry && typeof entry["pinned"] !== "boolean") {
518
+ throw new Error(
519
+ `Agent View roster at ${rosterPath} has a non-boolean pinned field.`
520
+ );
521
+ }
522
+ }
523
+ const roster = normalizeRoster(parsed);
524
+ if (roster.sessions.length !== parsed["sessions"].length) {
525
+ throw new Error(
526
+ `Agent View roster at ${rosterPath} has incomplete session entries.`
527
+ );
528
+ }
529
+ return roster;
530
+ }
531
+ __name(readAgentViewRosterStrict, "readAgentViewRosterStrict");
532
+ async function writeAgentViewRoster(roster, options = {}) {
533
+ await writeJsonFile(getAgentViewStorePaths(options).rosterPath, roster);
534
+ }
535
+ __name(writeAgentViewRoster, "writeAgentViewRoster");
536
+ async function upsertAgentViewRosterEntry(entry, options = {}) {
537
+ return mutateAgentViewRoster(options, async () => {
538
+ const roster = await readAgentViewRosterForWrite(options);
539
+ const entryKey = sanitizeSessionId(entry.sessionId);
540
+ const sessions = roster.sessions.filter(
541
+ (item) => sanitizeSessionId(item.sessionId) !== entryKey
542
+ );
543
+ const existing = roster.sessions.find(
544
+ (item) => sanitizeSessionId(item.sessionId) === entryKey
545
+ );
546
+ const updated = {
547
+ ...existing,
548
+ ...entry
549
+ };
550
+ const next = {
551
+ ...roster,
552
+ schemaVersion: 1,
553
+ updatedAt: entry.updatedAt,
554
+ sessions: [...sessions, updated].sort(compareRosterEntries)
555
+ };
556
+ await writeAgentViewRoster(next, options);
557
+ return next;
558
+ });
559
+ }
560
+ __name(upsertAgentViewRosterEntry, "upsertAgentViewRosterEntry");
561
+ async function removeAgentViewRosterEntry(sessionId, options = {}) {
562
+ return mutateAgentViewRoster(options, async () => {
563
+ const roster = await readAgentViewRosterForWrite(options);
564
+ const sessionKey = sanitizeSessionId(sessionId);
565
+ const now = (/* @__PURE__ */ new Date()).toISOString();
566
+ const next = {
567
+ ...roster,
568
+ schemaVersion: 1,
569
+ updatedAt: now,
570
+ sessions: roster.sessions.filter(
571
+ (item) => sanitizeSessionId(item.sessionId) !== sessionKey
572
+ )
573
+ };
574
+ await writeAgentViewRoster(next, options);
575
+ return next;
576
+ });
577
+ }
578
+ __name(removeAgentViewRosterEntry, "removeAgentViewRosterEntry");
579
+ async function updateAgentViewRosterEntry(sessionId, update, options = {}) {
580
+ return mutateAgentViewRoster(options, async () => {
581
+ const roster = await readAgentViewRosterForWrite(options);
582
+ const sessionKey = sanitizeSessionId(sessionId);
583
+ const existing = roster.sessions.find(
584
+ (entry) => sanitizeSessionId(entry.sessionId) === sessionKey
585
+ );
586
+ if (!existing) return void 0;
587
+ const updated = update(existing);
588
+ const sessions = roster.sessions.filter(
589
+ (entry) => sanitizeSessionId(entry.sessionId) !== sessionKey
590
+ );
591
+ const next = {
592
+ ...roster,
593
+ schemaVersion: 1,
594
+ updatedAt: updated.updatedAt,
595
+ sessions: [...sessions, updated].sort(compareRosterEntries)
596
+ };
597
+ await writeAgentViewRoster(next, options);
598
+ return updated;
599
+ });
600
+ }
601
+ __name(updateAgentViewRosterEntry, "updateAgentViewRosterEntry");
602
+ async function readAgentViewSessionState(sessionId, options = {}) {
603
+ const paths = getAgentViewSessionPaths(sessionId, options);
604
+ const raw = await readJsonRecord(paths.statePath);
605
+ return normalizeSessionState(raw, path.basename(paths.sessionDir));
606
+ }
607
+ __name(readAgentViewSessionState, "readAgentViewSessionState");
608
+ async function writeAgentViewSessionState(state, options = {}) {
609
+ return mutateAgentViewState(state.sessionId, options, async () => {
610
+ const paths = getAgentViewSessionPaths(state.sessionId, options);
611
+ const existing = await readJsonRecordForWrite(paths.statePath);
612
+ await writeJsonFile(paths.statePath, {
613
+ ...existing,
614
+ ...state,
615
+ schemaVersion: 1
616
+ });
617
+ await fs.mkdir(paths.tmpDir, { recursive: true });
618
+ });
619
+ }
620
+ __name(writeAgentViewSessionState, "writeAgentViewSessionState");
621
+ async function patchAgentViewSessionState(sessionId, patch, options = {}) {
622
+ return mutateAgentViewState(sessionId, options, async () => {
623
+ const paths = getAgentViewSessionPaths(sessionId, options);
624
+ const existing = await readJsonRecordForWrite(paths.statePath);
625
+ if (existing === void 0) {
626
+ return;
627
+ }
628
+ await writeJsonFile(paths.statePath, {
629
+ ...existing,
630
+ ...patch,
631
+ schemaVersion: 1
632
+ });
633
+ await fs.mkdir(paths.tmpDir, { recursive: true });
634
+ });
635
+ }
636
+ __name(patchAgentViewSessionState, "patchAgentViewSessionState");
637
+ async function patchAgentViewSessionStateIf(sessionId, decidePatch, options = {}) {
638
+ let applied = false;
639
+ await mutateAgentViewState(sessionId, options, async () => {
640
+ const paths = getAgentViewSessionPaths(sessionId, options);
641
+ const existing = await readJsonRecordForConditionalWrite(paths.statePath);
642
+ if (existing === void 0) {
643
+ return;
644
+ }
645
+ const normalized = normalizeSessionState(existing, sessionId);
646
+ if (normalized === void 0) {
647
+ throw new Error(
648
+ `Agent View session state at ${paths.statePath} is incomplete.`
649
+ );
650
+ }
651
+ const patch = decidePatch(normalized);
652
+ if (patch === void 0) {
653
+ return;
654
+ }
655
+ applied = true;
656
+ await writeJsonFile(paths.statePath, {
657
+ ...existing,
658
+ ...patch,
659
+ schemaVersion: 1
660
+ });
661
+ await fs.mkdir(paths.tmpDir, { recursive: true });
662
+ });
663
+ return applied;
664
+ }
665
+ __name(patchAgentViewSessionStateIf, "patchAgentViewSessionStateIf");
666
+ async function listAgentViewSessionStates(options = {}) {
667
+ const { jobsDir } = getAgentViewStorePaths(options);
668
+ let entries;
669
+ try {
670
+ entries = await fs.readdir(jobsDir);
671
+ } catch (error) {
672
+ if (isNodeError(error) && error.code === "ENOENT") {
673
+ return [];
674
+ }
675
+ throw error;
676
+ }
677
+ const states = await Promise.all(
678
+ entries.map((sessionId) => readAgentViewSessionState(sessionId, options))
679
+ );
680
+ return states.filter((state) => Boolean(state)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
681
+ }
682
+ __name(listAgentViewSessionStates, "listAgentViewSessionStates");
683
+ async function listAgentViewSessionSnapshots(options = {}) {
684
+ const states = await listAgentViewSessionStates(options);
685
+ const roster = await readAgentViewRoster(options);
686
+ const rosterEntries = new Map(
687
+ roster.sessions.map((entry) => [sanitizeSessionId(entry.sessionId), entry])
688
+ );
689
+ const snapshots = await Promise.all(
690
+ states.map(async (state) => {
691
+ const snapshot = {
692
+ sessionId: state.sessionId,
693
+ state,
694
+ rosterEntry: rosterEntries.get(sanitizeSessionId(state.sessionId))
695
+ };
696
+ if (state.ownership === "unmanaged") {
697
+ return snapshot;
698
+ }
699
+ return {
700
+ ...snapshot,
701
+ launch: redactAgentViewLaunch(
702
+ await readAgentViewLaunch(state.sessionId, options)
703
+ ),
704
+ activity: redactAgentViewActivity(
705
+ await readAgentViewActivity(state.sessionId, options)
706
+ ),
707
+ worker: redactAgentViewWorker(
708
+ await readAgentViewWorker(state.sessionId, options)
709
+ )
710
+ };
711
+ })
712
+ );
713
+ return snapshots.sort(
714
+ (left, right) => right.state.updatedAt.localeCompare(left.state.updatedAt)
715
+ );
716
+ }
717
+ __name(listAgentViewSessionSnapshots, "listAgentViewSessionSnapshots");
718
+ async function readAgentViewLaunch(sessionId, options = {}) {
719
+ const paths = getAgentViewSessionPaths(sessionId, options);
720
+ const raw = await readJsonRecord(paths.launchPath);
721
+ return normalizeLaunch(raw, path.basename(paths.sessionDir));
722
+ }
723
+ __name(readAgentViewLaunch, "readAgentViewLaunch");
724
+ async function writeAgentViewLaunch(launch, options = {}) {
725
+ const paths = getAgentViewSessionPaths(launch.sessionId, options);
726
+ const existing = await readJsonRecordForWrite(paths.launchPath);
727
+ await writeJsonFile(paths.launchPath, {
728
+ ...existing,
729
+ ...launch,
730
+ schemaVersion: 1
731
+ });
732
+ }
733
+ __name(writeAgentViewLaunch, "writeAgentViewLaunch");
734
+ async function readAgentViewActivity(sessionId, options = {}) {
735
+ const raw = await readJsonRecord(
736
+ getAgentViewSessionPaths(sessionId, options).activityPath
737
+ );
738
+ return normalizeActivity(raw);
739
+ }
740
+ __name(readAgentViewActivity, "readAgentViewActivity");
741
+ async function writeAgentViewActivity(sessionId, activity, options = {}) {
742
+ return mutateAgentViewActivity(sessionId, options, async () => {
743
+ const paths = getAgentViewSessionPaths(sessionId, options);
744
+ const existing = await readJsonRecordForWrite(paths.activityPath);
745
+ await writeJsonFile(paths.activityPath, {
746
+ ...existing,
747
+ ...activity,
748
+ schemaVersion: 1
749
+ });
750
+ });
751
+ }
752
+ __name(writeAgentViewActivity, "writeAgentViewActivity");
753
+ async function patchAgentViewActivityIf(sessionId, decidePatch, options = {}) {
754
+ let applied = false;
755
+ await mutateAgentViewActivity(sessionId, options, async () => {
756
+ const paths = getAgentViewSessionPaths(sessionId, options);
757
+ const existing = await readJsonRecordForWrite(paths.activityPath);
758
+ const normalized = normalizeActivity(existing);
759
+ if (normalized === void 0) {
760
+ return;
761
+ }
762
+ const patch = decidePatch(normalized);
763
+ if (patch === void 0) {
764
+ return;
765
+ }
766
+ applied = true;
767
+ await writeJsonFile(paths.activityPath, {
768
+ ...existing,
769
+ ...patch,
770
+ schemaVersion: 1
771
+ });
772
+ });
773
+ return applied;
774
+ }
775
+ __name(patchAgentViewActivityIf, "patchAgentViewActivityIf");
776
+ async function clearAgentViewWorkerPids(sessionId, options = {}) {
777
+ const paths = getAgentViewSessionPaths(sessionId, options);
778
+ await withMutationQueue(workerMutationQueues, paths.workerPath, async () => {
779
+ const existing = await readJsonRecordForWrite(paths.workerPath);
780
+ if (existing === void 0) {
781
+ return;
782
+ }
783
+ const next = { ...existing };
784
+ delete next["hostPid"];
785
+ delete next["workerPid"];
786
+ await writeJsonFile(paths.workerPath, { ...next, schemaVersion: 1 });
787
+ });
788
+ }
789
+ __name(clearAgentViewWorkerPids, "clearAgentViewWorkerPids");
790
+ function digestAgentViewWorkerToken(token) {
791
+ return createHash("sha256").update(token).digest("hex");
792
+ }
793
+ __name(digestAgentViewWorkerToken, "digestAgentViewWorkerToken");
794
+ async function readAgentViewWorker(sessionId, options = {}) {
795
+ const raw = await readJsonRecord(
796
+ getAgentViewSessionPaths(sessionId, options).workerPath
797
+ );
798
+ return normalizeWorker(raw);
799
+ }
800
+ __name(readAgentViewWorker, "readAgentViewWorker");
801
+ async function writeAgentViewWorker(sessionId, worker, options = {}) {
802
+ const paths = getAgentViewSessionPaths(sessionId, options);
803
+ await withMutationQueue(workerMutationQueues, paths.workerPath, async () => {
804
+ const existing = await readJsonRecordForWrite(paths.workerPath);
805
+ await writeJsonFile(paths.workerPath, {
806
+ ...existing,
807
+ ...worker,
808
+ schemaVersion: 1
809
+ });
810
+ });
811
+ }
812
+ __name(writeAgentViewWorker, "writeAgentViewWorker");
813
+ async function readAgentViewSupervisor(options = {}) {
814
+ const raw = await readJsonRecord(
815
+ getAgentViewStorePaths(options).supervisorPath
816
+ );
817
+ return normalizeSupervisor(raw);
818
+ }
819
+ __name(readAgentViewSupervisor, "readAgentViewSupervisor");
820
+ async function writeAgentViewSupervisor(supervisor, options = {}) {
821
+ const paths = getAgentViewStorePaths(options);
822
+ const existing = await readJsonRecordForWrite(paths.supervisorPath);
823
+ await writeJsonFile(paths.supervisorPath, {
824
+ ...existing,
825
+ ...supervisor,
826
+ schemaVersion: 1
827
+ });
828
+ }
829
+ __name(writeAgentViewSupervisor, "writeAgentViewSupervisor");
830
+ function sanitizeSessionId(sessionId) {
831
+ const safe = path.basename(sessionId.replace(/\\/g, "/")).toLowerCase().replace(/^\.+/g, "_").replace(/[<>:"|?*\x00-\x1F]/g, "_");
832
+ return safe || "_";
833
+ }
834
+ __name(sanitizeSessionId, "sanitizeSessionId");
835
+ function compareRosterEntries(left, right) {
836
+ if (Boolean(left.pinned) !== Boolean(right.pinned)) {
837
+ return left.pinned ? -1 : 1;
838
+ }
839
+ return right.updatedAt.localeCompare(left.updatedAt);
840
+ }
841
+ __name(compareRosterEntries, "compareRosterEntries");
842
+ async function readJsonRecord(filePath) {
843
+ try {
844
+ const text = await fs.readFile(filePath, "utf8");
845
+ const parsed = JSON.parse(text);
846
+ return isRecord2(parsed) ? parsed : void 0;
847
+ } catch {
848
+ return void 0;
849
+ }
850
+ }
851
+ __name(readJsonRecord, "readJsonRecord");
852
+ async function readJsonRecordForWrite(filePath) {
853
+ let text;
854
+ try {
855
+ text = await fs.readFile(filePath, "utf8");
856
+ } catch (error) {
857
+ if (isNodeError(error) && error.code === "ENOENT") {
858
+ return void 0;
859
+ }
860
+ throw error;
861
+ }
862
+ try {
863
+ const parsed = JSON.parse(text);
864
+ return isRecord2(parsed) ? parsed : void 0;
865
+ } catch {
866
+ return void 0;
867
+ }
868
+ }
869
+ __name(readJsonRecordForWrite, "readJsonRecordForWrite");
870
+ async function readJsonRecordForConditionalWrite(filePath) {
871
+ let text;
872
+ try {
873
+ text = await fs.readFile(filePath, "utf8");
874
+ } catch (error) {
875
+ if (isNodeError(error) && error.code === "ENOENT") {
876
+ return void 0;
877
+ }
878
+ throw error;
879
+ }
880
+ let parsed;
881
+ try {
882
+ parsed = JSON.parse(text);
883
+ } catch (error) {
884
+ throw new Error(`Agent View record at ${filePath} is corrupt.`, {
885
+ cause: error
886
+ });
887
+ }
888
+ if (!isRecord2(parsed)) {
889
+ throw new Error(`Agent View record at ${filePath} is not a JSON object.`);
890
+ }
891
+ return parsed;
892
+ }
893
+ __name(readJsonRecordForConditionalWrite, "readJsonRecordForConditionalWrite");
894
+ async function withMutationQueue(queues, key, action) {
895
+ const previous = queues.get(key) ?? Promise.resolve();
896
+ let release;
897
+ const gate = new Promise((resolve3) => {
898
+ release = resolve3;
899
+ });
900
+ const current = previous.catch(() => {
901
+ }).then(() => gate);
902
+ queues.set(key, current);
903
+ await previous.catch(() => {
904
+ });
905
+ try {
906
+ return await action();
907
+ } finally {
908
+ release();
909
+ if (queues.get(key) === current) {
910
+ queues.delete(key);
911
+ }
912
+ }
913
+ }
914
+ __name(withMutationQueue, "withMutationQueue");
915
+ async function mutateAgentViewRoster(options, action) {
916
+ return withMutationQueue(
917
+ rosterMutationQueues,
918
+ getAgentViewStorePaths(options).rosterPath,
919
+ action
920
+ );
921
+ }
922
+ __name(mutateAgentViewRoster, "mutateAgentViewRoster");
923
+ async function mutateAgentViewActivity(sessionId, options, action) {
924
+ return withMutationQueue(
925
+ activityMutationQueues,
926
+ getAgentViewSessionPaths(sessionId, options).activityPath,
927
+ action
928
+ );
929
+ }
930
+ __name(mutateAgentViewActivity, "mutateAgentViewActivity");
931
+ async function mutateAgentViewState(sessionId, options, action) {
932
+ return withMutationQueue(
933
+ stateMutationQueues,
934
+ getAgentViewSessionPaths(sessionId, options).statePath,
935
+ action
936
+ );
937
+ }
938
+ __name(mutateAgentViewState, "mutateAgentViewState");
939
+ async function writeJsonFile(filePath, value) {
940
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
941
+ await atomicWriteFile(filePath, `${JSON.stringify(value, null, 2)}
942
+ `, {
943
+ mode: 384,
944
+ forceMode: true,
945
+ noFollow: true
946
+ });
947
+ }
948
+ __name(writeJsonFile, "writeJsonFile");
949
+ function normalizeRoster(raw) {
950
+ const now = (/* @__PURE__ */ new Date()).toISOString();
951
+ const sessions = Array.isArray(raw?.["sessions"]) ? raw["sessions"].map(normalizeRosterEntry).filter((entry) => Boolean(entry)) : [];
952
+ return {
953
+ ...raw,
954
+ schemaVersion: 1,
955
+ updatedAt: stringValue(raw?.["updatedAt"]) ?? now,
956
+ sessions: sessions.sort(compareRosterEntries)
957
+ };
958
+ }
959
+ __name(normalizeRoster, "normalizeRoster");
960
+ function normalizeRosterEntry(value) {
961
+ if (!isRecord2(value)) return void 0;
962
+ const sessionId = stringValue(value["sessionId"]);
963
+ const projectCwd = stringValue(value["projectCwd"]);
964
+ const activeCwd = stringValue(value["activeCwd"]);
965
+ const createdAt = stringValue(value["createdAt"]);
966
+ const updatedAt = stringValue(value["updatedAt"]);
967
+ if (!sessionId || !projectCwd || !activeCwd || !createdAt || !updatedAt) {
968
+ return void 0;
969
+ }
970
+ return {
971
+ ...value,
972
+ sessionId,
973
+ projectCwd: path.resolve(projectCwd),
974
+ activeCwd: path.resolve(activeCwd),
975
+ displayName: stringValue(value["displayName"]),
976
+ pinned: typeof value["pinned"] === "boolean" ? value["pinned"] : void 0,
977
+ createdAt,
978
+ updatedAt
979
+ };
980
+ }
981
+ __name(normalizeRosterEntry, "normalizeRosterEntry");
982
+ function normalizeSessionState(raw, expectedSessionId) {
983
+ if (!raw) return void 0;
984
+ const sessionId = expectedSessionId || stringValue(raw["sessionId"]);
985
+ const projectCwd = stringValue(raw["projectCwd"]);
986
+ const originalCwd = stringValue(raw["originalCwd"]);
987
+ const activeCwd = stringValue(raw["activeCwd"]);
988
+ const createdAt = stringValue(raw["createdAt"]);
989
+ const updatedAt = stringValue(raw["updatedAt"]);
990
+ if (!sessionId || !projectCwd || !originalCwd || !activeCwd || !createdAt || !updatedAt) {
991
+ return void 0;
992
+ }
993
+ return {
994
+ ...raw,
995
+ schemaVersion: 1,
996
+ sessionId,
997
+ ownership: ownershipValue(raw["ownership"]),
998
+ sessionState: sessionStateValue(raw["sessionState"]),
999
+ processState: processStateValue(raw["processState"]),
1000
+ attachState: attachStateValue(raw["attachState"]),
1001
+ projectCwd: path.resolve(projectCwd),
1002
+ originalCwd: path.resolve(originalCwd),
1003
+ activeCwd: path.resolve(activeCwd),
1004
+ foregroundOwnerId: stringValue(raw["foregroundOwnerId"]),
1005
+ createdAt,
1006
+ updatedAt,
1007
+ worktree: isRecord2(raw["worktree"]) ? {
1008
+ ...raw["worktree"],
1009
+ mode: worktreeModeValue(raw["worktree"]["mode"])
1010
+ } : { mode: "none" }
1011
+ };
1012
+ }
1013
+ __name(normalizeSessionState, "normalizeSessionState");
1014
+ function normalizeLaunch(raw, expectedSessionId) {
1015
+ if (!raw) return void 0;
1016
+ const sessionId = expectedSessionId || stringValue(raw["sessionId"]);
1017
+ const entrypoint = stringValue(raw["entrypoint"]);
1018
+ const projectCwd = stringValue(raw["projectCwd"]);
1019
+ const activeCwd = stringValue(raw["activeCwd"]);
1020
+ if (!sessionId || !entrypoint || !projectCwd || !activeCwd) return void 0;
1021
+ return stripUndefined({
1022
+ ...raw,
1023
+ schemaVersion: 1,
1024
+ sessionId,
1025
+ argv: stringArrayValue(raw["argv"]),
1026
+ env: stringMapValue(raw["env"]),
1027
+ entrypoint,
1028
+ initialPrompt: stringValue(raw["initialPrompt"]),
1029
+ projectCwd: path.resolve(projectCwd),
1030
+ activeCwd: path.resolve(activeCwd),
1031
+ includeDirectories: stringArrayValue(raw["includeDirectories"]),
1032
+ terminal: terminalValue(raw["terminal"])
1033
+ });
1034
+ }
1035
+ __name(normalizeLaunch, "normalizeLaunch");
1036
+ function redactAgentViewLaunch(launch) {
1037
+ if (!launch) return void 0;
1038
+ return {
1039
+ ...launch,
1040
+ env: {}
1041
+ };
1042
+ }
1043
+ __name(redactAgentViewLaunch, "redactAgentViewLaunch");
1044
+ function normalizeActivity(raw) {
1045
+ if (!raw) return void 0;
1046
+ const lastActivityAt = stringValue(raw["lastActivityAt"]);
1047
+ if (!lastActivityAt) return void 0;
1048
+ return stripUndefined({
1049
+ ...raw,
1050
+ schemaVersion: 1,
1051
+ summary: stringValue(raw["summary"]),
1052
+ model: stringValue(raw["model"]),
1053
+ theme: raw["theme"] === "light" ? "light" : raw["theme"] === "dark" ? "dark" : void 0,
1054
+ language: stringValue(raw["language"]),
1055
+ dashboardRequestId: stringValue(raw["dashboardRequestId"]),
1056
+ waitingFor: stringValue(raw["waitingFor"]),
1057
+ inputKind: inputKindValue(raw["inputKind"]),
1058
+ lastResult: stringValue(raw["lastResult"]),
1059
+ queuedPromptCount: numberValue(raw["queuedPromptCount"]),
1060
+ queuedPromptPreview: stringValue(raw["queuedPromptPreview"]),
1061
+ queuedPromptId: stringValue(raw["queuedPromptId"]),
1062
+ queuedPromptText: stringValue(raw["queuedPromptText"]),
1063
+ queuedPromptDeliveredAt: stringValue(raw["queuedPromptDeliveredAt"]),
1064
+ lastQueuedPromptAt: stringValue(raw["lastQueuedPromptAt"]),
1065
+ lastActivityAt,
1066
+ capabilities: stringArrayValue(raw["capabilities"])
1067
+ });
1068
+ }
1069
+ __name(normalizeActivity, "normalizeActivity");
1070
+ function redactAgentViewActivity(activity) {
1071
+ if (!activity) return void 0;
1072
+ return stripUndefined({
1073
+ ...activity,
1074
+ queuedPromptId: void 0,
1075
+ queuedPromptText: void 0,
1076
+ queuedPromptDeliveredAt: void 0
1077
+ });
1078
+ }
1079
+ __name(redactAgentViewActivity, "redactAgentViewActivity");
1080
+ function redactAgentViewWorker(worker) {
1081
+ if (!worker) return void 0;
1082
+ return stripUndefined({
1083
+ ...worker,
1084
+ hostAuthToken: void 0
1085
+ });
1086
+ }
1087
+ __name(redactAgentViewWorker, "redactAgentViewWorker");
1088
+ function stripUndefined(value) {
1089
+ return Object.fromEntries(
1090
+ Object.entries(value).filter((entry) => entry[1] !== void 0)
1091
+ );
1092
+ }
1093
+ __name(stripUndefined, "stripUndefined");
1094
+ function normalizeWorker(raw) {
1095
+ if (!raw) return void 0;
1096
+ return {
1097
+ ...raw,
1098
+ schemaVersion: 1,
1099
+ hostPid: numberValue(raw["hostPid"]),
1100
+ workerPid: numberValue(raw["workerPid"]),
1101
+ endpoint: stringValue(raw["endpoint"]),
1102
+ hostEndpoint: stringValue(raw["hostEndpoint"]),
1103
+ hostAuthToken: stringValue(raw["hostAuthToken"]),
1104
+ hostId: stringValue(raw["hostId"]),
1105
+ tokenDigest: stringValue(raw["tokenDigest"]),
1106
+ lastHeartbeatAt: stringValue(raw["lastHeartbeatAt"]),
1107
+ protocolVersion: numberValue(raw["protocolVersion"]) ?? 1,
1108
+ platform: platformValue(raw["platform"]),
1109
+ recentOutputBytes: numberValue(raw["recentOutputBytes"]) ?? 0
1110
+ };
1111
+ }
1112
+ __name(normalizeWorker, "normalizeWorker");
1113
+ function normalizeSupervisor(raw) {
1114
+ if (!raw) return void 0;
1115
+ const pid = numberValue(raw["pid"]);
1116
+ const socketPath = stringValue(raw["socketPath"]);
1117
+ const authToken = stringValue(raw["authToken"]);
1118
+ const startedAt = stringValue(raw["startedAt"]);
1119
+ const updatedAt = stringValue(raw["updatedAt"]);
1120
+ if (!pid || !socketPath || !startedAt || !updatedAt) return void 0;
1121
+ return {
1122
+ ...raw,
1123
+ schemaVersion: 1,
1124
+ pid,
1125
+ socketPath,
1126
+ authToken,
1127
+ startedAt,
1128
+ updatedAt,
1129
+ protocolVersion: numberValue(raw["protocolVersion"]) ?? 1
1130
+ };
1131
+ }
1132
+ __name(normalizeSupervisor, "normalizeSupervisor");
1133
+ function ownershipValue(value) {
1134
+ return value === "unmanaged" || value === "adopting" || value === "managed" || value === "removing" ? value : "managed";
1135
+ }
1136
+ __name(ownershipValue, "ownershipValue");
1137
+ function isAgentViewSessionState(value) {
1138
+ return value === "starting" || value === "working" || value === "needs_input" || value === "idle" || value === "completed" || value === "stopped" || value === "failed";
1139
+ }
1140
+ __name(isAgentViewSessionState, "isAgentViewSessionState");
1141
+ function sessionStateValue(value) {
1142
+ return isAgentViewSessionState(value) ? value : "failed";
1143
+ }
1144
+ __name(sessionStateValue, "sessionStateValue");
1145
+ function processStateValue(value) {
1146
+ return value === "starting" || value === "alive" || value === "hibernating" || value === "hibernated" || value === "restarting" || value === "exited" ? value : "exited";
1147
+ }
1148
+ __name(processStateValue, "processStateValue");
1149
+ function attachStateValue(value) {
1150
+ return value === "attaching" || value === "attached" ? value : "detached";
1151
+ }
1152
+ __name(attachStateValue, "attachStateValue");
1153
+ function worktreeModeValue(value) {
1154
+ return value === "worktree" || value === "shared-unisolated" ? value : "none";
1155
+ }
1156
+ __name(worktreeModeValue, "worktreeModeValue");
1157
+ function inputKindValue(value) {
1158
+ return value === "blocking" || value === "soft" ? value : void 0;
1159
+ }
1160
+ __name(inputKindValue, "inputKindValue");
1161
+ function terminalValue(value) {
1162
+ if (!isRecord2(value)) return { columns: 80, rows: 24 };
1163
+ return {
1164
+ columns: numberValue(value["columns"]) ?? 80,
1165
+ rows: numberValue(value["rows"]) ?? 24
1166
+ };
1167
+ }
1168
+ __name(terminalValue, "terminalValue");
1169
+ var KNOWN_PLATFORMS = /* @__PURE__ */ new Set([
1170
+ "aix",
1171
+ "darwin",
1172
+ "freebsd",
1173
+ "linux",
1174
+ "openbsd",
1175
+ "sunos",
1176
+ "win32"
1177
+ ]);
1178
+ function platformValue(value) {
1179
+ return typeof value === "string" && KNOWN_PLATFORMS.has(value) ? value : process.platform;
1180
+ }
1181
+ __name(platformValue, "platformValue");
1182
+ function stringMapValue(value) {
1183
+ if (!isRecord2(value)) return {};
1184
+ return Object.fromEntries(
1185
+ Object.entries(value).filter(
1186
+ (entry) => typeof entry[1] === "string"
1187
+ )
1188
+ );
1189
+ }
1190
+ __name(stringMapValue, "stringMapValue");
1191
+ function stringArrayValue(value) {
1192
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1193
+ }
1194
+ __name(stringArrayValue, "stringArrayValue");
1195
+ function stringValue(value) {
1196
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1197
+ }
1198
+ __name(stringValue, "stringValue");
1199
+ function numberValue(value) {
1200
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1201
+ }
1202
+ __name(numberValue, "numberValue");
1203
+ function isRecord2(value) {
1204
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1205
+ }
1206
+ __name(isRecord2, "isRecord");
1207
+ function isNodeError(error) {
1208
+ return error instanceof Error && "code" in error;
1209
+ }
1210
+ __name(isNodeError, "isNodeError");
1211
+
1212
+ // packages/cli/src/agent-view/current-cli-argv.ts
1213
+ init_esbuild_shims();
1214
+ import * as fs2 from "node:fs";
1215
+ import * as path2 from "node:path";
1216
+ function getCurrentO1CodeCliEntrypoint() {
1217
+ const entry = process.argv[1];
1218
+ if (!entry) return "o1-code";
1219
+ return path2.isAbsolute(entry) ? entry : path2.resolve(entry);
1220
+ }
1221
+ __name(getCurrentO1CodeCliEntrypoint, "getCurrentO1CodeCliEntrypoint");
1222
+ function buildCurrentO1CodeCliArgv(args) {
1223
+ const entrypoint = getCurrentO1CodeCliEntrypoint();
1224
+ if (entrypoint === "o1-code") {
1225
+ return ["o1-code", ...args];
1226
+ }
1227
+ if (process.env["DEV"] === "true" && entrypoint.endsWith(".ts")) {
1228
+ const tsxCli = findLocalTsxCli(entrypoint);
1229
+ if (tsxCli) {
1230
+ return [process.execPath, tsxCli, entrypoint, ...args];
1231
+ }
1232
+ throw new Error(
1233
+ `Cannot spawn supervisor: DEV=true with TypeScript entrypoint ${entrypoint} but tsx was not found. Run npm install.`
1234
+ );
1235
+ }
1236
+ return [process.execPath, entrypoint, ...args];
1237
+ }
1238
+ __name(buildCurrentO1CodeCliArgv, "buildCurrentO1CodeCliArgv");
1239
+ function findLocalTsxCli(entrypoint) {
1240
+ const root = path2.resolve(path2.dirname(entrypoint), "..", "..");
1241
+ const tsxCli = path2.join(root, "node_modules", "tsx", "dist", "cli.mjs");
1242
+ if (fs2.existsSync(tsxCli)) {
1243
+ return tsxCli;
1244
+ }
1245
+ return void 0;
1246
+ }
1247
+ __name(findLocalTsxCli, "findLocalTsxCli");
1248
+
1249
+ // packages/cli/src/agent-view/pty-host-process.ts
1250
+ var INTERNAL_AGENT_VIEW_PTY_HOST_ARG = "--internal-agent-view-pty-host";
1251
+ var HOST_READY_RETRIES = 50;
1252
+ var CONNECT_HOST_READY_RETRIES = 10;
1253
+ var HOST_READY_DELAY_MS = 50;
1254
+ var HOST_READY_REQUEST_TIMEOUT_MS = 250;
1255
+ var REMOTE_HOST_EXIT_POLL_MS = 5e3;
1256
+ var SHUTDOWN_GRACE_MS = 2e3;
1257
+ var UNIX_SOCKET_PATH_LIMIT = 100;
1258
+ var MAX_PTY_HOST_REQUEST_LINE_BYTES = 1024 * 1024;
1259
+ var MAX_PTY_HOST_RESPONSE_LINE_BYTES = 8 * 1024 * 1024;
1260
+ var ALLOWED_KILL_SIGNALS = /* @__PURE__ */ new Set([
1261
+ "SIGINT",
1262
+ "SIGKILL",
1263
+ "SIGTERM"
1264
+ ]);
1265
+ var HOST_OPERATIONS = [
1266
+ "status",
1267
+ "logs",
1268
+ "resize",
1269
+ "kill",
1270
+ "shutdown",
1271
+ "attachStream"
1272
+ ];
1273
+ function createAgentViewPtyHostIdentity(sessionId, options = {}) {
1274
+ return {
1275
+ hostId: randomUUID(),
1276
+ endpoint: getAgentViewPtyHostSocketPath(sessionId, options),
1277
+ authToken: randomUUID()
1278
+ };
1279
+ }
1280
+ __name(createAgentViewPtyHostIdentity, "createAgentViewPtyHostIdentity");
1281
+ async function launchAgentViewPtyHostProcess(launch, options = {}) {
1282
+ const identity = options.identity ?? createAgentViewPtyHostIdentity(launch.sessionId, options);
1283
+ const socketPath = identity.endpoint;
1284
+ const authToken = identity.authToken;
1285
+ const launchPath = getAgentViewSessionPaths(launch.sessionId, {
1286
+ ...options.globalDir ? { globalDir: options.globalDir } : {}
1287
+ }).launchPath;
1288
+ const stderrLogPath = `${launchPath}.host-stderr.log`;
1289
+ const child = (options.spawnProcess ?? defaultSpawnPtyHost)(
1290
+ [INTERNAL_AGENT_VIEW_PTY_HOST_ARG, launchPath, socketPath],
1291
+ {
1292
+ [PTY_HOST_AUTH_TOKEN_ENV]: authToken,
1293
+ [PTY_HOST_ID_ENV]: identity.hostId
1294
+ },
1295
+ stderrLogPath
1296
+ );
1297
+ child.unref?.();
1298
+ let status;
1299
+ try {
1300
+ status = await waitForSpawnedPtyHost(
1301
+ socketPath,
1302
+ child,
1303
+ authToken,
1304
+ identity.hostId
1305
+ );
1306
+ } catch (error) {
1307
+ child.kill?.("SIGKILL");
1308
+ throw await withHostStderrTail(error, stderrLogPath);
1309
+ }
1310
+ return createRemotePtyHostHandle({
1311
+ hostId: identity.hostId,
1312
+ socketPath,
1313
+ launch,
1314
+ authToken,
1315
+ pid: child.pid ?? status.pid,
1316
+ workerPid: status.workerPid,
1317
+ child
1318
+ });
1319
+ }
1320
+ __name(launchAgentViewPtyHostProcess, "launchAgentViewPtyHostProcess");
1321
+ async function connectAgentViewPtyHostProcess(launch, socketPath, authToken, options = {}) {
1322
+ const status = await waitForPtyHost(
1323
+ socketPath,
1324
+ options.readyRetries ?? CONNECT_HOST_READY_RETRIES,
1325
+ authToken,
1326
+ {
1327
+ requestTimeoutMs: options.requestTimeoutMs ?? HOST_READY_REQUEST_TIMEOUT_MS,
1328
+ expectedHostId: options.expectedHostId
1329
+ }
1330
+ );
1331
+ return createRemotePtyHostHandle({
1332
+ hostId: status.hostId,
1333
+ socketPath,
1334
+ launch,
1335
+ authToken,
1336
+ ...options.requestTimeoutMs !== void 0 ? { requestTimeoutMs: options.requestTimeoutMs } : {},
1337
+ pid: status.pid,
1338
+ workerPid: status.workerPid
1339
+ });
1340
+ }
1341
+ __name(connectAgentViewPtyHostProcess, "connectAgentViewPtyHostProcess");
1342
+ function createRemotePtyHostHandle({
1343
+ hostId,
1344
+ socketPath,
1345
+ launch,
1346
+ authToken,
1347
+ requestTimeoutMs,
1348
+ pid,
1349
+ workerPid,
1350
+ child
1351
+ }) {
1352
+ const output = new BoundedOutputRing();
1353
+ let attachSocket;
1354
+ const exitTracker = child ? createChildExitTracker(child) : createRemoteExitTracker(socketPath, authToken);
1355
+ return {
1356
+ ...hostId ? { hostId } : {},
1357
+ pid,
1358
+ workerPid,
1359
+ command: launch.argv,
1360
+ endpoint: socketPath,
1361
+ ...authToken ? { authToken } : {},
1362
+ output,
1363
+ exited: exitTracker.exited,
1364
+ async getOutput() {
1365
+ const result = await callAgentViewPtyHost(
1366
+ socketPath,
1367
+ authToken,
1368
+ "logs",
1369
+ void 0,
1370
+ requestTimeoutMs
1371
+ );
1372
+ if (isRecord3(result) && typeof result["output"] === "string") {
1373
+ return result["output"];
1374
+ }
1375
+ return "";
1376
+ },
1377
+ write(data) {
1378
+ if (!attachSocket) {
1379
+ throw new Error(
1380
+ "Agent View PTY host input requires an active attach stream."
1381
+ );
1382
+ }
1383
+ attachSocket.write(data);
1384
+ },
1385
+ onData(callback) {
1386
+ attachSocket?.destroy();
1387
+ const socket = net.createConnection(socketPath);
1388
+ attachSocket = socket;
1389
+ socket.setEncoding("utf8");
1390
+ socket.write(
1391
+ `${JSON.stringify({
1392
+ id: createRequestId(),
1393
+ op: "attachStream",
1394
+ ...authToken ? { authToken } : {}
1395
+ })}
1396
+ `
1397
+ );
1398
+ let attached = false;
1399
+ let buffer = "";
1400
+ const onData = /* @__PURE__ */ __name((textChunk) => {
1401
+ if (attached) {
1402
+ output.append(textChunk);
1403
+ callback(textChunk);
1404
+ return;
1405
+ }
1406
+ buffer += textChunk;
1407
+ if (Buffer.byteLength(buffer, "utf8") > MAX_PTY_HOST_RESPONSE_LINE_BYTES) {
1408
+ socket.destroy(
1409
+ new AgentViewPtyHostProtocolError(
1410
+ "Agent View PTY host response line is too large."
1411
+ )
1412
+ );
1413
+ return;
1414
+ }
1415
+ const newline = buffer.indexOf("\n");
1416
+ if (newline === -1) return;
1417
+ let response;
1418
+ try {
1419
+ response = parseHostResponse(buffer.slice(0, newline));
1420
+ } catch (error) {
1421
+ socket.destroy(
1422
+ error instanceof Error ? error : new Error(String(error))
1423
+ );
1424
+ return;
1425
+ }
1426
+ if (!response.ok) {
1427
+ socket.destroy(new Error(response.error.message));
1428
+ return;
1429
+ }
1430
+ attached = true;
1431
+ const leftover = buffer.slice(newline + 1);
1432
+ buffer = "";
1433
+ if (leftover) {
1434
+ output.append(leftover);
1435
+ callback(leftover);
1436
+ }
1437
+ }, "onData");
1438
+ socket.on("data", onData);
1439
+ socket.once("error", () => {
1440
+ if (attachSocket === socket) {
1441
+ attachSocket = void 0;
1442
+ }
1443
+ });
1444
+ socket.once("close", () => {
1445
+ if (attachSocket === socket) {
1446
+ attachSocket = void 0;
1447
+ }
1448
+ });
1449
+ return {
1450
+ dispose() {
1451
+ socket.off("data", onData);
1452
+ socket.destroy();
1453
+ }
1454
+ };
1455
+ },
1456
+ resize(size) {
1457
+ void callAgentViewPtyHost(socketPath, authToken, "resize", {
1458
+ columns: size.columns,
1459
+ rows: size.rows
1460
+ }).catch(() => {
1461
+ });
1462
+ },
1463
+ kill(signal) {
1464
+ const allowedSignal = killSignalValue(signal);
1465
+ void callAgentViewPtyHost(socketPath, authToken, "kill", {
1466
+ signal: allowedSignal
1467
+ }).then(
1468
+ () => {
1469
+ if (!child && allowedSignal === "SIGKILL") {
1470
+ exitTracker.markKillConfirmed?.();
1471
+ }
1472
+ },
1473
+ () => {
1474
+ child?.kill(allowedSignal);
1475
+ }
1476
+ );
1477
+ },
1478
+ shutdown() {
1479
+ void callAgentViewPtyHost(socketPath, authToken, "shutdown").then(
1480
+ () => {
1481
+ if (!child) {
1482
+ exitTracker.markShutdownConfirmed?.();
1483
+ }
1484
+ },
1485
+ () => {
1486
+ child?.kill("SIGTERM");
1487
+ }
1488
+ );
1489
+ attachSocket?.destroy();
1490
+ },
1491
+ dispose() {
1492
+ void callAgentViewPtyHost(socketPath, authToken, "shutdown").catch(() => {
1493
+ child?.kill("SIGTERM");
1494
+ });
1495
+ attachSocket?.destroy();
1496
+ exitTracker.resolve({ kind: "unreachable" });
1497
+ }
1498
+ };
1499
+ }
1500
+ __name(createRemotePtyHostHandle, "createRemotePtyHostHandle");
1501
+ function createChildExitTracker(child) {
1502
+ let resolveExit = /* @__PURE__ */ __name(() => {
1503
+ }, "resolveExit");
1504
+ const exited = new Promise((resolve3) => {
1505
+ resolveExit = resolve3;
1506
+ child.once("exit", (code, signal) => {
1507
+ const signalNumber = signal ? os.constants.signals[signal] : void 0;
1508
+ resolve3({
1509
+ kind: "exited",
1510
+ exitCode: typeof code === "number" ? code : 1,
1511
+ ...signalNumber ? { signal: signalNumber } : {}
1512
+ });
1513
+ });
1514
+ });
1515
+ return { exited, resolve: resolveExit };
1516
+ }
1517
+ __name(createChildExitTracker, "createChildExitTracker");
1518
+ function createRemoteExitTracker(socketPath, authToken) {
1519
+ let settled = false;
1520
+ let pollInFlight = false;
1521
+ let resolveExit = /* @__PURE__ */ __name(() => {
1522
+ }, "resolveExit");
1523
+ const exited = new Promise((resolve3) => {
1524
+ resolveExit = resolve3;
1525
+ });
1526
+ let consecutiveFailures = 0;
1527
+ let confirmedTermination;
1528
+ let confirmedTerminationPoll;
1529
+ const scheduleConfirmedPoll = /* @__PURE__ */ __name(() => {
1530
+ if (settled || !confirmedTermination) return;
1531
+ clearTimeout(confirmedTerminationPoll);
1532
+ confirmedTerminationPoll = setTimeout(poll, 50);
1533
+ confirmedTerminationPoll.unref?.();
1534
+ }, "scheduleConfirmedPoll");
1535
+ const poll = /* @__PURE__ */ __name(() => {
1536
+ if (settled || pollInFlight) return;
1537
+ pollInFlight = true;
1538
+ void callAgentViewPtyHost(socketPath, authToken, "status").then(() => {
1539
+ if (settled) return;
1540
+ consecutiveFailures = 0;
1541
+ }).catch(() => {
1542
+ if (settled) return;
1543
+ if (++consecutiveFailures >= 2) {
1544
+ resolveExitOnce(
1545
+ confirmedTermination === "kill" ? { kind: "confirmed-kill" } : confirmedTermination === "shutdown" ? { kind: "confirmed-shutdown" } : { kind: "unreachable" }
1546
+ );
1547
+ }
1548
+ }).finally(() => {
1549
+ pollInFlight = false;
1550
+ scheduleConfirmedPoll();
1551
+ });
1552
+ }, "poll");
1553
+ const interval = setInterval(poll, REMOTE_HOST_EXIT_POLL_MS);
1554
+ interval.unref?.();
1555
+ const resolveExitOnce = /* @__PURE__ */ __name((exit) => {
1556
+ if (settled) return;
1557
+ settled = true;
1558
+ clearInterval(interval);
1559
+ clearTimeout(confirmedTerminationPoll);
1560
+ resolveExit(exit);
1561
+ }, "resolveExitOnce");
1562
+ return {
1563
+ exited,
1564
+ resolve: resolveExitOnce,
1565
+ markKillConfirmed: /* @__PURE__ */ __name(() => {
1566
+ if (confirmedTermination) return;
1567
+ confirmedTermination = "kill";
1568
+ poll();
1569
+ }, "markKillConfirmed"),
1570
+ markShutdownConfirmed: /* @__PURE__ */ __name(() => {
1571
+ if (confirmedTermination) return;
1572
+ confirmedTermination = "shutdown";
1573
+ poll();
1574
+ }, "markShutdownConfirmed")
1575
+ };
1576
+ }
1577
+ __name(createRemoteExitTracker, "createRemoteExitTracker");
1578
+ async function runAgentViewPtyHostProcess({
1579
+ launchPath,
1580
+ socketPath,
1581
+ authToken,
1582
+ hostId,
1583
+ loadPty
1584
+ }) {
1585
+ const launch = JSON.parse(await fs3.readFile(launchPath, "utf8"));
1586
+ const host = await launchAgentViewPtyHost(launch, {
1587
+ ...loadPty ? { loadPty } : {}
1588
+ });
1589
+ const server = createAgentViewPtyHostServer(host, socketPath, {
1590
+ authToken: authToken ?? process.env[PTY_HOST_AUTH_TOKEN_ENV],
1591
+ hostId: hostId ?? process.env[PTY_HOST_ID_ENV]
1592
+ });
1593
+ try {
1594
+ await server.listen();
1595
+ } catch (error) {
1596
+ host.dispose();
1597
+ throw error;
1598
+ }
1599
+ await host.exited.finally(async () => {
1600
+ host.dispose();
1601
+ await server.close();
1602
+ });
1603
+ }
1604
+ __name(runAgentViewPtyHostProcess, "runAgentViewPtyHostProcess");
1605
+ function getAgentViewPtyHostSocketPath(sessionId, options = {}) {
1606
+ const platform = options.platform ?? process.platform;
1607
+ const digest = shortHash(`${options.globalDir ?? ""}:${sessionId}:pty-host`);
1608
+ if (platform === "win32") {
1609
+ return `\\\\.\\pipe\\o1-code-agent-pty-${digest}`;
1610
+ }
1611
+ const tmpDir = getAgentViewSessionPaths(sessionId, {
1612
+ ...options.globalDir ? { globalDir: options.globalDir } : {}
1613
+ }).tmpDir;
1614
+ const candidate = path3.join(tmpDir, "pty-host.sock");
1615
+ if (Buffer.byteLength(candidate) < UNIX_SOCKET_PATH_LIMIT) {
1616
+ return candidate;
1617
+ }
1618
+ const uid = typeof process.getuid === "function" ? process.getuid() : "user";
1619
+ const fallbackCandidates = [
1620
+ path3.join(os.tmpdir(), `o1-code-avp-${uid}`, `${digest}.sock`),
1621
+ path3.join("/tmp", `o1-code-avp-${uid}`, `${digest}.sock`)
1622
+ ];
1623
+ const fallback = fallbackCandidates.find(
1624
+ (item) => Buffer.byteLength(item) < UNIX_SOCKET_PATH_LIMIT && canPrepareSocketDirectory(path3.dirname(item))
1625
+ );
1626
+ const lengthFallback = fallbackCandidates.find(
1627
+ (item) => Buffer.byteLength(item) < UNIX_SOCKET_PATH_LIMIT
1628
+ );
1629
+ if (fallback) {
1630
+ return fallback;
1631
+ }
1632
+ if (lengthFallback) {
1633
+ throw new Error(
1634
+ "Agent View PTY host socket fallback directories are not writable."
1635
+ );
1636
+ }
1637
+ throw new Error("Agent View PTY host socket path is too long.");
1638
+ }
1639
+ __name(getAgentViewPtyHostSocketPath, "getAgentViewPtyHostSocketPath");
1640
+ async function callAgentViewPtyHost(socketPath, authToken, op, params, timeoutMs) {
1641
+ const response = await requestAgentViewPtyHost(
1642
+ socketPath,
1643
+ {
1644
+ id: createRequestId(),
1645
+ op,
1646
+ ...authToken ? { authToken } : {},
1647
+ ...params ? { params } : {}
1648
+ },
1649
+ timeoutMs ? { timeoutMs } : {}
1650
+ );
1651
+ if (response.ok) return response.result;
1652
+ throw new AgentViewPtyHostRequestError(
1653
+ response.error.code,
1654
+ response.error.message
1655
+ );
1656
+ }
1657
+ __name(callAgentViewPtyHost, "callAgentViewPtyHost");
1658
+ var AgentViewPtyHostRequestError = class extends Error {
1659
+ constructor(code, message) {
1660
+ super(message);
1661
+ this.code = code;
1662
+ this.name = "AgentViewPtyHostRequestError";
1663
+ }
1664
+ static {
1665
+ __name(this, "AgentViewPtyHostRequestError");
1666
+ }
1667
+ };
1668
+ var AgentViewPtyHostProtocolError = class extends Error {
1669
+ static {
1670
+ __name(this, "AgentViewPtyHostProtocolError");
1671
+ }
1672
+ constructor(message) {
1673
+ super(message);
1674
+ this.name = "AgentViewPtyHostProtocolError";
1675
+ }
1676
+ };
1677
+ async function requestAgentViewPtyHost(socketPath, request, options = {}) {
1678
+ return new Promise((resolve3, reject) => {
1679
+ const socket = net.createConnection(socketPath);
1680
+ let buffer = "";
1681
+ let settled = false;
1682
+ const timeout = setTimeout(() => {
1683
+ finish(
1684
+ void 0,
1685
+ new Error("Timed out waiting for Agent View PTY host.")
1686
+ );
1687
+ socket.destroy();
1688
+ }, options.timeoutMs ?? 5e3);
1689
+ const finish = /* @__PURE__ */ __name((response, error) => {
1690
+ if (settled) return;
1691
+ settled = true;
1692
+ clearTimeout(timeout);
1693
+ socket.removeAllListeners();
1694
+ if (error) {
1695
+ reject(error);
1696
+ } else {
1697
+ resolve3(response);
1698
+ }
1699
+ }, "finish");
1700
+ socket.setEncoding("utf8");
1701
+ socket.on("connect", () => {
1702
+ socket.write(`${JSON.stringify(request)}
1703
+ `);
1704
+ });
1705
+ socket.on("data", (chunk) => {
1706
+ buffer += chunk;
1707
+ if (Buffer.byteLength(buffer, "utf8") > MAX_PTY_HOST_RESPONSE_LINE_BYTES) {
1708
+ finish(
1709
+ void 0,
1710
+ new AgentViewPtyHostProtocolError(
1711
+ "Agent View PTY host response line is too large."
1712
+ )
1713
+ );
1714
+ socket.destroy();
1715
+ return;
1716
+ }
1717
+ const newline = buffer.indexOf("\n");
1718
+ if (newline === -1) return;
1719
+ try {
1720
+ finish(parseHostResponse(buffer.slice(0, newline)));
1721
+ } catch (error) {
1722
+ finish(void 0, error);
1723
+ } finally {
1724
+ socket.end();
1725
+ }
1726
+ });
1727
+ socket.on("error", (error) => finish(void 0, error));
1728
+ socket.on("close", () => {
1729
+ finish(void 0, new Error("Agent View PTY host connection closed."));
1730
+ });
1731
+ });
1732
+ }
1733
+ __name(requestAgentViewPtyHost, "requestAgentViewPtyHost");
1734
+ function createAgentViewPtyHostServer(host, socketPath, options = {}) {
1735
+ const attachState = {
1736
+ activeAttachSocket: void 0
1737
+ };
1738
+ const openSockets = /* @__PURE__ */ new Set();
1739
+ const server = net.createServer((socket) => {
1740
+ openSockets.add(socket);
1741
+ socket.once("close", () => {
1742
+ openSockets.delete(socket);
1743
+ });
1744
+ socket.on("error", () => {
1745
+ });
1746
+ socket.setTimeout(5e3, () => {
1747
+ socket.destroy();
1748
+ });
1749
+ let buffer = Buffer.alloc(0);
1750
+ socket.on("data", (chunk) => {
1751
+ buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
1752
+ if (buffer.length > MAX_PTY_HOST_REQUEST_LINE_BYTES) {
1753
+ socket.destroy();
1754
+ return;
1755
+ }
1756
+ const newline = buffer.indexOf(10);
1757
+ if (newline === -1) return;
1758
+ const line = buffer.toString("utf8", 0, newline);
1759
+ const leftover = Buffer.from(buffer.subarray(newline + 1));
1760
+ buffer = Buffer.alloc(0);
1761
+ socket.pause();
1762
+ void respondToHostLine(
1763
+ host,
1764
+ line,
1765
+ socket,
1766
+ attachState,
1767
+ leftover,
1768
+ options.authToken,
1769
+ options.hostId,
1770
+ options.shutdownGraceMs
1771
+ ).catch(() => {
1772
+ socket.destroy();
1773
+ });
1774
+ });
1775
+ });
1776
+ let releaseLock;
1777
+ return {
1778
+ async listen() {
1779
+ if (!isWindowsPipePath(socketPath)) {
1780
+ releaseLock = await acquireSocketPathLock(socketPath);
1781
+ }
1782
+ try {
1783
+ await prepareSocketPath(socketPath);
1784
+ await new Promise((resolve3, reject) => {
1785
+ server.once("error", reject);
1786
+ server.listen(socketPath, () => {
1787
+ server.off("error", reject);
1788
+ server.on("error", () => {
1789
+ });
1790
+ if (isWindowsPipePath(socketPath)) {
1791
+ resolve3();
1792
+ return;
1793
+ }
1794
+ fs3.chmod(socketPath, 384).then(resolve3, (error) => {
1795
+ server.close(() => reject(error));
1796
+ });
1797
+ });
1798
+ });
1799
+ if (!isWindowsPipePath(socketPath)) {
1800
+ const lockContent = await fs3.readFile(`${socketPath}.lock`, "utf8").catch(() => "");
1801
+ if (lockContent !== String(process.pid)) {
1802
+ releaseLock = void 0;
1803
+ for (const socket of openSockets) {
1804
+ socket.destroy();
1805
+ }
1806
+ await new Promise((resolve3) => server.close(() => resolve3()));
1807
+ const displaced = new Error(
1808
+ `Agent View PTY host socket is already in use: ${socketPath}`
1809
+ );
1810
+ displaced.code = "EADDRINUSE";
1811
+ throw displaced;
1812
+ }
1813
+ }
1814
+ } catch (error) {
1815
+ await releaseLock?.();
1816
+ releaseLock = void 0;
1817
+ throw error;
1818
+ }
1819
+ },
1820
+ async close() {
1821
+ attachState.activeAttachSocket?.destroy();
1822
+ for (const socket of openSockets) {
1823
+ socket.destroy();
1824
+ }
1825
+ await new Promise((resolve3, reject) => {
1826
+ if (!server.listening) {
1827
+ resolve3();
1828
+ return;
1829
+ }
1830
+ server.close((error) => error ? reject(error) : resolve3());
1831
+ });
1832
+ await removeOwnedSocketPath(socketPath);
1833
+ await releaseLock?.();
1834
+ releaseLock = void 0;
1835
+ }
1836
+ };
1837
+ }
1838
+ __name(createAgentViewPtyHostServer, "createAgentViewPtyHostServer");
1839
+ async function respondToHostLine(host, line, socket, attachState, leftover = Buffer.alloc(0), authToken, hostId, shutdownGraceMs) {
1840
+ const request = parseHostRequest(line);
1841
+ if (!request) {
1842
+ socket.end(
1843
+ `${JSON.stringify(errorResponse("", "invalid_json", "Invalid JSON."))}
1844
+ `
1845
+ );
1846
+ return;
1847
+ }
1848
+ if (authToken && !isValidAuthToken(request.authToken, authToken)) {
1849
+ socket.end(
1850
+ `${JSON.stringify(
1851
+ errorResponse(
1852
+ request.id,
1853
+ "unauthorized",
1854
+ "Unauthorized PTY host request."
1855
+ )
1856
+ )}
1857
+ `
1858
+ );
1859
+ return;
1860
+ }
1861
+ if (request.op === "attachStream") {
1862
+ if (attachState.activeAttachSocket?.destroyed === false) {
1863
+ socket.end(
1864
+ `${JSON.stringify(
1865
+ errorResponse(
1866
+ request.id,
1867
+ "already_attached",
1868
+ "Agent View PTY host already has an attached stream."
1869
+ )
1870
+ )}
1871
+ `
1872
+ );
1873
+ return;
1874
+ }
1875
+ attachState.activeAttachSocket = socket;
1876
+ host.resetInput?.();
1877
+ const clearActiveAttach = /* @__PURE__ */ __name(() => {
1878
+ if (attachState.activeAttachSocket === socket) {
1879
+ attachState.activeAttachSocket = void 0;
1880
+ }
1881
+ }, "clearActiveAttach");
1882
+ socket.once("close", clearActiveAttach);
1883
+ socket.removeAllListeners("data");
1884
+ socket.setTimeout(0);
1885
+ socket.resume();
1886
+ try {
1887
+ socket.write(
1888
+ `${JSON.stringify({
1889
+ id: request.id,
1890
+ ok: true,
1891
+ result: { attached: true }
1892
+ })}
1893
+ `
1894
+ );
1895
+ if (leftover.length > 0) {
1896
+ host.write(leftover);
1897
+ }
1898
+ await bridgeAgentViewTerminal({
1899
+ stdin: socket,
1900
+ stdout: socket,
1901
+ pty: host
1902
+ });
1903
+ } finally {
1904
+ socket.off("close", clearActiveAttach);
1905
+ clearActiveAttach();
1906
+ socket.end();
1907
+ }
1908
+ return;
1909
+ }
1910
+ try {
1911
+ const result = await handleHostRequest(
1912
+ host,
1913
+ request,
1914
+ hostId,
1915
+ shutdownGraceMs
1916
+ );
1917
+ socket.end(`${JSON.stringify({ id: request.id, ok: true, result })}
1918
+ `);
1919
+ } catch (error) {
1920
+ socket.end(
1921
+ `${JSON.stringify(
1922
+ errorResponse(
1923
+ request.id,
1924
+ "internal_error",
1925
+ error instanceof Error ? error.message : "PTY host request failed."
1926
+ )
1927
+ )}
1928
+ `
1929
+ );
1930
+ }
1931
+ }
1932
+ __name(respondToHostLine, "respondToHostLine");
1933
+ async function handleHostRequest(host, request, hostId, shutdownGraceMs) {
1934
+ switch (request.op) {
1935
+ case "status":
1936
+ return {
1937
+ ...hostId ? { hostId } : {},
1938
+ pid: process.pid,
1939
+ workerPid: host.workerPid
1940
+ };
1941
+ case "logs":
1942
+ return { output: host.output.toString() };
1943
+ case "resize":
1944
+ host.resize({
1945
+ columns: positiveIntegerParam(request.params, "columns"),
1946
+ rows: positiveIntegerParam(request.params, "rows")
1947
+ });
1948
+ return { resized: true };
1949
+ case "kill":
1950
+ host.kill(signalParam(request.params) ?? "SIGTERM");
1951
+ return { killed: true };
1952
+ case "shutdown":
1953
+ await shutdownHost(host, shutdownGraceMs);
1954
+ return { shuttingDown: true };
1955
+ case "attachStream":
1956
+ throw new Error("attachStream must use the streaming path.");
1957
+ default: {
1958
+ const unknownOperation = request.op;
1959
+ throw new Error(`Unsupported PTY host operation: ${unknownOperation}`);
1960
+ }
1961
+ }
1962
+ }
1963
+ __name(handleHostRequest, "handleHostRequest");
1964
+ async function shutdownHost(host, graceMs = SHUTDOWN_GRACE_MS) {
1965
+ if (host.shutdown) {
1966
+ await host.shutdown();
1967
+ } else {
1968
+ host.kill("SIGTERM");
1969
+ }
1970
+ const timer = setTimeout(() => {
1971
+ try {
1972
+ host.kill("SIGKILL");
1973
+ } catch {
1974
+ }
1975
+ }, graceMs);
1976
+ timer.unref?.();
1977
+ const cancel = /* @__PURE__ */ __name(() => clearTimeout(timer), "cancel");
1978
+ void host.exited.then(cancel, cancel);
1979
+ }
1980
+ __name(shutdownHost, "shutdownHost");
1981
+ async function waitForSpawnedPtyHost(socketPath, child, authToken, hostId) {
1982
+ return new Promise((resolve3, reject) => {
1983
+ let settled = false;
1984
+ const abortController = new AbortController();
1985
+ const cleanup = /* @__PURE__ */ __name(() => {
1986
+ abortController.abort();
1987
+ child.off("exit", onExit);
1988
+ child.off("error", onError);
1989
+ }, "cleanup");
1990
+ const finishResolve = /* @__PURE__ */ __name((value) => {
1991
+ if (settled) return;
1992
+ settled = true;
1993
+ cleanup();
1994
+ resolve3(value);
1995
+ }, "finishResolve");
1996
+ const finishReject = /* @__PURE__ */ __name((error) => {
1997
+ if (settled) return;
1998
+ settled = true;
1999
+ cleanup();
2000
+ reject(error);
2001
+ }, "finishReject");
2002
+ const onExit = /* @__PURE__ */ __name((code, signal) => {
2003
+ const suffix = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`;
2004
+ finishReject(
2005
+ new Error(`Agent View PTY host exited before ready (${suffix}).`)
2006
+ );
2007
+ }, "onExit");
2008
+ const onError = /* @__PURE__ */ __name((error) => {
2009
+ finishReject(error);
2010
+ }, "onError");
2011
+ child.once("exit", onExit);
2012
+ child.once("error", onError);
2013
+ void waitForPtyHost(socketPath, HOST_READY_RETRIES, authToken, {
2014
+ requestTimeoutMs: HOST_READY_REQUEST_TIMEOUT_MS,
2015
+ expectedHostId: hostId,
2016
+ signal: abortController.signal
2017
+ }).then(
2018
+ (status) => finishResolve(status),
2019
+ (error) => {
2020
+ if (abortController.signal.aborted && settled) return;
2021
+ finishReject(error instanceof Error ? error : new Error(String(error)));
2022
+ }
2023
+ );
2024
+ });
2025
+ }
2026
+ __name(waitForSpawnedPtyHost, "waitForSpawnedPtyHost");
2027
+ async function waitForPtyHost(socketPath, retries = HOST_READY_RETRIES, authToken, options = {}) {
2028
+ const requestTimeoutMs = options.requestTimeoutMs ?? 5e3;
2029
+ const deadlineMs = Date.now() + retries * (HOST_READY_DELAY_MS + requestTimeoutMs);
2030
+ for (let attempt = 0; attempt < retries; attempt++) {
2031
+ if (options.signal?.aborted || Date.now() >= deadlineMs) break;
2032
+ try {
2033
+ const result = await callAgentViewPtyHost(
2034
+ socketPath,
2035
+ authToken,
2036
+ "status",
2037
+ void 0,
2038
+ requestTimeoutMs
2039
+ );
2040
+ if (isRecord3(result) && Number.isInteger(result["workerPid"])) {
2041
+ const hostId = typeof result["hostId"] === "string" ? result["hostId"] : void 0;
2042
+ if (options.expectedHostId && hostId !== options.expectedHostId) {
2043
+ throw new AgentViewPtyHostProtocolError(
2044
+ "Agent View PTY host identity does not match."
2045
+ );
2046
+ }
2047
+ return {
2048
+ ...hostId ? { hostId } : {},
2049
+ pid: Number.isInteger(result["pid"]) ? Number(result["pid"]) : process.pid,
2050
+ workerPid: Number(result["workerPid"])
2051
+ };
2052
+ }
2053
+ } catch (error) {
2054
+ if (error instanceof AgentViewPtyHostProtocolError || error instanceof AgentViewPtyHostRequestError && error.code === "unauthorized") {
2055
+ throw error;
2056
+ }
2057
+ }
2058
+ await delay(HOST_READY_DELAY_MS, options.signal);
2059
+ }
2060
+ throw new Error("Agent View PTY host did not become ready.");
2061
+ }
2062
+ __name(waitForPtyHost, "waitForPtyHost");
2063
+ function defaultSpawnPtyHost(args, env, stderrLogPath) {
2064
+ const argv = buildCurrentO1CodeCliArgv(args);
2065
+ let stderrFd;
2066
+ if (stderrLogPath) {
2067
+ try {
2068
+ stderrFd = openSync(stderrLogPath, "w", 384);
2069
+ } catch {
2070
+ }
2071
+ }
2072
+ try {
2073
+ return spawn(argv[0], argv.slice(1), {
2074
+ detached: true,
2075
+ windowsHide: true,
2076
+ stdio: ["ignore", "ignore", stderrFd ?? "ignore"],
2077
+ env: {
2078
+ ...process.env,
2079
+ ...env,
2080
+ O1CODE_NO_RELAUNCH: "1"
2081
+ }
2082
+ });
2083
+ } finally {
2084
+ if (stderrFd !== void 0) closeSync(stderrFd);
2085
+ }
2086
+ }
2087
+ __name(defaultSpawnPtyHost, "defaultSpawnPtyHost");
2088
+ async function withHostStderrTail(error, stderrLogPath) {
2089
+ const base = error instanceof Error ? error : new Error(String(error));
2090
+ const tail = await fs3.readFile(stderrLogPath, "utf8").then((text) => text.trim().slice(-2048)).catch(() => "");
2091
+ if (!tail) return base;
2092
+ return new Error(`${base.message} Host stderr: ${tail}`, { cause: base });
2093
+ }
2094
+ __name(withHostStderrTail, "withHostStderrTail");
2095
+ function parseHostRequest(line) {
2096
+ try {
2097
+ const parsed = JSON.parse(line);
2098
+ if (!isRecord3(parsed) || typeof parsed["id"] !== "string" || !isHostOperation(parsed["op"])) {
2099
+ return void 0;
2100
+ }
2101
+ return {
2102
+ id: parsed["id"],
2103
+ op: parsed["op"],
2104
+ ...typeof parsed["authToken"] === "string" ? { authToken: parsed["authToken"] } : {},
2105
+ ...isRecord3(parsed["params"]) ? { params: parsed["params"] } : {}
2106
+ };
2107
+ } catch {
2108
+ return void 0;
2109
+ }
2110
+ }
2111
+ __name(parseHostRequest, "parseHostRequest");
2112
+ function parseHostResponse(line) {
2113
+ let parsed;
2114
+ try {
2115
+ parsed = JSON.parse(line);
2116
+ } catch (error) {
2117
+ throw new AgentViewPtyHostProtocolError(
2118
+ error instanceof Error ? error.message : "Invalid PTY host response."
2119
+ );
2120
+ }
2121
+ if (!isRecord3(parsed) || typeof parsed["id"] !== "string") {
2122
+ throw new AgentViewPtyHostProtocolError(
2123
+ "Invalid Agent View PTY host response."
2124
+ );
2125
+ }
2126
+ if (parsed["ok"] === true) {
2127
+ return { id: parsed["id"], ok: true, result: parsed["result"] };
2128
+ }
2129
+ if (parsed["ok"] === false && isRecord3(parsed["error"]) && typeof parsed["error"]["code"] === "string" && typeof parsed["error"]["message"] === "string") {
2130
+ return {
2131
+ id: parsed["id"],
2132
+ ok: false,
2133
+ error: {
2134
+ code: parsed["error"]["code"],
2135
+ message: parsed["error"]["message"]
2136
+ }
2137
+ };
2138
+ }
2139
+ throw new AgentViewPtyHostProtocolError(
2140
+ "Invalid Agent View PTY host response."
2141
+ );
2142
+ }
2143
+ __name(parseHostResponse, "parseHostResponse");
2144
+ function isHostOperation(value) {
2145
+ return HOST_OPERATIONS.includes(value);
2146
+ }
2147
+ __name(isHostOperation, "isHostOperation");
2148
+ function errorResponse(id, code, message) {
2149
+ return { id, ok: false, error: { code, message } };
2150
+ }
2151
+ __name(errorResponse, "errorResponse");
2152
+ async function acquireSocketPathLock(socketPath) {
2153
+ const lockPath = `${socketPath}.lock`;
2154
+ await fs3.mkdir(path3.dirname(socketPath), { recursive: true, mode: 448 });
2155
+ while (true) {
2156
+ try {
2157
+ await fs3.writeFile(lockPath, String(process.pid), { flag: "wx" });
2158
+ return async () => {
2159
+ const current = await fs3.readFile(lockPath, "utf8").catch(() => "");
2160
+ if (current === String(process.pid)) {
2161
+ await fs3.rm(lockPath, { force: true });
2162
+ }
2163
+ };
2164
+ } catch (error) {
2165
+ if (error.code !== "EEXIST") throw error;
2166
+ const raw = await fs3.readFile(lockPath, "utf8").catch(() => "");
2167
+ const holderPid = Number.parseInt(raw, 10);
2168
+ if (!Number.isInteger(holderPid) || !isProcessAlive2(holderPid)) {
2169
+ const current = await fs3.readFile(lockPath, "utf8").catch(() => "");
2170
+ if (current === raw) {
2171
+ await fs3.rm(lockPath, { force: true });
2172
+ }
2173
+ continue;
2174
+ }
2175
+ break;
2176
+ }
2177
+ }
2178
+ const busy = new Error(
2179
+ `Agent View PTY host socket is already in use: ${socketPath}`
2180
+ );
2181
+ busy.code = "EADDRINUSE";
2182
+ throw busy;
2183
+ }
2184
+ __name(acquireSocketPathLock, "acquireSocketPathLock");
2185
+ function isProcessAlive2(pid) {
2186
+ try {
2187
+ process.kill(pid, 0);
2188
+ return true;
2189
+ } catch (error) {
2190
+ return error.code === "EPERM";
2191
+ }
2192
+ }
2193
+ __name(isProcessAlive2, "isProcessAlive");
2194
+ async function prepareSocketPath(socketPath) {
2195
+ if (isWindowsPipePath(socketPath)) return;
2196
+ const socketDir = path3.dirname(socketPath);
2197
+ await fs3.mkdir(socketDir, { recursive: true, mode: 448 });
2198
+ await ensurePrivateSocketDirectory(socketDir);
2199
+ if (!await socketPathExists(socketPath)) return;
2200
+ if (await canConnect(socketPath)) {
2201
+ const error = new Error(
2202
+ `Agent View PTY host socket is already in use: ${socketPath}`
2203
+ );
2204
+ error.code = "EADDRINUSE";
2205
+ throw error;
2206
+ }
2207
+ await removeSocketPath(socketPath);
2208
+ }
2209
+ __name(prepareSocketPath, "prepareSocketPath");
2210
+ async function ensurePrivateSocketDirectory(socketDir) {
2211
+ const stat = await fs3.lstat(socketDir);
2212
+ if (stat.isSymbolicLink()) {
2213
+ throw new Error("Agent View PTY host socket parent must not be a symlink.");
2214
+ }
2215
+ if (!stat.isDirectory()) {
2216
+ throw new Error("Agent View PTY host socket parent is not a directory.");
2217
+ }
2218
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
2219
+ throw new Error("Agent View PTY host socket parent is not owned by you.");
2220
+ }
2221
+ if ((stat.mode & 63) !== 0) {
2222
+ await fs3.chmod(socketDir, 448);
2223
+ }
2224
+ }
2225
+ __name(ensurePrivateSocketDirectory, "ensurePrivateSocketDirectory");
2226
+ function canPrepareSocketDirectory(socketDir) {
2227
+ try {
2228
+ const stat = lstatSync(socketDir);
2229
+ if (stat.isSymbolicLink() || !stat.isDirectory()) return false;
2230
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
2231
+ return false;
2232
+ }
2233
+ accessSync(socketDir, fsConstants.W_OK | fsConstants.X_OK);
2234
+ return true;
2235
+ } catch (error) {
2236
+ if (!isNodeError2(error) || error.code !== "ENOENT") return false;
2237
+ }
2238
+ const parentDir = path3.dirname(socketDir);
2239
+ try {
2240
+ const parentStat = statSync(parentDir);
2241
+ if (!parentStat.isDirectory()) return false;
2242
+ accessSync(parentDir, fsConstants.W_OK | fsConstants.X_OK);
2243
+ return true;
2244
+ } catch {
2245
+ return false;
2246
+ }
2247
+ }
2248
+ __name(canPrepareSocketDirectory, "canPrepareSocketDirectory");
2249
+ async function removeSocketPath(socketPath) {
2250
+ if (isWindowsPipePath(socketPath)) return;
2251
+ try {
2252
+ await fs3.unlink(socketPath);
2253
+ } catch (error) {
2254
+ if (!isNodeError2(error) || error.code !== "ENOENT") {
2255
+ throw error;
2256
+ }
2257
+ }
2258
+ }
2259
+ __name(removeSocketPath, "removeSocketPath");
2260
+ async function removeOwnedSocketPath(socketPath) {
2261
+ if (isWindowsPipePath(socketPath)) return;
2262
+ if (!await socketPathExists(socketPath)) return;
2263
+ if (await canConnect(socketPath)) return;
2264
+ await removeSocketPath(socketPath);
2265
+ }
2266
+ __name(removeOwnedSocketPath, "removeOwnedSocketPath");
2267
+ async function socketPathExists(socketPath) {
2268
+ try {
2269
+ await fs3.lstat(socketPath);
2270
+ return true;
2271
+ } catch (error) {
2272
+ if (isNodeError2(error) && error.code === "ENOENT") return false;
2273
+ throw error;
2274
+ }
2275
+ }
2276
+ __name(socketPathExists, "socketPathExists");
2277
+ async function canConnect(socketPath) {
2278
+ return new Promise((resolve3) => {
2279
+ const socket = net.createConnection(socketPath);
2280
+ let settled = false;
2281
+ function finish(result) {
2282
+ if (settled) return;
2283
+ settled = true;
2284
+ clearTimeout(timeout);
2285
+ socket.removeAllListeners();
2286
+ socket.destroy();
2287
+ resolve3(result);
2288
+ }
2289
+ __name(finish, "finish");
2290
+ socket.once("connect", () => finish(true));
2291
+ socket.once("error", () => finish(false));
2292
+ const timeout = setTimeout(() => finish(false), 250);
2293
+ });
2294
+ }
2295
+ __name(canConnect, "canConnect");
2296
+ function positiveIntegerParam(params, key) {
2297
+ const value = params?.[key];
2298
+ if (!Number.isInteger(value) || Number(value) <= 0) {
2299
+ throw new Error(`Agent View PTY host ${key} must be a positive integer.`);
2300
+ }
2301
+ return Number(value);
2302
+ }
2303
+ __name(positiveIntegerParam, "positiveIntegerParam");
2304
+ function signalParam(params) {
2305
+ return killSignalValue(params?.["signal"]);
2306
+ }
2307
+ __name(signalParam, "signalParam");
2308
+ function killSignalValue(value) {
2309
+ if (value === void 0 || value === "") return void 0;
2310
+ if (typeof value === "string" && ALLOWED_KILL_SIGNALS.has(value)) {
2311
+ return value;
2312
+ }
2313
+ throw new Error("Agent View PTY host signal is not allowed.");
2314
+ }
2315
+ __name(killSignalValue, "killSignalValue");
2316
+ function isValidAuthToken(provided, expected) {
2317
+ if (!provided) return false;
2318
+ const providedBuffer = Buffer.from(provided);
2319
+ const expectedBuffer = Buffer.from(expected);
2320
+ return providedBuffer.length === expectedBuffer.length && timingSafeEqual(providedBuffer, expectedBuffer);
2321
+ }
2322
+ __name(isValidAuthToken, "isValidAuthToken");
2323
+ function isRecord3(value) {
2324
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2325
+ }
2326
+ __name(isRecord3, "isRecord");
2327
+ function isNodeError2(error) {
2328
+ return error instanceof Error && "code" in error;
2329
+ }
2330
+ __name(isNodeError2, "isNodeError");
2331
+ function isWindowsPipePath(socketPath) {
2332
+ return socketPath.startsWith("\\\\.\\pipe\\");
2333
+ }
2334
+ __name(isWindowsPipePath, "isWindowsPipePath");
2335
+ function shortHash(value) {
2336
+ return createHash2("sha256").update(value).digest("hex").slice(0, 12);
2337
+ }
2338
+ __name(shortHash, "shortHash");
2339
+ function createRequestId() {
2340
+ return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
2341
+ }
2342
+ __name(createRequestId, "createRequestId");
2343
+ async function delay(ms, signal) {
2344
+ await new Promise((resolve3) => {
2345
+ if (signal?.aborted) {
2346
+ resolve3();
2347
+ return;
2348
+ }
2349
+ const onAbort = /* @__PURE__ */ __name(() => {
2350
+ clearTimeout(timeout);
2351
+ resolve3();
2352
+ }, "onAbort");
2353
+ const timeout = setTimeout(() => {
2354
+ signal?.removeEventListener("abort", onAbort);
2355
+ resolve3();
2356
+ }, ms);
2357
+ signal?.addEventListener("abort", onAbort, { once: true });
2358
+ });
2359
+ }
2360
+ __name(delay, "delay");
2361
+
2362
+ export {
2363
+ getAgentViewStorePaths,
2364
+ getAgentViewSessionPaths,
2365
+ readAgentViewRosterStrict,
2366
+ upsertAgentViewRosterEntry,
2367
+ removeAgentViewRosterEntry,
2368
+ updateAgentViewRosterEntry,
2369
+ readAgentViewSessionState,
2370
+ writeAgentViewSessionState,
2371
+ patchAgentViewSessionState,
2372
+ patchAgentViewSessionStateIf,
2373
+ listAgentViewSessionStates,
2374
+ listAgentViewSessionSnapshots,
2375
+ readAgentViewLaunch,
2376
+ writeAgentViewLaunch,
2377
+ readAgentViewActivity,
2378
+ writeAgentViewActivity,
2379
+ patchAgentViewActivityIf,
2380
+ clearAgentViewWorkerPids,
2381
+ digestAgentViewWorkerToken,
2382
+ readAgentViewWorker,
2383
+ writeAgentViewWorker,
2384
+ readAgentViewSupervisor,
2385
+ writeAgentViewSupervisor,
2386
+ sanitizeSessionId,
2387
+ redactAgentViewActivity,
2388
+ redactAgentViewWorker,
2389
+ isAgentViewSessionState,
2390
+ inputKindValue,
2391
+ getCurrentO1CodeCliEntrypoint,
2392
+ buildCurrentO1CodeCliArgv,
2393
+ INTERNAL_AGENT_VIEW_PTY_HOST_ARG,
2394
+ createAgentViewPtyHostIdentity,
2395
+ launchAgentViewPtyHostProcess,
2396
+ connectAgentViewPtyHostProcess,
2397
+ runAgentViewPtyHostProcess,
2398
+ getAgentViewPtyHostSocketPath,
2399
+ createAgentViewPtyHostServer
2400
+ };
2401
+ /**
2402
+ * @license
2403
+ * Copyright 2026 Qwen Team
2404
+ * SPDX-License-Identifier: Apache-2.0
2405
+ */