weaver-work-cli 0.1.73 → 0.1.75

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 (310) hide show
  1. package/README.md +37 -1
  2. package/dist/chunks/{archive-THZV4ND4.js → archive-OZJ6PYUR.js} +14 -9
  3. package/dist/chunks/{archive-oa-PQ23OLEV.js → archive-oa-BHL5RK2F.js} +10 -7
  4. package/dist/chunks/{asset-RGPROZYH.js → asset-HKRFRQR2.js} +10 -7
  5. package/dist/chunks/{asset-idle-Z2PDX7NA.js → asset-idle-GGIR4KE7.js} +7 -4
  6. package/dist/chunks/{attachment-content-R3RPVOYE.js → attachment-content-4OV65NK5.js} +3 -3
  7. package/dist/chunks/{blog-7U3QZPIF.js → blog-HYDP4DV3.js} +10 -7
  8. package/dist/chunks/{caizhilian-3AB42GCV.js → caizhilian-JS4RQZ6Z.js} +10 -7
  9. package/dist/chunks/{calendar-KINM64E4.js → calendar-SWRY4DIT.js} +10 -7
  10. package/dist/chunks/chunk-257JXJGD.js +30 -0
  11. package/dist/chunks/{chunk-LLCMOZ5L.js → chunk-2AUFKU2D.js} +11 -11
  12. package/dist/chunks/chunk-2BZ7TY4M.js +49 -0
  13. package/dist/chunks/{chunk-WM33BSIL.js → chunk-2QCCXPNU.js} +1 -1
  14. package/dist/chunks/{chunk-TV46Q4NY.js → chunk-4FCBEWNB.js} +74 -68
  15. package/dist/chunks/{chunk-NUP4RYZK.js → chunk-5D2V7ZAN.js} +2 -2
  16. package/dist/chunks/{chunk-DRUND2PJ.js → chunk-5QUTQHXF.js} +225 -152
  17. package/dist/chunks/{chunk-4BXR6CNB.js → chunk-5ZJGPEIB.js} +2 -2
  18. package/dist/chunks/chunk-7DE3VMZD.js +35 -0
  19. package/dist/chunks/chunk-BNKUHN4N.js +1346 -0
  20. package/dist/chunks/{chunk-2CHGUYMG.js → chunk-BSR5TM7U.js} +4 -4
  21. package/dist/chunks/{chunk-4I26YMBY.js → chunk-ERZY6GYL.js} +7 -3
  22. package/dist/chunks/{chunk-4YXAK6OA.js → chunk-FEZK536Z.js} +12 -7
  23. package/dist/chunks/{chunk-F4HM25K4.js → chunk-I6NOHKEK.js} +1 -1
  24. package/dist/chunks/{chunk-JMJBPP4B.js → chunk-J7FAAHWH.js} +2 -2
  25. package/dist/chunks/{chunk-54ST55IJ.js → chunk-JJONWB5N.js} +11 -1
  26. package/dist/chunks/chunk-JOY3HZXL.js +467 -0
  27. package/dist/chunks/{chunk-GWJLAF6B.js → chunk-JWF2R6EQ.js} +0 -462
  28. package/dist/chunks/{chunk-BWYVS62Z.js → chunk-KEA4XQPO.js} +4 -4
  29. package/dist/chunks/chunk-KINXYJXM.js +205 -0
  30. package/dist/chunks/{chunk-IBSJJGXL.js → chunk-KWJEICD4.js} +2 -2
  31. package/dist/chunks/{chunk-GAMGDNTF.js → chunk-LJI4N6FV.js} +1 -1
  32. package/dist/chunks/{chunk-IU6UB2TD.js → chunk-MXCRKXOP.js} +48 -6
  33. package/dist/chunks/{chunk-PAFOLIYQ.js → chunk-NWYHCZTY.js} +1 -1
  34. package/dist/chunks/chunk-OJ4JPD25.js +428 -0
  35. package/dist/chunks/{chunk-L7TYG5SN.js → chunk-OQCK5SAU.js} +2 -2
  36. package/dist/chunks/chunk-PG5YSNYY.js +1166 -0
  37. package/dist/chunks/{chunk-XZBYRYWX.js → chunk-QJWVYOOV.js} +2 -2
  38. package/dist/chunks/{chunk-AMAPQVBT.js → chunk-QVKRNL7L.js} +286 -305
  39. package/dist/chunks/chunk-SU6IJD6D.js +49 -0
  40. package/dist/chunks/{chunk-ZWLWXHJC.js → chunk-TA2RBUTH.js} +2 -2
  41. package/dist/chunks/{chunk-6HT73VOI.js → chunk-U6Y32KEV.js} +2 -2
  42. package/dist/chunks/chunk-UUJK76HV.js +209 -0
  43. package/dist/chunks/{chunk-R3MK2RBN.js → chunk-VOMDD2C5.js} +1 -1
  44. package/dist/chunks/chunk-Y3C6MDL7.js +28 -0
  45. package/dist/chunks/chunk-ZM7RN2IM.js +38 -0
  46. package/dist/chunks/{chunk-2XED2FKY.js → chunk-ZUB4M4N3.js} +38 -36
  47. package/dist/chunks/{chunk-7QFVXP2X.js → chunk-ZWIMLT6P.js} +8 -7
  48. package/dist/chunks/cli-FULPXIKJ.js +226 -0
  49. package/dist/chunks/commands-BNWFNTD3.js +70 -0
  50. package/dist/chunks/{conflict-VPAR7E6F.js → conflict-5BKCDV2F.js} +2 -2
  51. package/dist/chunks/{contract-DDXAO2DZ.js → contract-WI23OXVC.js} +12446 -5964
  52. package/dist/chunks/{cowork-34QCHMDD.js → cowork-DZBBVNMQ.js} +11 -8
  53. package/dist/chunks/{create-flow-52PU2OBI.js → create-flow-7ZRBRKX7.js} +6 -6
  54. package/dist/chunks/{data-CLQ62QGD.js → data-PAZVE6QE.js} +6 -3
  55. package/dist/chunks/{ebuilder-form-W5R7Q22S.js → ebuilder-form-5SQXIGXN.js} +9 -6
  56. package/dist/chunks/{ehr-LCNAVMK5.js → ehr-CX5F4ZAU.js} +23 -16
  57. package/dist/chunks/{entry-mode-6Z3ZV3DE.js → entry-mode-I2BYNONZ.js} +3 -3
  58. package/dist/chunks/{env-RDKWAARB.js → env-ZAQZ7EHN.js} +2 -2
  59. package/dist/chunks/{esb-ANKPUU65.js → esb-DQTXDIBF.js} +10 -7
  60. package/dist/chunks/{factory-434B7RAT.js → factory-XRI6KZ7H.js} +1 -1
  61. package/dist/chunks/{fna-AKBSG5HI.js → fna-FK6HQVJL.js} +13 -8
  62. package/dist/chunks/{group-chat-PROTW22R.js → group-chat-MLWNYM2P.js} +3 -3
  63. package/dist/chunks/{host-WO4L5G5I.js → host-3EPREGXS.js} +6 -3
  64. package/dist/chunks/{host-XIYG4F4B.js → host-J74JGYAW.js} +6 -3
  65. package/dist/chunks/{host-7FJW4E7R.js → host-KUMU3DDK.js} +6 -3
  66. package/dist/chunks/{host-5R2SNFWD.js → host-MEC4VQZA.js} +6 -3
  67. package/dist/chunks/{host-PDJAKCT7.js → host-T6NNQGVZ.js} +6 -3
  68. package/dist/chunks/{host-CGXUFQO4.js → host-VI7Q45PM.js} +6 -3
  69. package/dist/chunks/{hrm-WGODDTEH.js → hrm-KKVAW4P5.js} +8 -5
  70. package/dist/chunks/{im-YKTKAJU3.js → im-47CIWQNL.js} +7 -4
  71. package/dist/chunks/{invoice-PVYCCCVM.js → invoice-CDYRBNIG.js} +21 -16
  72. package/dist/chunks/{jiuchuanhui-RKOQW7BY.js → jiuchuanhui-M7QTRHZK.js} +17 -10
  73. package/dist/chunks/{lazy-dispatch-DW45AFQ5.js → lazy-dispatch-FKQJZFI5.js} +22 -8
  74. package/dist/chunks/{mail-BNB5S4NW.js → mail-NRBS5N6Y.js} +11 -8
  75. package/dist/chunks/{meeting-O2KDJH66.js → meeting-WC5LD3IO.js} +22 -18
  76. package/dist/chunks/{minute-doc-JUCG56GY.js → minute-doc-OQUMDTKG.js} +4 -4
  77. package/dist/chunks/{okr-LWFGWOE7.js → okr-EHKSKMPL.js} +10 -7
  78. package/dist/chunks/{operations-532PN5OB.js → operations-V5VM5MS2.js} +7 -4
  79. package/dist/chunks/{performance-7W5COCFU.js → performance-ZJADXJPN.js} +6 -3
  80. package/dist/chunks/{plan-ZVY3IYTL.js → plan-OTDNBDJ7.js} +10 -7
  81. package/dist/chunks/{project-SA62B7MH.js → project-4XVBQ3HX.js} +10 -7
  82. package/dist/chunks/{reception-NGIONPQ3.js → reception-3FAHOOH7.js} +8 -4
  83. package/dist/chunks/{recruit-stage-WOSN6MGP.js → recruit-stage-3WTVWW2K.js} +199 -74
  84. package/dist/chunks/register-SQOPIR2G.js +16 -0
  85. package/dist/chunks/{registry-R72GWXOG.js → registry-F4YFZLOD.js} +7 -3
  86. package/dist/chunks/registry-NBTBXR4L.js +30 -0
  87. package/dist/chunks/{registry-N7P3W2RD.js → registry-TJGCVRCW.js} +7 -4
  88. package/dist/chunks/{room-recommend-KCGIVUFR.js → room-recommend-KL62XB2Y.js} +4 -4
  89. package/dist/chunks/root-YZG2TS5W.js +16 -0
  90. package/dist/chunks/{schedule-6UP27HQ4.js → schedule-XOISYUPB.js} +4 -4
  91. package/dist/chunks/{smart-extract-DDOQSPRB.js → smart-extract-UYGNV3BM.js} +15 -7
  92. package/dist/chunks/update-AV5VOXGY.js +13 -0
  93. package/dist/chunks/{workflow-V5ALD6QZ.js → workflow-V54LJPXL.js} +15 -10
  94. package/dist/cli.js +40 -0
  95. package/dist/cmd/action.js +3 -1
  96. package/dist/cmd/doctor/index.js +1 -1
  97. package/dist/cmd/e10/index.js +1 -1
  98. package/dist/cmd/identity/index.js +5 -8
  99. package/dist/cmd/index.js +2 -0
  100. package/dist/cmd/setup/index.js +1 -1
  101. package/dist/cmd/update/index.js +38 -0
  102. package/dist/core/manifest-view.js +1 -1
  103. package/dist/core/output.js +8 -1
  104. package/dist/core/runtime-agent.js +13 -0
  105. package/dist/core/update-notice.js +23 -0
  106. package/dist/index.js +105 -198
  107. package/dist/internal/e10/auth/agent-host-key.js +16 -0
  108. package/dist/internal/e10/auth/agent-hosts.js +45 -9
  109. package/dist/internal/e10/auth/commands.js +66 -36
  110. package/dist/internal/e10/auth/session.js +30 -15
  111. package/dist/internal/e10/auth/xiaoe.js +4 -20
  112. package/dist/internal/e10/auth-recovery.js +44 -4
  113. package/dist/internal/e10/context.js +5 -2
  114. package/dist/internal/update/bootstrap.js +96 -0
  115. package/dist/internal/update/npm.js +78 -0
  116. package/dist/internal/update/service.js +252 -0
  117. package/dist/internal/update/store.js +135 -0
  118. package/dist/shortcuts/archive/index.js +2 -2
  119. package/dist/shortcuts/archive/manifest.js +1 -0
  120. package/dist/shortcuts/archive/operations/search.js +3 -1
  121. package/dist/shortcuts/archive-oa/index.js +1 -1
  122. package/dist/shortcuts/asset/index.js +1 -1
  123. package/dist/shortcuts/asset-idle/index.js +1 -1
  124. package/dist/shortcuts/blog/index.js +1 -1
  125. package/dist/shortcuts/caizhilian/index.js +1 -1
  126. package/dist/shortcuts/calendar/index.js +1 -1
  127. package/dist/shortcuts/contract/data/bi-config.js +156 -0
  128. package/dist/shortcuts/contract/data/collection-ledger-html.js +189 -0
  129. package/dist/shortcuts/contract/data/collection-node-catalog.js +226 -0
  130. package/dist/shortcuts/contract/data/metric-catalog.js +154 -20
  131. package/dist/shortcuts/contract/data/report-renderers.js +414 -0
  132. package/dist/shortcuts/contract/data/report-spec.js +132 -0
  133. package/dist/shortcuts/contract/error-actions.js +114 -0
  134. package/dist/shortcuts/contract/host.js +12 -3
  135. package/dist/shortcuts/contract/index.js +17 -1
  136. package/dist/shortcuts/contract/manifest.js +398 -3
  137. package/dist/shortcuts/contract/ooxml/docx-table.js +48 -0
  138. package/dist/shortcuts/contract/operations/bi-preview.js +131 -0
  139. package/dist/shortcuts/contract/operations/bizreview-report.js +496 -0
  140. package/dist/shortcuts/contract/operations/collection-node.js +229 -0
  141. package/dist/shortcuts/contract/operations/docx-slots.js +735 -16
  142. package/dist/shortcuts/contract/operations/draft-build.js +940 -0
  143. package/dist/shortcuts/contract/operations/draft-submit.js +229 -0
  144. package/dist/shortcuts/contract/operations/first-screen.js +3 -2
  145. package/dist/shortcuts/contract/operations/generated-submit.js +175 -0
  146. package/dist/shortcuts/contract/operations/ledger-report.js +233 -0
  147. package/dist/shortcuts/contract/operations/ledger-stat.js +1400 -0
  148. package/dist/shortcuts/contract/operations/ledger.js +4 -1
  149. package/dist/shortcuts/contract/operations/metrics.js +9 -3
  150. package/dist/shortcuts/contract/operations/ops-draft.js +527 -0
  151. package/dist/shortcuts/contract/operations/page.js +9 -0
  152. package/dist/shortcuts/contract/operations/quote-submit.js +55 -229
  153. package/dist/shortcuts/contract/operations/registry.js +20 -0
  154. package/dist/shortcuts/contract/operations/sign-launch.js +256 -0
  155. package/dist/shortcuts/contract/operations/viewlink.js +334 -0
  156. package/dist/shortcuts/cowork/index.js +2 -2
  157. package/dist/shortcuts/ebuilder-form/index.js +1 -1
  158. package/dist/shortcuts/ehr/index.js +2 -2
  159. package/dist/shortcuts/ehr/manifest.js +1 -1
  160. package/dist/shortcuts/ehr/operations/recruit-position.js +7 -2
  161. package/dist/shortcuts/ehr/operations/recruit-write.js +7 -6
  162. package/dist/shortcuts/ehr/operations/recruit.js +318 -248
  163. package/dist/shortcuts/ehr/operations/shared.js +22 -2
  164. package/dist/shortcuts/esb/index.js +1 -1
  165. package/dist/shortcuts/fna/index.js +1 -1
  166. package/dist/shortcuts/fna/manifest.js +1 -0
  167. package/dist/shortcuts/fna/operations/expense-chart.js +3 -1
  168. package/dist/shortcuts/hrm/index.js +1 -1
  169. package/dist/shortcuts/invoice/index.js +1 -1
  170. package/dist/shortcuts/jiuchuanhui/index.js +2 -2
  171. package/dist/shortcuts/jiuchuanhui/manifest.js +3 -0
  172. package/dist/shortcuts/mail/index.js +2 -2
  173. package/dist/shortcuts/meeting/index.js +1 -1
  174. package/dist/shortcuts/meeting/manifest.js +1 -0
  175. package/dist/shortcuts/meeting/operations/eb/catalog.js +5 -3
  176. package/dist/shortcuts/meeting/operations/eb/conflict.js +3 -1
  177. package/dist/shortcuts/meeting/operations/eb/create-flow.js +10 -9
  178. package/dist/shortcuts/meeting/operations/eb/factory.js +2 -0
  179. package/dist/shortcuts/meeting/operations/eb/member-expand.js +3 -2
  180. package/dist/shortcuts/meeting/operations/invitation-publish.js +3 -3
  181. package/dist/shortcuts/meeting/operations/invitation.js +4 -4
  182. package/dist/shortcuts/meeting/operations/link.js +3 -1
  183. package/dist/shortcuts/okr/index.js +1 -1
  184. package/dist/shortcuts/performance/index.js +1 -1
  185. package/dist/shortcuts/plan/index.js +1 -1
  186. package/dist/shortcuts/project/index.js +1 -1
  187. package/dist/shortcuts/reception/manifest.js +2 -2
  188. package/dist/shortcuts/recruit-stage/context.js +10 -2
  189. package/dist/shortcuts/recruit-stage/index.js +16 -3
  190. package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +1 -1
  191. package/dist/shortcuts/recruit-stage/operations/interview-feedback.js +1 -1
  192. package/dist/shortcuts/recruit-stage/operations/jd-create.js +17 -8
  193. package/dist/shortcuts/recruit-stage/operations/list.js +1 -1
  194. package/dist/shortcuts/recruit-stage/operations/resume-import.js +178 -35
  195. package/dist/shortcuts/recruit-stage/operations/search.js +2 -2
  196. package/dist/shortcuts/recruit-stage/operations/shortlist.js +4 -2
  197. package/dist/shortcuts/recruit-stage/shared.js +27 -53
  198. package/dist/shortcuts/smart-extract/manifest.js +1 -0
  199. package/dist/shortcuts/smart-extract/operations/fill.js +7 -2
  200. package/dist/shortcuts/smart-extract/operations/validate.js +4 -1
  201. package/dist/shortcuts/workflow/index.js +2 -2
  202. package/dist/shortcuts/workflow/manifest.js +1 -0
  203. package/dist/shortcuts/workflow/operations/aiDeepRead/render.js +4 -1
  204. package/dist/shortcuts/workflow/operations/deepRead.js +23 -2
  205. package/dist/shortcuts/workflow/operations/form.js +8 -2
  206. package/docs/contract.md +6 -1
  207. package/docs/e10-auth.md +25 -7
  208. package/docs/operation-manual.md +15 -0
  209. package/package.json +2 -2
  210. package/scripts/pysite/__pycache__/sitecustomize.cpython-314.pyc +0 -0
  211. package/skill-template/business-info.json +28 -0
  212. package/skill-template/domains/jinchengda.md +13 -1
  213. package/skills/weaver-e10-archive-oa/references/source-manifest.json +3 -3
  214. package/skills/weaver-e10-caizhilian/references/auth-and-install.md +2 -1
  215. package/skills/weaver-e10-caizhilian/references/source-manifest.json +3 -3
  216. package/skills/weaver-e10-esb/references/source-manifest.json +3 -3
  217. package/skills/weaver-e10-jinchengda/SKILL.md +90 -32
  218. package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +45 -0
  219. package/skills/weaver-e10-jinchengda/references/contract-bizreview-report-template.html +68 -0
  220. package/skills/weaver-e10-jinchengda/references/contract-bizreview.md +216 -0
  221. package/skills/weaver-e10-jinchengda/references/contract-clause-negotiate.md +215 -0
  222. package/skills/weaver-e10-jinchengda/references/contract-collection-node.md +113 -0
  223. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +19 -3
  224. package/skills/weaver-e10-jinchengda/references/contract-decisions.md +114 -0
  225. package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +53 -44
  226. package/skills/weaver-e10-jinchengda/references/contract-element-extract.md +1 -1
  227. package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +1 -1
  228. package/skills/weaver-e10-jinchengda/references/contract-firstscreen-guide.md +200 -0
  229. package/skills/weaver-e10-jinchengda/references/contract-ledger-catalog.md +18 -1
  230. package/skills/weaver-e10-jinchengda/references/contract-ledger-query-playbook.md +138 -3
  231. package/skills/weaver-e10-jinchengda/references/contract-ledger-report.md +158 -0
  232. package/skills/weaver-e10-jinchengda/references/contract-ledger-rules.md +3 -1
  233. package/skills/weaver-e10-jinchengda/references/contract-material-gap.md +139 -0
  234. package/skills/weaver-e10-jinchengda/references/contract-object-detect.md +2 -2
  235. package/skills/weaver-e10-jinchengda/references/contract-open-web-pages.md +10 -3
  236. package/skills/weaver-e10-jinchengda/references/contract-ops-draft.md +106 -0
  237. package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +1 -1
  238. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +176 -56
  239. package/skills/weaver-e10-jinchengda/references/contract-sign-launch.md +123 -0
  240. package/skills/weaver-e10-jinchengda/references/contract-smart-draft.md +410 -0
  241. package/skills/weaver-e10-jinchengda/references/contract-template-recommend.md +1 -1
  242. package/skills/weaver-e10-jinchengda/references/contract-viewlink.md +110 -0
  243. package/skills/weaver-e10-jinchengda/references/orchestration.md +38 -24
  244. package/skills/weaver-e10-meeting/SKILL.md +13 -0
  245. package/skills/weaver-e10-okr/SKILL.md +11 -0
  246. package/skills/weaver-e10-okr/references/source-manifest.json +7 -6
  247. package/skills/weaver-e10-performance/SKILL.md +131 -39
  248. package/skills/weaver-e10-performance/agents/openai.yaml +48 -17
  249. package/skills/weaver-e10-performance/references/default-assembly.md +3 -0
  250. package/skills/weaver-e10-performance/references/extraction-guide.md +17 -3
  251. package/skills/weaver-e10-performance/references/flow-assess.md +38 -5
  252. package/skills/weaver-e10-performance/references/scheme-setting-page.md +20 -3
  253. package/skills/weaver-e10-performance/scripts/assemble_scheme.py +461 -0
  254. package/skills/weaver-e10-performance/scripts/parse_appraisal_doc.py +41 -0
  255. package/skills/weaver-e10-plan/SKILL.md +10 -0
  256. package/skills/weaver-e10-plan/references/source-manifest.json +13 -13
  257. package/skills/weaver-e10-qiyecheng/SKILL.md +2 -2
  258. package/skills/weaver-e10-qiyecheng/references/source-manifest.json +9 -9
  259. package/skills/weaver-e10-recruit-stage/SKILL.md +188 -169
  260. package/skills/weaver-e10-recruit-stage/agents/openai.yaml +55 -37
  261. package/skills/weaver-e10-recruit-stage/lib/interview-conflict.mjs +3 -0
  262. package/skills/weaver-e10-recruit-stage/lib/interview-summary.mjs +168 -35
  263. package/skills/weaver-e10-recruit-stage/lib/recruit-shortlist.mjs +175 -7
  264. package/skills/weaver-e10-recruit-stage/lib/recruit-write-helper.mjs +3 -0
  265. package/skills/weaver-e10-recruit-stage/lib/recruit-xiaoe-file.mjs +15 -1
  266. package/skills/weaver-e10-recruit-stage/lib/report-attachment.mjs +38 -0
  267. package/skills/weaver-e10-recruit-stage/lib/xiaoe-session.mjs +5 -1
  268. package/skills/weaver-e10-recruit-stage/references/env-fixed-values.md +4 -0
  269. package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +4 -0
  270. package/skills/weaver-e10-recruit-stage/references/position-templates.md +12 -8
  271. package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +16 -11
  272. package/skills/weaver-e10-recruit-stage/references/recruit-capability-check.md +10 -6
  273. package/skills/weaver-e10-recruit-stage/references/recruit-check-install.md +5 -1
  274. package/skills/weaver-e10-recruit-stage/references/recruit-detail-process.md +4 -0
  275. package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +7 -3
  276. package/skills/weaver-e10-recruit-stage/references/recruit-failure-fallback.md +6 -1
  277. package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +7 -3
  278. package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +31 -23
  279. package/skills/weaver-e10-recruit-stage/references/recruit-jd-template.md +4 -0
  280. package/skills/weaver-e10-recruit-stage/references/recruit-list-candidate.md +4 -0
  281. package/skills/weaver-e10-recruit-stage/references/recruit-list-interview.md +5 -1
  282. package/skills/weaver-e10-recruit-stage/references/recruit-maint.md +4 -0
  283. package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +16 -10
  284. package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +6 -2
  285. package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +147 -34
  286. package/skills/weaver-e10-recruit-stage/references/recruit-platform-compat.md +4 -0
  287. package/skills/weaver-e10-recruit-stage/references/recruit-report-templates.md +16 -4
  288. package/skills/weaver-e10-recruit-stage/references/recruit-resolve-creator.md +4 -0
  289. package/skills/weaver-e10-recruit-stage/references/recruit-resolve-metadata.md +8 -4
  290. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +6 -2
  291. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +24 -15
  292. package/skills/weaver-e10-recruit-stage/references/recruit-resume-parse.md +7 -3
  293. package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +7 -3
  294. package/skills/weaver-e10-recruit-stage/references/recruit-search-candidate.md +8 -4
  295. package/skills/weaver-e10-recruit-stage/references/recruit-tag-recommend.md +5 -1
  296. package/skills/weaver-e10-recruit-stage/references/recruit-urge-feedback.md +5 -1
  297. package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +5 -1
  298. package/skills/weaver-e10-recruit-stage/templates/candidate-evidence.html +41 -28
  299. package/skills/weaver-e10-recruit-stage/templates/interview-summary.html +23 -26
  300. package/skills/weaver-e10-recruit-stage/templates/match-report.html +32 -30
  301. package/skills/weaver-e10-shared/SKILL.md +40 -5
  302. package/skills/weaver-e10-shared/references/e10-auth-and-session.md +11 -1
  303. package/skills/weaver-e10-shared/references/json-output-contract.md +144 -8
  304. package/skills/weaver-e10-shared/references/weaver-e10-installation.md +11 -0
  305. package/skills/weaver-e10-shijingran/references/source-manifest.json +3 -3
  306. package/skills/weaver-e10-wenshuding/references/source-manifest.json +3 -3
  307. package/skills/weaver-e10-workflow/references/source-manifest.json +3 -3
  308. package/skills/weaver-e10-yepiaotong/references/source-manifest.json +5 -5
  309. package/dist/chunks/chunk-ICP53R52.js +0 -2849
  310. package/dist/chunks/registry-RIQ67ZT7.js +0 -27
@@ -0,0 +1,1346 @@
1
+ import { createRequire as __esbuildCreateRequire } from 'node:module';
2
+ const require = __esbuildCreateRequire(import.meta.url);
3
+ import {
4
+ clearInvoiceTokenForSession
5
+ } from "./chunk-JOY3HZXL.js";
6
+ import {
7
+ appendXiaoEAuthErrorLog,
8
+ clearXiaoEAuthErrorLog,
9
+ getXiaoEAuthErrorLogPath,
10
+ normalizeXiaoEAuthErrorLogLimit,
11
+ readXiaoEAuthErrorLog,
12
+ xiaoEAuthLogSecrets
13
+ } from "./chunk-MXCRKXOP.js";
14
+ import {
15
+ E10AuthSession,
16
+ XIAOE_AGENT_TYPE,
17
+ buildE10CookieHeader,
18
+ clearProfileAuthFile,
19
+ createXiaoEUnifiedLoginUnavailableError,
20
+ extractRawSetCookie,
21
+ extractSessionTicket,
22
+ findAuthFile,
23
+ getActiveProfile,
24
+ getE10AuthRoot,
25
+ getProfileAuthPath,
26
+ getProfileDir,
27
+ hasXiaoEEnv,
28
+ inspectXiaoEUnifiedLoginSources,
29
+ isIsolatedAgentHost,
30
+ listProfiles,
31
+ lookupAgentHost,
32
+ profileNameFromUrl,
33
+ readProfileConfig,
34
+ readTeamsCheckUserInfo,
35
+ resolveActiveProfileForHost,
36
+ resolveAgentHostKey,
37
+ resolveDefaultE10BaseUrl,
38
+ resolveLoginProfileName,
39
+ resolveSessionHostKey,
40
+ resolveXiaoEPreferredBaseUrl,
41
+ saveAuthFile,
42
+ saveProfileConfig,
43
+ setActiveProfile,
44
+ switchActiveProfile,
45
+ tryXiaoEUnifiedLogin,
46
+ upsertAgentHost
47
+ } from "./chunk-QVKRNL7L.js";
48
+ import {
49
+ isConnectorMode
50
+ } from "./chunk-Y3C6MDL7.js";
51
+ import {
52
+ CliError
53
+ } from "./chunk-UG5G54VL.js";
54
+
55
+ // src/internal/e10/auth/commands.ts
56
+ import { execFile } from "node:child_process";
57
+ import { randomBytes } from "node:crypto";
58
+ import { existsSync } from "node:fs";
59
+ import { createServer } from "node:http";
60
+ var DEFAULT_AGENT_TYPE = "weaver-work-cli";
61
+ var EXPLICIT_AGENT_TYPE_ENV_KEYS = [
62
+ "WORKBUDDY_AGENT_TYPE",
63
+ "CODEX_AGENT_TYPE",
64
+ "WEAVER_AGENT_TYPE"
65
+ ];
66
+ var AGENT_RETURN_URL_ENV_KEY = "WEAVER_AGENT_RETURN_URL";
67
+ var AGENT_RETURN_PATH = "/agent-return";
68
+ var AGENT_RETURN_TOKEN_HEADER = "x-weaver-agent-return-token";
69
+ var AGENT_RETURN_TIMEOUT_MS = 9e5;
70
+ var OAUTH_CALLBACK_PROTOCOL_MISMATCH_GRACE_MS = 3e4;
71
+ var UNSAFE_AGENT_RETURN_PROTOCOLS = /* @__PURE__ */ new Set([
72
+ "about:",
73
+ "blob:",
74
+ "data:",
75
+ "file:",
76
+ "ftp:",
77
+ "http:",
78
+ "https:",
79
+ "javascript:",
80
+ "mailto:",
81
+ "sms:",
82
+ "tel:",
83
+ "vbscript:",
84
+ "ws:",
85
+ "wss:"
86
+ ]);
87
+ var BUILT_IN_AGENT_RETURN_TARGETS = [
88
+ {
89
+ aliases: ["workbuddy"],
90
+ label: "WorkBuddy",
91
+ url: "workbuddy://"
92
+ },
93
+ {
94
+ aliases: ["xiaoe", "xiaoeclient", "\u5C0Fe", "\u667A\u80FD\u5C0Fe"],
95
+ label: "\u667A\u80FD\u5C0F E",
96
+ url: "xiaoe-client://"
97
+ },
98
+ {
99
+ aliases: ["codex", "openaicodex"],
100
+ label: "Codex",
101
+ url: "codex://"
102
+ }
103
+ ];
104
+ function asOptions(value) {
105
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
106
+ }
107
+ function optionString(options, ...keys) {
108
+ for (const key of keys) {
109
+ const value = options[key];
110
+ if (typeof value === "string" && value.trim()) return value.trim();
111
+ }
112
+ return "";
113
+ }
114
+ function envString(env, ...keys) {
115
+ for (const key of keys) {
116
+ const value = env[key];
117
+ if (typeof value === "string" && value.trim()) return value.trim();
118
+ }
119
+ return "";
120
+ }
121
+ function hasEnvPrefix(env, prefix) {
122
+ return Object.keys(env).some((key) => key === prefix || key.startsWith(`${prefix}_`));
123
+ }
124
+ function inferAgentTypeFromEnv(env) {
125
+ if (hasXiaoEEnv(env)) return XIAOE_AGENT_TYPE;
126
+ if (hasEnvPrefix(env, "WORKBUDDY")) return "workbuddy";
127
+ if (hasEnvPrefix(env, "CODEX")) return "codex";
128
+ if (hasEnvPrefix(env, "DOUBAO_OFFICE") || hasEnvPrefix(env, "DOUBAO")) return "doubao";
129
+ if (hasEnvPrefix(env, "QWENWORK") || hasEnvPrefix(env, "QWEN")) return "qwen";
130
+ return "";
131
+ }
132
+ function resolveAgentType(options = {}, env = process.env) {
133
+ return optionString(options, "agentType", "agent_type") || envString(env, ...EXPLICIT_AGENT_TYPE_ENV_KEYS) || inferAgentTypeFromEnv(env) || DEFAULT_AGENT_TYPE;
134
+ }
135
+ function resolveLoginTarget(input) {
136
+ const explicitAgentType = (input.explicitAgentType || "").trim();
137
+ const hostKey = resolveAgentHostKey(input.env, explicitAgentType);
138
+ const explicitProfile = (input.explicitProfile || "").trim();
139
+ if (explicitProfile) {
140
+ return { hostKey, profile: explicitProfile, cfg: readProfileConfig(explicitProfile) };
141
+ }
142
+ const host = lookupAgentHost(input.env, explicitAgentType);
143
+ if (host) {
144
+ const cfg = readProfileConfig(host.profile);
145
+ if (cfg.baseUrl || cfg.tenantKey) return { hostKey, profile: host.profile, cfg };
146
+ }
147
+ const active = getActiveProfile();
148
+ if (isIsolatedAgentHost(hostKey)) return { hostKey, profile: hostKey, cfg: {} };
149
+ return { hostKey, profile: active, cfg: readProfileConfig(active) };
150
+ }
151
+ function normalizeAgentKey(value) {
152
+ return value.toLowerCase().replace(/[^a-z0-9]+/gu, "");
153
+ }
154
+ function normalizeAgentAlias(value) {
155
+ return value.trim().toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu, "");
156
+ }
157
+ function builtInAgentReturnTarget(agentType) {
158
+ const alias = normalizeAgentAlias(agentType);
159
+ const target = BUILT_IN_AGENT_RETURN_TARGETS.find((candidate) => candidate.aliases.includes(alias));
160
+ return target ? { label: target.label, url: target.url } : null;
161
+ }
162
+ function conventionalAgentReturnUrl(agentType) {
163
+ const scheme = agentType.trim().toLowerCase();
164
+ if (normalizeAgentAlias(agentType) === normalizeAgentAlias(DEFAULT_AGENT_TYPE) || scheme.length > 64 || !/^[a-z][a-z0-9+.-]*$/u.test(scheme) || UNSAFE_AGENT_RETURN_PROTOCOLS.has(`${scheme}:`)) {
165
+ return "";
166
+ }
167
+ return `${scheme}://`;
168
+ }
169
+ function validateAgentReturnUrl(value) {
170
+ if (value.length > 2048 || /[\u0000-\u001f\u007f\s]/u.test(value) || !/^[a-z][a-z0-9+.-]*:\/\//iu.test(value)) {
171
+ throw new CliError("Invalid --agent-return-url value", 2 /* UsageError */);
172
+ }
173
+ let url;
174
+ try {
175
+ url = new URL(value);
176
+ } catch {
177
+ throw new CliError("Invalid --agent-return-url value", 2 /* UsageError */);
178
+ }
179
+ if (UNSAFE_AGENT_RETURN_PROTOCOLS.has(url.protocol)) {
180
+ throw new CliError("--agent-return-url must use a registered desktop application URL scheme.", 2 /* UsageError */);
181
+ }
182
+ return value;
183
+ }
184
+ function isMachineAuthMode(stdout = process.stdout, connectorMode = isConnectorMode()) {
185
+ if (connectorMode) return true;
186
+ return stdout.isTTY !== true;
187
+ }
188
+ function resolveAgentReturnTarget(options = {}, env = process.env, agentType = resolveAgentType(options, env), mode = {}) {
189
+ const builtInTarget = builtInAgentReturnTarget(agentType);
190
+ const explicitUrl = optionString(options, "agentReturnUrl") || envString(env, AGENT_RETURN_URL_ENV_KEY);
191
+ if (explicitUrl) {
192
+ return {
193
+ label: builtInTarget?.label || agentType,
194
+ url: validateAgentReturnUrl(explicitUrl)
195
+ };
196
+ }
197
+ if (mode.machine) return null;
198
+ if (builtInTarget) return builtInTarget;
199
+ const conventionalUrl = conventionalAgentReturnUrl(agentType);
200
+ return conventionalUrl ? { label: agentType, url: conventionalUrl } : null;
201
+ }
202
+ function normalizeUrl(value) {
203
+ return value.replace(/\/+$/, "");
204
+ }
205
+ function readString(data, ...keys) {
206
+ for (const key of keys) {
207
+ const value = data[key];
208
+ if (typeof value === "string" && value) return value;
209
+ if (typeof value === "number") return String(value);
210
+ }
211
+ return "";
212
+ }
213
+ function cookieString(value) {
214
+ if (!value) return "";
215
+ if (typeof value === "string") return value;
216
+ if (typeof value === "object" && !Array.isArray(value)) {
217
+ return Object.entries(value).filter(([, cookieValue2]) => cookieValue2 !== void 0 && cookieValue2 !== null && cookieValue2 !== "").map(([name, cookieValue2]) => `${name}=${String(cookieValue2)}`).join("; ");
218
+ }
219
+ return "";
220
+ }
221
+ function cookieValue(rawCookie, name) {
222
+ const match = rawCookie.match(new RegExp(`${name}=([^;]+)`));
223
+ return match?.[1] || "";
224
+ }
225
+ async function resolveAuthState(session, probe) {
226
+ if (!session) {
227
+ return { hasSessionFile: false, expired: false, reachable: void 0, authorized: false };
228
+ }
229
+ const expired = session.isExpired();
230
+ const reachable = expired ? false : probe ? await session.probeValid() : void 0;
231
+ return { hasSessionFile: true, expired, reachable, authorized: reachable !== false };
232
+ }
233
+ function formatAuthStatus(status) {
234
+ if (!status.loggedIn) {
235
+ const lines2 = ["Not logged in. Select the appropriate authentication method for the current runtime before retrying."];
236
+ if (status.hasSessionFile) {
237
+ lines2.push("session file exists but is not usable:");
238
+ lines2.push("authFile: " + status.authFile);
239
+ lines2.push("expired: " + String(status.expired));
240
+ if ("reachable" in status) lines2.push("reachable: " + String(status.reachable));
241
+ }
242
+ return lines2.join("\n");
243
+ }
244
+ const lines = [
245
+ "Logged in.",
246
+ "userId: " + status.userId,
247
+ "tenantKey: " + (status.tenantKey || ""),
248
+ "tenantName: " + (status.tenantName || ""),
249
+ "department: " + (status.department || ""),
250
+ "subcompany: " + (status.subcompany || ""),
251
+ "position: " + (status.position || ""),
252
+ "version: " + (status.version || ""),
253
+ "agentType: " + (status.agentType || ""),
254
+ "baseUrl: " + status.baseUrl,
255
+ "profile: " + status.profile,
256
+ ..."agentHost" in status && status.agentHost ? ["agentHost: " + status.agentHost] : [],
257
+ "authFile: " + status.authFile,
258
+ ..."loginSource" in status && status.loginSource ? ["loginSource: " + status.loginSource] : [],
259
+ ..."credentialSourceStep" in status && status.credentialSourceStep ? ["credentialSourceStep: " + status.credentialSourceStep] : [],
260
+ ..."credentialSourceType" in status && status.credentialSourceType ? ["credentialSourceType: " + status.credentialSourceType] : [],
261
+ ..."credentialSourceLabel" in status && status.credentialSourceLabel ? ["credentialSourceLabel: " + status.credentialSourceLabel] : [],
262
+ ..."expiryTimes" in status && status.expiryTimes ? ["expiryTimes: " + status.expiryTimes] : []
263
+ ];
264
+ if ("reachable" in status) {
265
+ lines.push("reachable: " + String(status.reachable));
266
+ }
267
+ return lines.join("\n");
268
+ }
269
+ function formatLoginResult(result) {
270
+ return [
271
+ "Saved E10 auth.",
272
+ "userId: " + result.userId,
273
+ "tenantKey: " + result.tenantKey,
274
+ "tenantName: " + result.tenantName,
275
+ "baseUrl: " + result.baseUrl,
276
+ "profile: " + result.profile,
277
+ "authFile: " + result.authFile,
278
+ ...result.loginSource ? ["loginSource: " + result.loginSource] : [],
279
+ ...result.credentialSourceStep ? ["credentialSourceStep: " + result.credentialSourceStep] : [],
280
+ ...result.credentialSourceType ? ["credentialSourceType: " + result.credentialSourceType] : [],
281
+ ...result.credentialSourceLabel ? ["credentialSourceLabel: " + result.credentialSourceLabel] : [],
282
+ ...result.expiryTimes ? ["expiryTimes: " + result.expiryTimes] : []
283
+ ].join("\n");
284
+ }
285
+ async function clearInvoiceTokenCache(profile, authData) {
286
+ if (!authData.baseUrl || !authData.userId) return;
287
+ await clearInvoiceTokenForSession({
288
+ baseUrl: normalizeUrl(authData.baseUrl),
289
+ profile,
290
+ userId: authData.userId
291
+ }).catch(() => false);
292
+ }
293
+ function posixShellQuote(value) {
294
+ return `'${value.replace(/'/g, "'\\''")}'`;
295
+ }
296
+ function powershellQuote(value) {
297
+ return `'${value.replace(/'/g, "''")}'`;
298
+ }
299
+ function resolveWeaverEnvShell(shell, platform = process.platform) {
300
+ if (shell === "auto") return platform === "win32" ? "powershell" : "posix";
301
+ if (shell === "posix" || shell === "powershell") return shell;
302
+ throw new CliError("Invalid --shell value. Use auto, posix, or powershell.", 2 /* UsageError */);
303
+ }
304
+ function formatWeaverEnvExports(value, shell = "auto", platform = process.platform) {
305
+ const resolved = resolveWeaverEnvShell(shell, platform);
306
+ return Object.entries(value).map(([name, envValue]) => resolved === "powershell" ? `$env:${name} = ${powershellQuote(envValue)}` : `export ${name}=${posixShellQuote(envValue)}`).join("\n");
307
+ }
308
+ function esc(value) {
309
+ return String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
310
+ }
311
+ function renderE10LoginSuccessPage(userId, returnTarget = null, launchToken = "") {
312
+ const safeReturnTarget = returnTarget ? { ...returnTarget, url: validateAgentReturnUrl(returnTarget.url) } : null;
313
+ const agentKey = safeReturnTarget ? normalizeAgentKey(safeReturnTarget.label) || "agent" : "";
314
+ const returnAction = safeReturnTarget && launchToken ? `<div class="overlay" data-agent-return data-token="${esc(launchToken)}" data-agent-key="${esc(agentKey)}" data-agent-label="${esc(safeReturnTarget.label)}" data-fallback-url="${esc(safeReturnTarget.url)}"><section class="prompt" role="dialog" aria-modal="true" aria-labelledby="agent-return-title"><div class="app-icon" aria-hidden="true"><svg viewBox="0 0 64 64"><defs><linearGradient id="app-gradient" x1="8" y1="4" x2="56" y2="60" gradientUnits="userSpaceOnUse"><stop stop-color="#24d3b5"/><stop offset="1" stop-color="#08aa82"/></linearGradient></defs><rect width="64" height="64" rx="16" fill="url(#app-gradient)"/><path d="M18 21.5 32 13l14 8.5v17L32 47 18 38.5v-17Z" fill="#fff" fill-opacity=".96"/><rect x="23" y="25" width="18" height="15" rx="6" fill="#12b991"/><circle cx="28.5" cy="32.5" r="1.8" fill="#fff"/><circle cx="35.5" cy="32.5" r="1.8" fill="#fff"/></svg></div><h1 id="agent-return-title">\u662F\u5426\u6253\u5F00\u201C${esc(safeReturnTarget.label)}\u201D\uFF1F</h1><p>\u767B\u5F55\u6388\u6743\u5DF2\u5B8C\u6210\uFF0C\u8FD4\u56DE ${esc(safeReturnTarget.label)} \u7EE7\u7EED\u4F7F\u7528\u3002</p><button class="primary" type="button" data-action="open">\u6253\u5F00\u201C${esc(safeReturnTarget.label)}\u201D</button><button class="secondary" type="button" data-action="always">\u59CB\u7EC8\u6253\u5F00\u201C${esc(safeReturnTarget.label)}\u201D</button><button class="secondary" type="button" data-action="cancel">\u53D6\u6D88</button><div class="status" role="status" aria-live="polite"></div></section></div>` : "";
315
+ const returnScript = safeReturnTarget && launchToken ? `<script nonce="${esc(launchToken)}">(()=>{const root=document.querySelector('[data-agent-return]');if(!root)return;const status=root.querySelector('.status');const buttons=[...root.querySelectorAll('button')];const agentLabel=root.dataset.agentLabel||'\u5E94\u7528';const fallbackUrl=root.dataset.fallbackUrl||'';const storageKey='weaver-work-cli.agent-return.'+root.dataset.agentKey;let busy=false;const setBusy=value=>{busy=value;buttons.forEach(button=>{button.disabled=value;});};const closePrompt=()=>{root.hidden=true;};const savePreference=()=>{try{localStorage.setItem(storageKey,'1');}catch{}};const clearPreference=()=>{try{localStorage.removeItem(storageKey);}catch{}};const hasPreference=()=>{try{return localStorage.getItem(storageKey)==='1';}catch{return false;}};const post=async action=>{let response;try{response=await fetch('${AGENT_RETURN_PATH}?action='+encodeURIComponent(action),{method:'POST',headers:{'${AGENT_RETURN_TOKEN_HEADER}':root.dataset.token}});}catch{return false;}if(!response.ok)throw new Error(await response.text()||'\u8BF7\u6C42\u5931\u8D25');return true;};const openAgent=async persist=>{if(busy)return;setBusy(true);status.textContent='\u6B63\u5728\u6253\u5F00 '+agentLabel+'\u2026';try{const openedLocally=await post('open');if(persist)savePreference();if(!openedLocally){closePrompt();window.location.href=fallbackUrl;return;}closePrompt();}catch(error){if(persist)clearPreference();status.textContent=error instanceof Error?error.message:'\u65E0\u6CD5\u6253\u5F00\u5E94\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002';setBusy(false);}};root.querySelector('[data-action="open"]').addEventListener('click',()=>openAgent(false));root.querySelector('[data-action="always"]').addEventListener('click',()=>openAgent(true));root.querySelector('[data-action="cancel"]').addEventListener('click',()=>{if(busy)return;clearPreference();closePrompt();post('cancel').catch(()=>{});});if(hasPreference())openAgent(false);})();</script>` : "";
316
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>weaver-work-cli \u767B\u5F55\u6210\u529F</title><style>:root{color-scheme:light}*{box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif;background:radial-gradient(circle at 50% 18%,#eefbf8 0,#f6f7f9 42%,#eef1f5 100%);color:#20242a;display:grid;place-items:center;min-height:100vh;margin:0}.card{background:rgba(255,255,255,.88);border:1px solid #e6e8ec;border-radius:18px;padding:34px 38px;box-shadow:0 18px 55px rgba(18,24,40,.09);width:min(560px,calc(100vw - 40px));text-align:center}.title{font-size:24px;font-weight:700;margin-bottom:10px}.desc{color:#667085;font-size:15px;line-height:24px}.user{color:#98a2b3;font-size:12px;margin-top:18px}.overlay{position:fixed;inset:0;z-index:10;display:grid;place-items:center;padding:20px;background:rgba(28,34,41,.36);backdrop-filter:blur(5px)}.overlay[hidden]{display:none}.prompt{width:min(410px,calc(100vw - 32px));padding:32px 28px 26px;border:1px solid rgba(255,255,255,.75);border-radius:24px;background:rgba(250,250,251,.97);box-shadow:0 24px 70px rgba(15,23,42,.28);text-align:center}.app-icon{width:74px;height:74px;margin:0 auto 24px;filter:drop-shadow(0 8px 14px rgba(8,170,130,.22))}.app-icon svg{display:block;width:100%;height:100%}.prompt h1{margin:0;font-size:20px;line-height:30px;font-weight:700;letter-spacing:-.2px}.prompt p{margin:10px 0 24px;color:#667085;font-size:14px;line-height:22px}.prompt button{display:block;width:100%;min-height:40px;border:0;border-radius:12px;font:600 16px/22px inherit;cursor:pointer;transition:transform .12s ease,filter .12s ease}.prompt button+button{margin-top:10px}.prompt button:hover{filter:brightness(.98)}.prompt button:active{transform:scale(.99)}.prompt button:disabled{cursor:wait;opacity:.62}.primary{background:linear-gradient(180deg,#2f91ff,#0b74e5);color:#fff;box-shadow:0 8px 18px rgba(11,116,229,.2)}.secondary{background:#e9eaec;color:#22252a}.status{min-height:18px;margin-top:14px;color:#667085;font-size:12px;line-height:18px}</style></head><body><main class="card"><div class="title">\u767B\u5F55\u6388\u6743\u6210\u529F</div><div class="desc">\u4F60\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u8FD4\u56DE\u667A\u80FD\u4F53\u6216\u7EC8\u7AEF\u7EE7\u7EED\u4F7F\u7528\u3002</div><div class="user">${esc(userId)}</div></main>${returnAction}${returnScript}</body></html>`;
317
+ }
318
+ function defaultFileExists(file) {
319
+ try {
320
+ return existsSync(file);
321
+ } catch {
322
+ return false;
323
+ }
324
+ }
325
+ function firstExisting(candidates, exists) {
326
+ return candidates.find((candidate) => exists(candidate)) ?? null;
327
+ }
328
+ function resolveWindowsRundll32Path(env = process.env, exists = defaultFileExists) {
329
+ const systemRoot = (env.SystemRoot || env.windir || env.WINDIR || "C:\\Windows").replace(/[\\/]+$/, "");
330
+ return firstExisting(
331
+ [
332
+ // 常规路径;32 位进程下会被 WOW64 重定向到 SysWOW64,同样可正常 ShellExecute。
333
+ `${systemRoot}\\System32\\rundll32.exe`,
334
+ // 仅 32 位进程可见的虚拟目录,作为兜底;64 位进程探测会返回 false。
335
+ `${systemRoot}\\Sysnative\\rundll32.exe`
336
+ ],
337
+ exists
338
+ ) ?? "rundll32.exe";
339
+ }
340
+ function closeHttpServer(server, onClosed, graceMs = 500) {
341
+ let closed = false;
342
+ let timer = null;
343
+ const done = () => {
344
+ if (closed) return;
345
+ closed = true;
346
+ if (timer) clearTimeout(timer);
347
+ onClosed();
348
+ };
349
+ try {
350
+ server.close(done);
351
+ server.closeIdleConnections?.();
352
+ timer = setTimeout(() => {
353
+ try {
354
+ server.closeAllConnections?.();
355
+ } catch {
356
+ }
357
+ done();
358
+ }, graceMs);
359
+ timer.unref?.();
360
+ } catch {
361
+ done();
362
+ }
363
+ }
364
+ function resolveBrowserOpenCommand(url, platform = process.platform, options = {}) {
365
+ const exists = options.exists ?? defaultFileExists;
366
+ const env = options.env ?? process.env;
367
+ if (platform === "win32") {
368
+ return { file: resolveWindowsRundll32Path(env, exists), args: ["url.dll,FileProtocolHandler", url] };
369
+ }
370
+ if (platform === "darwin") {
371
+ return { file: firstExisting(["/usr/bin/open"], exists) ?? "open", args: [url] };
372
+ }
373
+ return { file: firstExisting(["/usr/bin/xdg-open", "/bin/xdg-open"], exists) ?? "xdg-open", args: [url] };
374
+ }
375
+ function describeOpenFailure(error) {
376
+ if (error instanceof Error) {
377
+ const code = error.code;
378
+ return code ? `${code}: ${error.message}` : error.message;
379
+ }
380
+ return String(error);
381
+ }
382
+ function openUrlInBrowser(url, ctx) {
383
+ const command = resolveBrowserOpenCommand(url);
384
+ execFile(command.file, command.args, (error) => {
385
+ if (error) {
386
+ ctx.logger.warn(
387
+ `Could not open browser automatically (${command.file}: ${describeOpenFailure(error)}). Copy the login URL manually.`
388
+ );
389
+ }
390
+ });
391
+ }
392
+ function openUrlWithSystemHandler(url) {
393
+ const command = resolveBrowserOpenCommand(url);
394
+ return new Promise((resolve, reject) => {
395
+ execFile(command.file, command.args, (error) => {
396
+ if (error) reject(error);
397
+ else resolve();
398
+ });
399
+ });
400
+ }
401
+ var PROMOTION_KEYWORD_RULES = [
402
+ { keyword: "xiaoe", aliases: ["xiaoe", "\u5C0Fe", "\u667A\u80FD\u5C0Fe"] },
403
+ { keyword: "workbuddy", aliases: ["workbuddy"] },
404
+ { keyword: "codex", aliases: ["codex", "openaicodex"] },
405
+ { keyword: "doubao", aliases: ["doubao", "\u8C46\u5305", "\u8C46\u5305\u529E\u516C"] },
406
+ { keyword: "qianwen", aliases: ["qwen", "qianwen", "qwenwork", "\u5343\u95EE", "\u901A\u4E49\u5343\u95EE", "\u5343\u95EE\u529E\u516C"] }
407
+ ];
408
+ function resolvePromotionKeyword(agentType) {
409
+ const normalized = normalizeAgentAlias(agentType);
410
+ if (!normalized) return "";
411
+ const matched = PROMOTION_KEYWORD_RULES.find(
412
+ ({ aliases }) => aliases.some((alias) => normalized.startsWith(alias))
413
+ );
414
+ return matched ? matched.keyword : "";
415
+ }
416
+ var PROMOTION_SOURCES = {
417
+ qianwen: "188",
418
+ doubao: "187",
419
+ workbuddy: "186"
420
+ };
421
+ function resolvePromotionSource(promotionKeyword) {
422
+ if (!promotionKeyword) return "";
423
+ return PROMOTION_SOURCES[promotionKeyword] || "";
424
+ }
425
+ function buildE10AuthorizeUrl(baseUrl, redirectUri, agentType, promotionKeyword = resolvePromotionKeyword(agentType), promotionSource = resolvePromotionSource(promotionKeyword)) {
426
+ const authorizeParams = new URLSearchParams({
427
+ redirect_uri: redirectUri,
428
+ response_type: "code",
429
+ access_type: "agent",
430
+ agent_type: agentType,
431
+ from: agentType
432
+ });
433
+ if (promotionKeyword) authorizeParams.set("promotionKeyword", promotionKeyword);
434
+ if (promotionSource) authorizeParams.set("promotionSource", promotionSource);
435
+ return `${baseUrl}/papi/sso/oauth2.0/authorize?${authorizeParams.toString()}`;
436
+ }
437
+ function isTlsClientHello(error) {
438
+ if (!error || typeof error !== "object") return false;
439
+ const rawPacket = error.rawPacket;
440
+ return Buffer.isBuffer(rawPacket) && rawPacket.length >= 3 && rawPacket[0] === 22 && rawPacket[1] === 3;
441
+ }
442
+ function createOAuthCallbackProtocolMismatchError(port) {
443
+ return Object.assign(new CliError(
444
+ `OAuth callback protocol mismatch: the browser connected to https://127.0.0.1:${port}, but the CLI callback listener uses HTTP. Retry the login and, on the callback error page, change only the URL scheme to http:// before reloading; keep the path and query unchanged. The E10 authorization service should preserve HTTP loopback redirect URIs.`,
445
+ 3 /* AuthError */
446
+ ), {
447
+ type: "authentication",
448
+ subtype: "oauth_callback_protocol_mismatch",
449
+ retryable: false,
450
+ stage: "oauth_callback"
451
+ });
452
+ }
453
+ async function readJsonObject(resp) {
454
+ const data = await resp.json().catch(() => ({}));
455
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
456
+ }
457
+ async function resolveUserInfo(baseUrl, eteamsId, rawCookie = "", agentType = "") {
458
+ const resp = await fetch(`${baseUrl}/api/baseserver/layout/teamsCheck?clientType=not_xinchuang&client=WEB&domainName=${encodeURIComponent(baseUrl)}`, {
459
+ method: "POST",
460
+ headers: {
461
+ accept: "application/json",
462
+ "content-type": "application/json",
463
+ eteamsid: eteamsId,
464
+ cookie: buildE10CookieHeader(rawCookie, eteamsId, agentType),
465
+ "user-agent": agentType ? `AgentType=${agentType},IsAgent=true` : DEFAULT_AGENT_TYPE,
466
+ origin: baseUrl
467
+ },
468
+ redirect: "manual"
469
+ });
470
+ const data = await resp.json().catch(() => ({}));
471
+ return { userInfo: readTeamsCheckUserInfo(resp, data), setCookie: extractRawSetCookie(resp) };
472
+ }
473
+ async function saveEteamsIdLogin(input) {
474
+ const baseUrl = normalizeUrl(input.baseUrl);
475
+ const passportUrl = normalizeUrl(input.passportUrl || baseUrl);
476
+ const { userInfo, setCookie } = await resolveUserInfo(baseUrl, input.eteamsId, input.rawCookie || "", input.agentType);
477
+ if (!userInfo.userId) {
478
+ throw new CliError("Could not resolve userId. Check whether ETEAMSID is valid for this E10 domain.", 3 /* AuthError */);
479
+ }
480
+ const tenantKey = userInfo.tenantKey || input.tenantKeyFallback;
481
+ const profile = resolveLoginProfileName({
482
+ derivedName: profileNameFromUrl(baseUrl),
483
+ baseUrl,
484
+ hostKey: input.hostKey,
485
+ profileHint: input.profileHint
486
+ });
487
+ setActiveProfile(profile);
488
+ const cookies = { ETEAMSID: input.eteamsId };
489
+ if (input.rawCookie) cookies.raw = input.rawCookie;
490
+ const ztSession = extractSessionTicket(setCookie, input.rawCookie || "");
491
+ const authData = {
492
+ cookies,
493
+ userId: userInfo.userId,
494
+ tenantKey,
495
+ tenantName: userInfo.tenantName,
496
+ department: userInfo.department,
497
+ subcompany: userInfo.subcompany,
498
+ position: userInfo.position,
499
+ agentType: input.agentType,
500
+ version: input.version || "",
501
+ baseUrl,
502
+ passportUrl,
503
+ cookieSavedAt: Date.now(),
504
+ ...ztSession ? { ztSession } : {}
505
+ };
506
+ await clearInvoiceTokenCache(profile, authData);
507
+ const authFile = saveAuthFile(authData, profile);
508
+ saveProfileConfig(baseUrl, passportUrl, profile, tenantKey);
509
+ upsertAgentHost({ profile, baseUrl, tenantKey, agentType: input.agentType, hostKey: input.hostKey });
510
+ return {
511
+ ...userInfo,
512
+ tenantKey,
513
+ eteamsId: input.eteamsId,
514
+ baseUrl,
515
+ passportUrl,
516
+ profile,
517
+ authFile,
518
+ agentType: input.agentType,
519
+ version: input.version || ""
520
+ };
521
+ }
522
+ async function tryXiaoEUnifiedLogin2(ctx, baseUrl, tenantKeyFallback, profileHint, allowTokenScript = false, diagnostics, hostKey) {
523
+ const login = await tryXiaoEUnifiedLogin({
524
+ env: ctx.env,
525
+ baseUrl,
526
+ allowBundledEnvScript: true,
527
+ tenantKeyFallback,
528
+ profileHint,
529
+ allowTokenScript,
530
+ logger: ctx.logger,
531
+ diagnostics,
532
+ hostKey
533
+ });
534
+ return login?.result || null;
535
+ }
536
+ async function oidcExchange(code, redirectUri, baseUrl, tenantKeyFallback, agentTypeFallback, profileHint, hostKey) {
537
+ const base = normalizeUrl(baseUrl);
538
+ const tokenParams = new URLSearchParams({
539
+ grant_type: "authorization_code",
540
+ code,
541
+ redirect_uri: redirectUri
542
+ });
543
+ const tokenResp = await fetch(`${base}/papi/sso/oauth2.0/accessToken`, {
544
+ method: "POST",
545
+ headers: { "content-type": "application/x-www-form-urlencoded" },
546
+ body: tokenParams.toString(),
547
+ redirect: "manual"
548
+ });
549
+ const tokenData = await readJsonObject(tokenResp);
550
+ const businessStatus = Number(tokenData.status);
551
+ const businessFailed = Number.isFinite(businessStatus) && businessStatus >= 400;
552
+ if (tokenResp.status >= 400 || businessFailed) {
553
+ const message = readString(tokenData, "message", "msg", "error_description", "error") || `OAuth token exchange failed: ${businessFailed ? businessStatus : tokenResp.status}`;
554
+ const code2 = readString(tokenData, "code");
555
+ throw new CliError(code2 ? `${message} (code ${code2})` : message, 3 /* AuthError */);
556
+ }
557
+ let eteamsId = readString(tokenData, "eteamsId", "eteamsid");
558
+ let userId = readString(tokenData, "id", "userId", "employeeId");
559
+ let rawCookies = cookieString(tokenData.cookies || tokenData.cookie) || extractRawSetCookie(tokenResp);
560
+ let agentType = agentTypeFallback || readString(tokenData, "agentType", "agent_type");
561
+ let version = readString(tokenData, "version", "baselineVersion");
562
+ const accessToken = readString(tokenData, "access_token", "accessToken");
563
+ if (!eteamsId) eteamsId = cookieValue(rawCookies, "ETEAMSID");
564
+ if (accessToken && (!eteamsId || !userId || !rawCookies || !version || !agentType)) {
565
+ const profileResp = await fetch(`${base}/papi/sso/oauth2.0/profile?access_token=${encodeURIComponent(accessToken)}`, {
566
+ method: "POST",
567
+ headers: { accept: "application/json" },
568
+ redirect: "manual"
569
+ });
570
+ const profileData = await readJsonObject(profileResp);
571
+ const profileRawCookies = cookieString(profileData.cookies || profileData.cookie) || extractRawSetCookie(profileResp);
572
+ if (!eteamsId) eteamsId = readString(profileData, "eteamsId", "eteamsid") || cookieValue(profileRawCookies, "ETEAMSID");
573
+ if (!userId) userId = readString(profileData, "id", "userId", "employeeId");
574
+ if (!rawCookies) rawCookies = profileRawCookies;
575
+ if (!agentType) agentType = readString(profileData, "agentType", "agent_type");
576
+ if (!version) version = readString(profileData, "version", "baselineVersion");
577
+ }
578
+ if (!eteamsId) {
579
+ throw new CliError("Could not resolve ETEAMSID from OAuth response.", 3 /* AuthError */);
580
+ }
581
+ const { userInfo, setCookie } = await resolveUserInfo(base, eteamsId, rawCookies, agentType).catch(() => ({
582
+ userInfo: {
583
+ userId: "",
584
+ tenantKey: "",
585
+ tenantName: "",
586
+ department: "",
587
+ subcompany: "",
588
+ position: ""
589
+ },
590
+ setCookie: ""
591
+ }));
592
+ const tenantKey = readString(tokenData, "tenant_key", "tenantKey") || userInfo.tenantKey || tenantKeyFallback;
593
+ const ztSession = extractSessionTicket(setCookie, rawCookies);
594
+ const authData = {
595
+ cookies: { ETEAMSID: eteamsId, raw: rawCookies },
596
+ userId: userInfo.userId || userId || "unknown",
597
+ tenantKey,
598
+ tenantName: userInfo.tenantName,
599
+ department: userInfo.department,
600
+ subcompany: userInfo.subcompany,
601
+ position: userInfo.position,
602
+ agentType,
603
+ version,
604
+ baseUrl: base,
605
+ passportUrl: base,
606
+ cookieSavedAt: Date.now(),
607
+ ...ztSession ? { ztSession } : {}
608
+ };
609
+ const profile = resolveLoginProfileName({
610
+ derivedName: profileNameFromUrl(base),
611
+ baseUrl: base,
612
+ hostKey,
613
+ profileHint
614
+ });
615
+ setActiveProfile(profile);
616
+ await clearInvoiceTokenCache(profile, authData);
617
+ const authFile = saveAuthFile(authData, profile);
618
+ saveProfileConfig(base, base, profile, tenantKey);
619
+ upsertAgentHost({ profile, baseUrl: base, tenantKey, agentType: agentTypeFallback, hostKey });
620
+ return {
621
+ userId: authData.userId,
622
+ tenantKey,
623
+ tenantName: authData.tenantName || "",
624
+ department: authData.department || "",
625
+ subcompany: authData.subcompany || "",
626
+ position: authData.position || "",
627
+ eteamsId,
628
+ baseUrl: base,
629
+ passportUrl: base,
630
+ profile,
631
+ authFile,
632
+ agentType,
633
+ version
634
+ };
635
+ }
636
+ function xiaoEUnifiedLoginUnavailableMessage(baseUrl, attempted) {
637
+ return [
638
+ attempted ? "XiaoE \u7EDF\u4E00\u767B\u5F55\u5DF2\u5C1D\u8BD5\uFF0C\u4F46\u672A\u83B7\u53D6\u5230\u53EF\u7528\u4F1A\u8BDD\u3002" : "\u672A\u68C0\u6D4B\u5230\u53EF\u7528\u7684 XiaoE \u7EDF\u4E00\u767B\u5F55\u51ED\u636E\u6E90\uFF0C\u672C\u6B21\u672A\u5C1D\u8BD5\u7EDF\u4E00\u767B\u5F55\u3002",
639
+ "`auth xiaoe` \u4E0D\u4F1A\u964D\u7EA7\u5230\u6D4F\u89C8\u5668 OAuth\u3002",
640
+ baseUrl ? `\u5F53\u524D E10 baseUrl: ${baseUrl}\u3002` : "\u672A\u4ECE XiaoE \u51ED\u8BC1\u4E2D\u89E3\u6790\u5230 E10 baseUrl\u3002",
641
+ attempted ? "CLI \u5DF2\u4F9D\u6B21\u5C1D\u8BD5\u5E73\u53F0\u6CE8\u5165\u51ED\u8BC1\u7684 Node \u6362\u7968\u3001CLI \u5185\u7F6E xiaoe_env.py \u517C\u5BB9\u6362\u7968\u3001\u5BBF\u4E3B xiaoeUserData/tokens.py\u3001\u684C\u9762 XiaoE \u5BA2\u6237\u7AEF\u51ED\u8BC1\uFF08XiaoE/Robots/*/user_settings.json\uFF09\u548C WEAVER_XIAOE_* \u73AF\u5883\u6620\u5C04\u3002" : "CLI \u5DF2\u68C0\u67E5\u5E73\u53F0\u6CE8\u5165\u51ED\u8BC1\u3001\u5BBF\u4E3B xiaoeUserData/tokens.py\u3001\u684C\u9762 XiaoE \u5BA2\u6237\u7AEF\u51ED\u8BC1\uFF08XiaoE/Robots/*/user_settings.json\uFF09\u548C WEAVER_XIAOE_* \u73AF\u5883\u6620\u5C04\u3002",
642
+ "CLI \u4F1A\u4F18\u5148\u4F7F\u7528 XiaoE \u5BA2\u6237\u7AEF\u5185\u7F6E Python \u6267\u884C tokens.py\uFF1B\u81EA\u52A8\u53D1\u73B0\u4E0D\u53EF\u7528\u65F6\uFF0C\u53EF\u7528 WEAVER_XIAOE_TOKEN_SCRIPT_PYTHON \u6307\u5B9A\u517C\u5BB9\u89E3\u91CA\u5668\u3002"
643
+ ].join(" ");
644
+ }
645
+ async function runXiaoELogin(ctx, options) {
646
+ const commandOpts = asOptions(options);
647
+ const globalOptions = ctx.getGlobalOptions();
648
+ const profileFromGlobal = globalOptions.profile;
649
+ const hostKey = "xiaoe";
650
+ const cfg = readProfileConfig(profileFromGlobal || resolveActiveProfileForHost(ctx.env, { runtimeAgent: "xiaoe" }));
651
+ const explicitBaseUrl = optionString(commandOpts, "baseUrl") || globalOptions.baseUrl || "";
652
+ const preferredXiaoEBaseUrl = resolveXiaoEPreferredBaseUrl({
653
+ explicitBaseUrl,
654
+ profileBaseUrl: cfg.baseUrl,
655
+ env: ctx.env
656
+ });
657
+ const xiaoESources = inspectXiaoEUnifiedLoginSources({
658
+ env: ctx.env,
659
+ baseUrl: preferredXiaoEBaseUrl,
660
+ profileBaseUrl: cfg.baseUrl,
661
+ allowTokenScript: true
662
+ });
663
+ const useXiaoELogin = xiaoESources.any;
664
+ const baseUrl = preferredXiaoEBaseUrl;
665
+ const tenantKey = optionString(commandOpts, "tenantKey");
666
+ const diagnostics = {
667
+ attemptedSteps: [],
668
+ baseUrl,
669
+ clientType: xiaoESources.clientType,
670
+ platformCredentialDetected: xiaoESources.platformCredential
671
+ };
672
+ if (!useXiaoELogin) {
673
+ diagnostics.attemptedSteps.push(
674
+ "platform_token:missing",
675
+ "bundled_env_script:missing",
676
+ xiaoESources.clientType === "cloud" ? "token_script:disabled" : "token_script:missing",
677
+ xiaoESources.clientType === "cloud" ? "client_session:disabled" : "client_session:missing",
678
+ "environment_map:empty"
679
+ );
680
+ }
681
+ ctx.logger.info([
682
+ "XiaoE unified login preflight:",
683
+ "authMode=xiaoe",
684
+ `credentialSourceDetected=${String(xiaoESources.any)}`,
685
+ `attempted=${String(useXiaoELogin)}`,
686
+ `platformCredentialDetected=${String(xiaoESources.platformCredential)}`,
687
+ `tokenScriptDetected=${String(xiaoESources.tokenScript)}`,
688
+ `clientSettingsDetected=${String(xiaoESources.clientCredential)}`,
689
+ `environmentCredentialDetected=${String(xiaoESources.environmentCredential)}`,
690
+ `clientType=${xiaoESources.clientType || "(unset)"}`,
691
+ `baseUrl=${baseUrl || "(unresolved)"}`
692
+ ].join(" "));
693
+ if (useXiaoELogin) {
694
+ try {
695
+ const xiaoEResult = await tryXiaoEUnifiedLogin2(
696
+ ctx,
697
+ baseUrl,
698
+ tenantKey,
699
+ profileFromGlobal,
700
+ true,
701
+ diagnostics,
702
+ hostKey
703
+ );
704
+ if (xiaoEResult) return xiaoEResult;
705
+ } catch (error2) {
706
+ await appendXiaoEAuthErrorLog({
707
+ source: "login",
708
+ profile: profileFromGlobal || resolveActiveProfileForHost(ctx.env),
709
+ baseUrl,
710
+ diagnostics,
711
+ error: error2,
712
+ secrets: xiaoEAuthLogSecrets(ctx.env)
713
+ }).catch((logError) => ctx.logger.debug(
714
+ `Could not persist XiaoE auth error log: ${logError instanceof Error ? logError.message : String(logError)}`
715
+ ));
716
+ throw error2;
717
+ }
718
+ }
719
+ ctx.logger.warn(xiaoEUnifiedLoginUnavailableMessage(baseUrl, useXiaoELogin));
720
+ const error = createXiaoEUnifiedLoginUnavailableError(baseUrl);
721
+ await appendXiaoEAuthErrorLog({
722
+ source: "login",
723
+ profile: profileFromGlobal || resolveActiveProfileForHost(ctx.env),
724
+ baseUrl,
725
+ diagnostics,
726
+ error,
727
+ secrets: xiaoEAuthLogSecrets(ctx.env)
728
+ }).catch((logError) => ctx.logger.debug(
729
+ `Could not persist XiaoE auth error log: ${logError instanceof Error ? logError.message : String(logError)}`
730
+ ));
731
+ throw error;
732
+ }
733
+ async function runBrowserLogin(ctx, options, loginMode = {}) {
734
+ const commandOpts = asOptions(options);
735
+ const globalOptions = ctx.getGlobalOptions();
736
+ const profileFromGlobal = globalOptions.profile;
737
+ const explicitBaseUrl = optionString(commandOpts, "baseUrl") || globalOptions.baseUrl || "";
738
+ const explicitAgentType = optionString(commandOpts, "agentType", "agent_type");
739
+ const agentType = resolveAgentType(commandOpts, ctx.env);
740
+ const target = resolveLoginTarget({
741
+ env: ctx.env,
742
+ explicitProfile: profileFromGlobal,
743
+ explicitAgentType
744
+ });
745
+ const hostKey = target.hostKey;
746
+ const baseUrl = normalizeUrl(explicitBaseUrl || target.cfg.baseUrl || resolveDefaultE10BaseUrl(ctx.env));
747
+ const tenantKey = optionString(commandOpts, "tenantKey");
748
+ const explicitPort = optionString(commandOpts, "port");
749
+ const portText = explicitPort || "19800";
750
+ let port = Number(portText);
751
+ if (!/^\d+$/u.test(portText) || !Number.isInteger(port) || port < 0 || port > 65535) {
752
+ throw new CliError("Invalid --port value", 2 /* UsageError */);
753
+ }
754
+ const machineMode = loginMode.machine === true || isMachineAuthMode();
755
+ const agentReturnTarget = loginMode.machine === true ? null : resolveAgentReturnTarget(commandOpts, ctx.env, agentType, { machine: machineMode });
756
+ const agentReturnToken = agentReturnTarget ? randomBytes(24).toString("base64url") : "";
757
+ const successHeaders = {
758
+ "cache-control": "no-store",
759
+ "content-security-policy": agentReturnTarget ? `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${agentReturnToken}'; connect-src 'self'` : `default-src 'none'; style-src 'unsafe-inline'`,
760
+ "content-type": "text/html; charset=utf-8",
761
+ "referrer-policy": "no-referrer",
762
+ "x-content-type-options": "nosniff",
763
+ "x-frame-options": "DENY"
764
+ };
765
+ let redirectUri = "";
766
+ if (machineMode && !agentReturnTarget) {
767
+ ctx.logger.info("Machine mode: closing the callback server right after authorization.");
768
+ }
769
+ ctx.logger.info("Waiting for E10 authorization callback...");
770
+ return await new Promise((resolve, reject) => {
771
+ let settled = false;
772
+ let timer = null;
773
+ let pendingLoginResult = null;
774
+ let tlsCallbackDetected = false;
775
+ let exchanging = false;
776
+ let retriedPort = false;
777
+ const finish = (error, result) => {
778
+ if (settled) return;
779
+ settled = true;
780
+ if (timer) clearTimeout(timer);
781
+ closeHttpServer(server, () => {
782
+ if (error) reject(error);
783
+ else resolve(result);
784
+ });
785
+ };
786
+ const server = createServer(async (req, res) => {
787
+ const callbackUrl = new URL(req.url || "/", `http://127.0.0.1:${port}`);
788
+ if (callbackUrl.pathname === AGENT_RETURN_PATH) {
789
+ const requestToken = req.headers[AGENT_RETURN_TOKEN_HEADER];
790
+ if (req.method !== "POST" || !agentReturnTarget || !pendingLoginResult || requestToken !== agentReturnToken) {
791
+ res.writeHead(403, { "cache-control": "no-store", "content-type": "text/plain; charset=utf-8" });
792
+ res.end("Forbidden");
793
+ return;
794
+ }
795
+ const action = callbackUrl.searchParams.get("action");
796
+ if (action === "cancel") {
797
+ const result = pendingLoginResult;
798
+ res.writeHead(204, { "cache-control": "no-store" });
799
+ res.end();
800
+ finish(null, result);
801
+ return;
802
+ }
803
+ if (action !== "open") {
804
+ res.writeHead(400, { "cache-control": "no-store", "content-type": "text/plain; charset=utf-8" });
805
+ res.end("Invalid action");
806
+ return;
807
+ }
808
+ try {
809
+ await openUrlWithSystemHandler(agentReturnTarget.url);
810
+ const result = pendingLoginResult;
811
+ res.writeHead(200, { "cache-control": "no-store", "content-type": "application/json; charset=utf-8" });
812
+ res.end('{"ok":true}');
813
+ finish(null, result);
814
+ } catch (openError) {
815
+ ctx.logger.warn(
816
+ `Could not open ${agentReturnTarget.label} automatically (${describeOpenFailure(openError)}).`
817
+ );
818
+ res.writeHead(500, { "cache-control": "no-store", "content-type": "text/plain; charset=utf-8" });
819
+ res.end(`\u65E0\u6CD5\u6253\u5F00 ${agentReturnTarget.label}\uFF0C\u8BF7\u786E\u8BA4\u5E94\u7528\u5DF2\u5B89\u88C5\u3002`);
820
+ }
821
+ return;
822
+ }
823
+ if (callbackUrl.pathname !== "/callback") {
824
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
825
+ res.end("Not found");
826
+ return;
827
+ }
828
+ if (pendingLoginResult) {
829
+ res.writeHead(200, successHeaders);
830
+ res.end(renderE10LoginSuccessPage(pendingLoginResult.userId, agentReturnTarget, agentReturnToken));
831
+ return;
832
+ }
833
+ if (exchanging || settled) {
834
+ res.writeHead(409, { "cache-control": "no-store", "content-type": "text/plain; charset=utf-8" });
835
+ res.end("Authorization callback already received.");
836
+ return;
837
+ }
838
+ const error = callbackUrl.searchParams.get("error");
839
+ const code = callbackUrl.searchParams.get("code");
840
+ const redirectAgentType = explicitAgentType || callbackUrl.searchParams.get("agent_type") || callbackUrl.searchParams.get("agentType") || callbackUrl.searchParams.get("from") || agentType;
841
+ if (error) {
842
+ const message = callbackUrl.searchParams.get("error_description") || error;
843
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
844
+ res.end(`<h1>Authorization failed</h1><p>${esc(message)}</p>`);
845
+ finish(new CliError("OAuth authorization failed: " + message, 3 /* AuthError */));
846
+ return;
847
+ }
848
+ if (!code) {
849
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
850
+ res.end("<h1>Login failed</h1><p>Missing authorization code.</p>");
851
+ finish(new CliError("No authorization code received.", 3 /* AuthError */));
852
+ return;
853
+ }
854
+ if (tlsCallbackDetected && timer) {
855
+ clearTimeout(timer);
856
+ timer = null;
857
+ }
858
+ try {
859
+ exchanging = true;
860
+ const result = await oidcExchange(code, redirectUri, baseUrl, tenantKey, redirectAgentType, profileFromGlobal, hostKey);
861
+ pendingLoginResult = result;
862
+ res.writeHead(200, successHeaders);
863
+ res.end(renderE10LoginSuccessPage(result.userId, agentReturnTarget, agentReturnToken));
864
+ if (!agentReturnTarget) {
865
+ finish(null, result);
866
+ return;
867
+ }
868
+ if (timer) clearTimeout(timer);
869
+ timer = setTimeout(() => finish(null, result), AGENT_RETURN_TIMEOUT_MS);
870
+ } catch (exchangeError) {
871
+ const message = exchangeError instanceof Error ? exchangeError.message : String(exchangeError);
872
+ res.writeHead(500, { "content-type": "text/html; charset=utf-8" });
873
+ res.end(`<h1>Login failed</h1><p>${esc(message)}</p>`);
874
+ finish(exchangeError);
875
+ }
876
+ });
877
+ server.on("error", (error) => {
878
+ if (error.code === "EADDRINUSE" && !explicitPort && !retriedPort) {
879
+ retriedPort = true;
880
+ ctx.logger.warn(`Port ${port} is already in use. Using an available callback port.`);
881
+ server.listen(0, "127.0.0.1");
882
+ return;
883
+ }
884
+ const message = error.code === "EADDRINUSE" ? `Port ${port} is already in use. Retry with --port ${port + 1}.` : error.code === "EACCES" ? `Port ${port} is not accessible. Retry with another --port.` : error.message;
885
+ finish(new CliError(message, 2 /* UsageError */));
886
+ });
887
+ server.on("clientError", (error, socket) => {
888
+ if (isTlsClientHello(error)) {
889
+ if (!tlsCallbackDetected) {
890
+ tlsCallbackDetected = true;
891
+ ctx.logger.warn([
892
+ `OAuth callback protocol mismatch: the browser used HTTPS for 127.0.0.1:${port}, while the CLI listener is HTTP.`,
893
+ "\u5728 30 \u79D2\u5185\u628A\u6D4F\u89C8\u5668\u5F53\u524D\u5730\u5740\u5F00\u5934\u660E\u786E\u6539\u4E3A http://\uFF0C\u4FDD\u7559\u540E\u9762\u7684\u5B8C\u6574\u8DEF\u5F84\u548C\u53C2\u6570\uFF0C\u7136\u540E\u56DE\u8F66\u91CD\u8BD5\u3002",
894
+ "\u4E0D\u8981\u628A\u5730\u5740\u4E2D\u7684\u6388\u6743\u7801\u590D\u5236\u5230\u804A\u5929\u6216\u65E5\u5FD7\u3002"
895
+ ].join(" "));
896
+ if (timer) clearTimeout(timer);
897
+ timer = setTimeout(() => {
898
+ finish(createOAuthCallbackProtocolMismatchError(port));
899
+ }, OAUTH_CALLBACK_PROTOCOL_MISMATCH_GRACE_MS);
900
+ }
901
+ socket.destroy();
902
+ return;
903
+ }
904
+ socket.destroy();
905
+ });
906
+ server.once("listening", () => {
907
+ const address = server.address();
908
+ if (!address || typeof address === "string") {
909
+ finish(new CliError("Could not resolve local OAuth callback port.", 2 /* UsageError */));
910
+ return;
911
+ }
912
+ port = address.port;
913
+ redirectUri = `http://127.0.0.1:${port}/callback`;
914
+ const loginUrl = buildE10AuthorizeUrl(baseUrl, redirectUri, agentType);
915
+ ctx.logger.info("Open browser login: " + loginUrl);
916
+ ctx.logger.info("Local callback server: " + redirectUri);
917
+ openUrlInBrowser(loginUrl, ctx);
918
+ });
919
+ server.listen(port, "127.0.0.1");
920
+ timer = setTimeout(() => {
921
+ finish(new CliError("Login timed out after 5 minutes.", 3 /* AuthError */));
922
+ }, 3e5);
923
+ });
924
+ }
925
+ function sessionToCachedUser(session, profile) {
926
+ return {
927
+ employeeId: session.userId,
928
+ tenantKey: session.tenantKey,
929
+ tenantName: session.tenantName,
930
+ department: session.department,
931
+ subcompany: session.subcompany,
932
+ position: session.position,
933
+ version: session.version,
934
+ baseUrl: session.getBaseUrl(),
935
+ profile,
936
+ eteamsId: session.eteamsId,
937
+ agentType: session.agentType,
938
+ cookie: session.cookieHeader(),
939
+ userAgent: session.uaHeader()
940
+ };
941
+ }
942
+ function formatWhoami(title, data) {
943
+ return [
944
+ title,
945
+ "employeeId: " + (data.employeeId || ""),
946
+ "tenantKey: " + (data.tenantKey || ""),
947
+ "tenantName: " + (data.tenantName || ""),
948
+ "department: " + (data.department || ""),
949
+ "subcompany: " + (data.subcompany || ""),
950
+ "position: " + (data.position || ""),
951
+ "version: " + (data.version || ""),
952
+ "baseUrl: " + (data.baseUrl || ""),
953
+ "profile: " + (data.profile || ""),
954
+ "ETEAMSID: " + (data.eteamsId || ""),
955
+ "cookie: " + (data.cookie || ""),
956
+ "User-Agent: " + (data.userAgent || "")
957
+ ].join("\n");
958
+ }
959
+ function formatTlsPolicy(tls) {
960
+ return [
961
+ `mode=${tls.mode}`,
962
+ `applied=${tls.applied}`,
963
+ ...tls.caFiles.length ? [`caFiles=${tls.caFiles.join(",")}`] : [],
964
+ ...tls.notAppliedReason ? [`notAppliedReason=${tls.notAppliedReason}`] : [],
965
+ ...tls.insecureSource ? [`insecureSource=${tls.insecureSource}`] : [],
966
+ ...tls.error ? [`error=${tls.error}`] : []
967
+ ].join(" ");
968
+ }
969
+ function formatXiaoEAuthErrorLogEntry(entry) {
970
+ const lines = [
971
+ `[${entry.timestamp}] ${entry.source} id=${entry.id}`,
972
+ ...entry.profile ? [`profile: ${entry.profile}`] : [],
973
+ ...entry.baseUrl ? [`baseUrl: ${entry.baseUrl}`] : [],
974
+ ...entry.clientType ? [`clientType: ${entry.clientType}`] : [],
975
+ ...entry.tls ? [`tls: ${formatTlsPolicy(entry.tls)}`] : [],
976
+ ...entry.attemptedSteps.length ? [`attemptedSteps: ${entry.attemptedSteps.join(", ")}`] : [],
977
+ ...entry.lastError ? [`lastError: ${entry.lastError}`] : [],
978
+ ...entry.resultSessionExpired ? ["resultSessionExpired: true"] : [],
979
+ ...entry.error ? [`error: ${entry.error.type}/${entry.error.subtype}: ${entry.error.message}`] : []
980
+ ];
981
+ for (const failure of entry.failures || []) {
982
+ lines.push([
983
+ `failure: ${failure.stage}/${failure.kind}`,
984
+ failure.causeCode ? `causeCode=${failure.causeCode}` : "",
985
+ failure.httpStatus === void 0 ? "" : `httpStatus=${failure.httpStatus}`,
986
+ failure.message
987
+ ].filter(Boolean).join(" "));
988
+ if (failure.request) {
989
+ lines.push([
990
+ "request:",
991
+ `transport=${failure.request.transport}`,
992
+ `method=${failure.request.method}`,
993
+ `endpoint=${failure.request.endpoint}`,
994
+ failure.request.finalEndpoint ? `finalEndpoint=${failure.request.finalEndpoint}` : "",
995
+ `redirect=${failure.request.redirect}`,
996
+ `timeoutMs=${failure.request.timeoutMs}`,
997
+ `elapsedMs=${failure.request.elapsedMs}`,
998
+ failure.request.redirectCount ? `redirectCount=${failure.request.redirectCount}` : ""
999
+ ].filter(Boolean).join(" "));
1000
+ lines.push(`requestHeaders: ${JSON.stringify(failure.request.headers)}`);
1001
+ lines.push(`requestBody: ${JSON.stringify(failure.request.body)}`);
1002
+ lines.push(`requestParams: ${JSON.stringify({
1003
+ transport: failure.request.transport,
1004
+ url: failure.request.endpoint,
1005
+ ...failure.request.finalEndpoint ? { finalUrl: failure.request.finalEndpoint } : {},
1006
+ method: failure.request.method,
1007
+ headers: failure.request.headers,
1008
+ body: failure.request.body,
1009
+ bodyBytes: failure.request.bodyBytes,
1010
+ redirect: failure.request.redirect,
1011
+ timeoutMs: failure.request.timeoutMs,
1012
+ authorizationPresent: failure.request.authorizationPresent,
1013
+ authorizationLength: failure.request.authorizationLength,
1014
+ elapsedMs: failure.request.elapsedMs,
1015
+ ...failure.request.redirectCount ? { redirectCount: failure.request.redirectCount } : {}
1016
+ })}`);
1017
+ }
1018
+ }
1019
+ return lines.join("\n");
1020
+ }
1021
+ async function showXiaoEAuthErrorLogs(ctx, options) {
1022
+ const commandOpts = asOptions(options);
1023
+ let limit;
1024
+ try {
1025
+ limit = normalizeXiaoEAuthErrorLogLimit(commandOpts.limit);
1026
+ } catch (error) {
1027
+ throw new CliError(error instanceof Error ? error.message : String(error), 2 /* UsageError */);
1028
+ }
1029
+ const result = await readXiaoEAuthErrorLog(limit);
1030
+ const text = result.entries.length ? [
1031
+ `XiaoE auth error logs (${result.returned}/${result.total}, newest first)`,
1032
+ `logFile: ${result.path}`,
1033
+ ...result.expiredRemoved ? [`expiredRemoved: ${result.expiredRemoved}`] : [],
1034
+ ...result.invalidLines ? [`invalidLines: ${result.invalidLines}`] : [],
1035
+ "",
1036
+ result.entries.map(formatXiaoEAuthErrorLogEntry).join("\n\n")
1037
+ ].join("\n") : [
1038
+ "No XiaoE auth error logs.",
1039
+ `logFile: ${result.path}`,
1040
+ ...result.expiredRemoved ? [`expiredRemoved: ${result.expiredRemoved}`] : [],
1041
+ ...result.invalidLines ? [`invalidLines: ${result.invalidLines}`] : []
1042
+ ].join("\n");
1043
+ ctx.output.write(result, { text });
1044
+ }
1045
+ function registerXiaoEAuthLogCommands(auth, action) {
1046
+ const logs = auth.command("logs").description("View or clear persisted XiaoE authentication error logs").option("--limit <n>", "number of recent entries to show (1-500)", "50").action(action(showXiaoEAuthErrorLogs));
1047
+ logs.command("show").description("Show persisted XiaoE authentication error logs").option("--limit <n>", "number of recent entries to show (1-500)", "50").action(action(showXiaoEAuthErrorLogs));
1048
+ logs.command("path").description("Print the XiaoE authentication error log path").action(action((ctx) => {
1049
+ const path = getXiaoEAuthErrorLogPath();
1050
+ ctx.output.write({ path }, { text: path });
1051
+ }));
1052
+ logs.command("clear").description("Clear persisted XiaoE authentication error logs").action(action(async (ctx) => {
1053
+ const result = await clearXiaoEAuthErrorLog();
1054
+ const text = result.cleared ? `Cleared XiaoE auth error logs.
1055
+ logFile: ${result.path}` : `No XiaoE auth error logs to clear.
1056
+ logFile: ${result.path}`;
1057
+ ctx.output.write(result, { text });
1058
+ }));
1059
+ }
1060
+ function registerBrowserLoginCommand(auth, action, name, description, machine = false) {
1061
+ const command = auth.command(name).description(description).option("--base-url <url>", "E10 base URL (defaults to https://weapp.eteams.cn)").option("--tenant-key <key>", "Tenant key fallback after login").option("--port <n>", "Local OAuth callback port (default: 19800 with automatic fallback; 0 selects an available port)").option("--agent_type <value>", "Agent type sent to E10 authorize endpoint").option("--agent-type <value>", "Alias of --agent_type").option("--agent-return-url <url>", "Desktop application URL linked by the login success page");
1062
+ command.action(action(async (ctx, options) => {
1063
+ if (!machine) {
1064
+ const result = await runBrowserLogin(ctx, options);
1065
+ ctx.output.write(result, { text: formatLoginResult(result) });
1066
+ return;
1067
+ }
1068
+ ctx.logger.machineMode = true;
1069
+ try {
1070
+ const result = await runBrowserLogin(ctx, options, { machine: true });
1071
+ ctx.output.raw(JSON.stringify({
1072
+ status: "authorized",
1073
+ employeeId: result.userId || "",
1074
+ tenantKey: result.tenantKey || ""
1075
+ }));
1076
+ } catch (error) {
1077
+ ctx.output.raw(JSON.stringify({ status: "unauthorized" }));
1078
+ throw error;
1079
+ } finally {
1080
+ ctx.logger.machineMode = false;
1081
+ }
1082
+ }));
1083
+ }
1084
+ function registerXiaoELoginCommand(auth, action) {
1085
+ auth.command("xiaoe").description("Use XiaoE unified login without browser OAuth fallback").option("--base-url <url>", "E10 base URL (defaults to the host-provided domain)").option("--tenant-key <key>", "Tenant key fallback after login").option("--port <n>", "Deprecated compatibility option; ignored by XiaoE unified login", "19800").option("--agent_type <value>", "Deprecated compatibility option; ignored by XiaoE unified login").option("--agent-type <value>", "Alias of --agent_type").option("--agent-return-url <url>", "Deprecated compatibility option; ignored by XiaoE unified login").action(action(async (ctx, options) => {
1086
+ const result = await runXiaoELogin(ctx, options);
1087
+ ctx.output.write(result, { text: formatLoginResult(result) });
1088
+ }));
1089
+ }
1090
+ function registerE10AuthCommands(parent, action) {
1091
+ const auth = parent.command("auth").description("E10 auth and profile management");
1092
+ auth.command("root").description("Print the E10 auth root directory").action(action((ctx) => {
1093
+ const root = getE10AuthRoot();
1094
+ ctx.output.write({ root }, { text: root });
1095
+ }));
1096
+ auth.command("status").description("Show E10 login status").option("--no-check", "skip remote session validity check").action(action(async (ctx, options) => {
1097
+ const opts = ctx.getGlobalOptions();
1098
+ const commandOpts = asOptions(options);
1099
+ const authFile = findAuthFile(ctx.cwd, opts, ctx.env);
1100
+ const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1101
+ const profile2 = opts.profile || resolveActiveProfileForHost(ctx.env, opts);
1102
+ const agentHost = resolveSessionHostKey(ctx.env, opts);
1103
+ const state = await resolveAuthState(session, commandOpts.check !== false);
1104
+ const status = session ? {
1105
+ status: state.authorized ? "authorized" : "unauthorized",
1106
+ // 名字必须配得上语义:`loggedIn` 只表示"登录有效",不表示"有会话文件"。
1107
+ loggedIn: state.authorized,
1108
+ hasSessionFile: true,
1109
+ expired: state.expired,
1110
+ reachable: state.reachable,
1111
+ userId: session.userId,
1112
+ tenantKey: session.tenantKey,
1113
+ tenantName: session.tenantName,
1114
+ department: session.department,
1115
+ subcompany: session.subcompany,
1116
+ position: session.position,
1117
+ version: session.version,
1118
+ agentType: session.agentType,
1119
+ baseUrl: session.getBaseUrl(),
1120
+ passportUrl: session.getPassportUrl(),
1121
+ profile: profile2,
1122
+ agentHost,
1123
+ authFile,
1124
+ hasEteamsId: Boolean(session.eteamsId),
1125
+ ...session.loginSource ? { loginSource: session.loginSource } : {},
1126
+ ...session.credentialSourceStep ? { credentialSourceStep: session.credentialSourceStep } : {},
1127
+ ...session.credentialSourceType ? { credentialSourceType: session.credentialSourceType } : {},
1128
+ ...session.credentialSourceLabel ? { credentialSourceLabel: session.credentialSourceLabel } : {},
1129
+ ...session.expiryTimes ? { expiryTimes: session.expiryTimes } : {}
1130
+ } : {
1131
+ status: "unauthorized",
1132
+ loggedIn: false,
1133
+ hasSessionFile: false,
1134
+ expired: false,
1135
+ profile: profile2,
1136
+ agentHost,
1137
+ authFile
1138
+ };
1139
+ ctx.output.write(status, { text: formatAuthStatus(status) });
1140
+ }));
1141
+ auth.command("show").description('Platform contract: print login status as {"status":"authorized"|"unauthorized"}').option("--status", "print only the strict JSON status object").option("--no-check", "skip remote session validity check").action(action(async (ctx, options) => {
1142
+ const opts = ctx.getGlobalOptions();
1143
+ const commandOpts = asOptions(options);
1144
+ const authFile = findAuthFile(ctx.cwd, opts, ctx.env);
1145
+ const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1146
+ const profile2 = opts.profile || resolveActiveProfileForHost(ctx.env, opts);
1147
+ const state = await resolveAuthState(session, commandOpts.check !== false);
1148
+ if (commandOpts.status === true) {
1149
+ ctx.output.raw(JSON.stringify({ status: state.authorized ? "authorized" : "unauthorized" }));
1150
+ return;
1151
+ }
1152
+ ctx.output.write({
1153
+ status: state.authorized ? "authorized" : "unauthorized",
1154
+ loggedIn: state.authorized,
1155
+ hasSessionFile: state.hasSessionFile,
1156
+ expired: state.expired,
1157
+ reachable: state.reachable,
1158
+ profile: profile2,
1159
+ baseUrl: session ? session.getBaseUrl() : ""
1160
+ }, { json: true });
1161
+ }));
1162
+ auth.command("set").description("Save E10 auth from an ETEAMSID cookie").requiredOption("--eteamsid <id>", "ETEAMSID cookie value").option("--base-url <url>", "E10 base URL (defaults to https://weapp.eteams.cn)").option("--passport-url <url>", "E10 passport URL; defaults to base URL").option("--tenant-key <key>", "Tenant key fallback").option("--agent_type <value>", "Agent type used in cookie and User-Agent").option("--agent-type <value>", "Alias of --agent_type").action(action(async (ctx, options) => {
1163
+ const globalOptions = ctx.getGlobalOptions();
1164
+ const commandOpts = asOptions(options);
1165
+ const profileFromGlobal = globalOptions.profile;
1166
+ const target = resolveLoginTarget({
1167
+ env: ctx.env,
1168
+ explicitProfile: profileFromGlobal,
1169
+ explicitAgentType: optionString(commandOpts, "agentType", "agent_type")
1170
+ });
1171
+ const cfg = target.cfg;
1172
+ const baseUrl = normalizeUrl(
1173
+ optionString(commandOpts, "baseUrl") || globalOptions.baseUrl || cfg.baseUrl || resolveDefaultE10BaseUrl(ctx.env)
1174
+ );
1175
+ const passportUrl = normalizeUrl(optionString(commandOpts, "passportUrl") || globalOptions.passportUrl || cfg.passportUrl || baseUrl);
1176
+ const tenantKeyFallback = optionString(commandOpts, "tenantKey");
1177
+ const agentType = resolveAgentType(commandOpts, ctx.env);
1178
+ const eteamsId = optionString(commandOpts, "eteamsid");
1179
+ if (!eteamsId) throw new CliError("Missing --eteamsid", 2 /* UsageError */);
1180
+ ctx.logger.info("Resolving E10 user information...");
1181
+ const result = await saveEteamsIdLogin({
1182
+ baseUrl,
1183
+ passportUrl,
1184
+ eteamsId,
1185
+ tenantKeyFallback,
1186
+ agentType,
1187
+ profileHint: profileFromGlobal,
1188
+ hostKey: target.hostKey
1189
+ });
1190
+ ctx.output.write(result, { text: formatLoginResult(result) });
1191
+ }));
1192
+ registerBrowserLoginCommand(auth, action, "login", "Open browser OAuth2.0 login and save E10 auth");
1193
+ registerBrowserLoginCommand(auth, action, "oidc", "Alias of auth login for OAuth2.0 browser login");
1194
+ registerBrowserLoginCommand(
1195
+ auth,
1196
+ action,
1197
+ "init",
1198
+ 'Platform contract alias of auth login: stdout is strict JSON {"status":"authorized"}',
1199
+ true
1200
+ );
1201
+ registerXiaoELoginCommand(auth, action);
1202
+ registerXiaoEAuthLogCommands(auth, action);
1203
+ auth.command("logout").alias("clear").description("Clear saved E10 auth for the current or selected profile").action(action(async (ctx) => {
1204
+ const opts = ctx.getGlobalOptions();
1205
+ const profile2 = opts.profile || resolveActiveProfileForHost(ctx.env, opts);
1206
+ const authFile = findAuthFile(ctx.cwd, { ...opts, auth: void 0, profile: profile2 }, ctx.env);
1207
+ if (!authFile) {
1208
+ ctx.output.write({ profile: profile2, cleared: false }, { text: "No E10 auth to clear." });
1209
+ return;
1210
+ }
1211
+ const session = E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl);
1212
+ if (session) {
1213
+ await clearInvoiceTokenCache(profile2, {
1214
+ baseUrl: session.getBaseUrl(),
1215
+ userId: session.userId
1216
+ });
1217
+ }
1218
+ const result = clearProfileAuthFile(profile2);
1219
+ const text = result.cleared ? "Cleared E10 auth.\nprofile: " + result.profile + "\nauthFile: " + result.authFile : "No E10 auth to clear.\nprofile: " + result.profile + "\nauthFile: " + result.authFile;
1220
+ ctx.output.write(result, { text });
1221
+ }));
1222
+ auth.command("whoami").description("Show cached or live E10 user information").option("--json", "print output as JSON").option("--live", "call teamsCheck for live user information").action(action(async (ctx, options) => {
1223
+ const opts = ctx.getGlobalOptions();
1224
+ const commandOpts = asOptions(options);
1225
+ const json = commandOpts.json === true;
1226
+ const live = commandOpts.live === true;
1227
+ const authFile = findAuthFile(ctx.cwd, opts, ctx.env);
1228
+ const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1229
+ if (!session || !session.eteamsId) throw new CliError("E10 auth not found.", 3 /* AuthError */);
1230
+ const profile2 = opts.profile || resolveActiveProfileForHost(ctx.env, opts);
1231
+ const cached = sessionToCachedUser(session, profile2);
1232
+ if (!live) {
1233
+ ctx.output.write(cached, {
1234
+ json,
1235
+ text: formatWhoami("Current E10 user (cached)", cached)
1236
+ });
1237
+ return;
1238
+ }
1239
+ const base = session.getBaseUrl();
1240
+ const resp = await fetch(`${base}/api/baseserver/layout/teamsCheck?clientType=not_xinchuang&client=WEB&domainName=${encodeURIComponent(base)}`, {
1241
+ method: "POST",
1242
+ headers: {
1243
+ accept: "application/json",
1244
+ "content-type": "application/json",
1245
+ eteamsid: session.eteamsId,
1246
+ cookie: session.cookieHeader(),
1247
+ "user-agent": session.uaHeader(),
1248
+ origin: base
1249
+ },
1250
+ redirect: "manual"
1251
+ });
1252
+ const raw = await resp.json().catch(() => ({}));
1253
+ if (json || ctx.getGlobalOptions().json) {
1254
+ ctx.output.write(raw, { json: true });
1255
+ return;
1256
+ }
1257
+ const userInfo = readTeamsCheckUserInfo(resp, raw);
1258
+ const liveData = {
1259
+ ...cached,
1260
+ employeeId: userInfo.userId || cached.employeeId,
1261
+ tenantKey: userInfo.tenantKey || cached.tenantKey,
1262
+ tenantName: userInfo.tenantName || cached.tenantName,
1263
+ department: userInfo.department || cached.department,
1264
+ subcompany: userInfo.subcompany || cached.subcompany,
1265
+ position: userInfo.position || cached.position
1266
+ };
1267
+ ctx.output.write(liveData, { text: formatWhoami("Current E10 user (live)", liveData) });
1268
+ }));
1269
+ auth.command("export-weaver-env").description("Print WEAVER_* shell exports for the active E10 auth").option("--shell <shell>", "Shell syntax: auto, posix, or powershell", "auto").action(action(async (ctx, options) => {
1270
+ const commandOpts = asOptions(options);
1271
+ const session = await E10AuthSession.fromOptions(ctx.getGlobalOptions(), ctx.cwd, {}, ctx.env);
1272
+ if (!session) throw new CliError("E10 auth not found.", 3 /* AuthError */);
1273
+ const value = {
1274
+ WEAVER_BASE_URL: session.getBaseUrl(),
1275
+ WEAVER_ETEAMSID: session.eteamsId,
1276
+ WEAVER_COOKIE: session.cookieHeader(),
1277
+ WEAVER_USER_AGENT: session.uaHeader(),
1278
+ WEAVER_AGENT_TYPE: session.agentType
1279
+ };
1280
+ if (ctx.getGlobalOptions().json) {
1281
+ ctx.output.write(value);
1282
+ return;
1283
+ }
1284
+ const shell = optionString(commandOpts, "shell") || "auto";
1285
+ ctx.output.raw(formatWeaverEnvExports(value, shell));
1286
+ }));
1287
+ const profile = auth.command("profile").description("Manage E10 profiles");
1288
+ profile.command("list").description("List E10 profiles").action(action((ctx) => {
1289
+ const active = getActiveProfile();
1290
+ const profiles = listProfiles().map((name) => ({
1291
+ name,
1292
+ active: name === active,
1293
+ dir: getProfileDir(name)
1294
+ }));
1295
+ ctx.output.write({ active, profiles });
1296
+ }));
1297
+ profile.command("use").description("Switch active E10 profile; creates it if missing").argument("<name>", "profile name").action(action((ctx, name) => {
1298
+ if (typeof name !== "string") throw new CliError("profile name must be a string", 2 /* UsageError */);
1299
+ resolveLoginProfileName({
1300
+ derivedName: name,
1301
+ profileHint: name,
1302
+ baseUrl: "",
1303
+ hostKey: resolveSessionHostKey(ctx.env, ctx.getGlobalOptions())
1304
+ });
1305
+ switchActiveProfile(name);
1306
+ const cfg = readProfileConfig(name);
1307
+ const hostRecord = upsertAgentHost({
1308
+ profile: name,
1309
+ hostKey: resolveSessionHostKey(ctx.env, ctx.getGlobalOptions()),
1310
+ ...cfg.baseUrl ? { baseUrl: cfg.baseUrl } : {},
1311
+ ...cfg.tenantKey ? { tenantKey: cfg.tenantKey } : {},
1312
+ env: ctx.env
1313
+ });
1314
+ const result = {
1315
+ active: name,
1316
+ dir: getProfileDir(name),
1317
+ authFile: getProfileAuthPath(name),
1318
+ agentHost: resolveSessionHostKey(ctx.env, ctx.getGlobalOptions()),
1319
+ ...hostRecord ? { agentHostProfile: hostRecord.profile } : {}
1320
+ };
1321
+ ctx.output.write(result, { text: "Active E10 profile: " + name + "\ndir: " + result.dir });
1322
+ }));
1323
+ profile.command("current").description("Print active E10 profile").action(action((ctx) => {
1324
+ const active = resolveActiveProfileForHost(ctx.env, ctx.getGlobalOptions());
1325
+ ctx.output.write({ active, dir: getProfileDir(active) }, { text: active });
1326
+ }));
1327
+ return auth;
1328
+ }
1329
+
1330
+ export {
1331
+ resolveAgentType,
1332
+ isMachineAuthMode,
1333
+ resolveAgentReturnTarget,
1334
+ formatWeaverEnvExports,
1335
+ renderE10LoginSuccessPage,
1336
+ resolveWindowsRundll32Path,
1337
+ closeHttpServer,
1338
+ resolveBrowserOpenCommand,
1339
+ resolvePromotionKeyword,
1340
+ resolvePromotionSource,
1341
+ buildE10AuthorizeUrl,
1342
+ isTlsClientHello,
1343
+ createOAuthCallbackProtocolMismatchError,
1344
+ runBrowserLogin,
1345
+ registerE10AuthCommands
1346
+ };