weaver-work-cli 0.1.54 → 0.1.56

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 (183) hide show
  1. package/dist/chunks/{archive-ZQ4A4TV6.js → archive-4SQAVTIB.js} +3 -2
  2. package/dist/chunks/{archive-oa-57R2FYHV.js → archive-oa-W2UEJ67L.js} +137 -8
  3. package/dist/chunks/{asset-ZOJVBWZH.js → asset-EGZEABBI.js} +3 -2
  4. package/dist/chunks/{asset-idle-XGB5IPGT.js → asset-idle-EBUZBB6M.js} +3 -2
  5. package/dist/chunks/{attachment-content-2EPEI4HV.js → attachment-content-QGM5MLQE.js} +4 -3
  6. package/dist/chunks/{blog-QSHLZSFW.js → blog-2YKMWOWI.js} +3 -2
  7. package/dist/chunks/{caizhilian-KCQYFH72.js → caizhilian-QJ4FLSQJ.js} +5 -4
  8. package/dist/chunks/{calendar-DLGMRJQA.js → calendar-H4QTJCUY.js} +3 -2
  9. package/dist/chunks/{chunk-XPQN4E5O.js → chunk-44KJ7WFA.js} +300 -55
  10. package/dist/chunks/{chunk-CZNZKOHR.js → chunk-4GG72JAT.js} +2 -2
  11. package/dist/chunks/{chunk-YIKSL36S.js → chunk-5N222HK6.js} +2 -2
  12. package/dist/chunks/{chunk-XHMJBRLZ.js → chunk-6DVL5IN5.js} +4 -1
  13. package/dist/chunks/{chunk-JJRIT2ZN.js → chunk-6MS3RLPO.js} +5 -334
  14. package/dist/chunks/{chunk-QUDHSMG3.js → chunk-7EBV7Q3R.js} +112 -27
  15. package/dist/chunks/{chunk-CNVZETM5.js → chunk-AHJZIMCX.js} +1 -1
  16. package/dist/chunks/{chunk-TGAGQV4I.js → chunk-CQ4OVCKG.js} +2 -2
  17. package/dist/chunks/{chunk-2BQESR2U.js → chunk-DVR2EDUU.js} +99 -34
  18. package/dist/chunks/{chunk-7KKI5KDY.js → chunk-FDAJC7R4.js} +4 -4
  19. package/dist/chunks/{chunk-GR76ZDDX.js → chunk-FMNCSYIG.js} +2 -2
  20. package/dist/chunks/{chunk-6LGLI46Q.js → chunk-L2LMBFG5.js} +1 -1
  21. package/dist/chunks/{chunk-DLY5GUXX.js → chunk-PH7N4UFT.js} +1 -1
  22. package/dist/chunks/{chunk-U6R6FZHD.js → chunk-SFM3M2L3.js} +286 -93
  23. package/dist/chunks/chunk-SHYQUBY3.js +48 -0
  24. package/dist/chunks/{chunk-HFXK54M4.js → chunk-TGM7BWEH.js} +2 -2
  25. package/dist/chunks/{chunk-Z7B7QSR2.js → chunk-TJUAGZU7.js} +11 -11
  26. package/dist/chunks/{chunk-LYOFRYC4.js → chunk-UI66EMOR.js} +4 -4
  27. package/dist/chunks/{chunk-762M5XJS.js → chunk-VMCCRWFO.js} +2 -2
  28. package/dist/chunks/{chunk-FE3CQAAM.js → chunk-WHJIUKJW.js} +681 -48
  29. package/dist/chunks/{chunk-PGO4ILMQ.js → chunk-WMB3SMXI.js} +1 -1
  30. package/dist/chunks/chunk-WMRNO6IU.js +337 -0
  31. package/dist/chunks/{chunk-6NXT4ICB.js → chunk-WVH5ESDA.js} +1 -1
  32. package/dist/chunks/{chunk-O6RIBG5E.js → chunk-XU3FL3AW.js} +4 -4
  33. package/dist/chunks/{chunk-Z6UUBY37.js → chunk-Z4IPY5GV.js} +2 -2
  34. package/dist/chunks/{conflict-K2IAKKFR.js → conflict-VAFFPUY3.js} +2 -2
  35. package/dist/chunks/{contract-LJRAXVZU.js → contract-LLRKMLQQ.js} +2655 -1319
  36. package/dist/chunks/{cowork-3ACICHDQ.js → cowork-2RDFBZWB.js} +3 -2
  37. package/dist/chunks/{create-flow-UL37MZGP.js → create-flow-TVYE3IOH.js} +6 -6
  38. package/dist/chunks/{data-WK5CQXNF.js → data-WVICO3DT.js} +57 -11
  39. package/dist/chunks/{ebuilder-form-CBYI6CQ6.js → ebuilder-form-TWSXS5NA.js} +7 -6
  40. package/dist/chunks/{ehr-XI4BIVR2.js → ehr-52GBKNJR.js} +3 -2
  41. package/dist/chunks/{env-BZDB5OVZ.js → env-BVVFIN4P.js} +2 -2
  42. package/dist/chunks/{esb-4BQHNP5C.js → esb-HJSXCEOM.js} +5 -4
  43. package/dist/chunks/{factory-VD3YI6N7.js → factory-RCQ36LLE.js} +1 -1
  44. package/dist/chunks/{fna-ECOYBQYL.js → fna-OBACRT3J.js} +72 -3
  45. package/dist/chunks/{group-chat-DHNVO76L.js → group-chat-YFZDUUY3.js} +3 -3
  46. package/dist/chunks/{host-TUOIOEMC.js → host-2BKMPWDH.js} +4 -3
  47. package/dist/chunks/{host-3TNBMDTR.js → host-KJT3G5D2.js} +4 -3
  48. package/dist/chunks/{host-7OWWPLM4.js → host-KOWUMNAY.js} +4 -3
  49. package/dist/chunks/{host-M4XP5URR.js → host-MFXRA2MY.js} +4 -3
  50. package/dist/chunks/{host-7NTIBSPK.js → host-TTSGY5NZ.js} +4 -3
  51. package/dist/chunks/{host-G3VU7SDW.js → host-W4JCNRFS.js} +4 -3
  52. package/dist/chunks/{hrm-YGIR3HGF.js → hrm-AK3WGBMN.js} +4 -3
  53. package/dist/chunks/{im-TN2JYVGJ.js → im-JZSBPO4Z.js} +4 -3
  54. package/dist/chunks/{invoice-V7ZTITUO.js → invoice-V6KD4TZE.js} +4 -3
  55. package/dist/chunks/{jiuchuanhui-ASFZBMPU.js → jiuchuanhui-K4EQU6GK.js} +3 -2
  56. package/dist/chunks/{lazy-dispatch-XSAHDK6Z.js → lazy-dispatch-JHGFCKJN.js} +5 -4
  57. package/dist/chunks/{mail-M3HJF5ER.js → mail-IKVCQCVZ.js} +3 -2
  58. package/dist/chunks/{meeting-OWG4O2XH.js → meeting-JOHV4RH3.js} +14 -12
  59. package/dist/chunks/minute-doc-JLS4KMFZ.js +156 -0
  60. package/dist/chunks/{okr-EVX7FB5G.js → okr-KV43FPPX.js} +3 -2
  61. package/dist/chunks/{operations-J7PUIVWZ.js → operations-ZPWBMYKE.js} +5 -4
  62. package/dist/chunks/{plan-2QJQEPBO.js → plan-WOYR4WEG.js} +3 -2
  63. package/dist/chunks/{project-XELELW2T.js → project-CQJKBUIL.js} +3 -2
  64. package/dist/chunks/{reception-QGPNTGHG.js → reception-MPBU3JXC.js} +3 -2
  65. package/dist/chunks/{recruit-stage-XCMVEQA2.js → recruit-stage-USTTRHOX.js} +3 -2
  66. package/dist/chunks/{registry-CJOVECZD.js → registry-GURQG4ZV.js} +3 -2
  67. package/dist/chunks/{registry-ASYCWF2U.js → registry-LITYOH2W.js} +12 -10
  68. package/dist/chunks/{registry-QJCZ2GVG.js → registry-SS5J2FZQ.js} +5 -4
  69. package/dist/chunks/{room-recommend-LSVAMGKV.js → room-recommend-62MECG4J.js} +4 -4
  70. package/dist/chunks/{schedule-7QOPRUU4.js → schedule-6QRXIBGU.js} +4 -4
  71. package/dist/chunks/{smart-extract-FOUYNIG3.js → smart-extract-APX2PNIN.js} +3 -2
  72. package/dist/chunks/{workflow-YHXFIU63.js → workflow-WMPW3WSB.js} +5 -4
  73. package/dist/index.js +33 -32
  74. package/dist/internal/e10/auth/agent-host-key.js +68 -0
  75. package/dist/internal/e10/auth/agent-hosts.js +250 -0
  76. package/dist/internal/e10/auth/commands.js +99 -30
  77. package/dist/internal/e10/auth/paths.js +9 -0
  78. package/dist/internal/e10/auth/session.js +17 -0
  79. package/dist/internal/e10/auth/xiaoe.js +37 -3
  80. package/dist/shortcuts/archive-oa/operations/contract-modules.js +106 -0
  81. package/dist/shortcuts/archive-oa/operations/contract.js +38 -4
  82. package/dist/shortcuts/archive-oa/operations/registry.js +2 -1
  83. package/dist/shortcuts/contract/index.js +6 -7
  84. package/dist/shortcuts/contract/manifest.js +101 -24
  85. package/dist/shortcuts/contract/ooxml/docx-table.js +75 -3
  86. package/dist/shortcuts/contract/ooxml/xlsx.js +49 -13
  87. package/dist/shortcuts/contract/operations/card-action.js +113 -12
  88. package/dist/shortcuts/contract/operations/card-ebdf-list.js +29 -7
  89. package/dist/shortcuts/contract/operations/card-plan.js +75 -9
  90. package/dist/shortcuts/contract/operations/card-risk-report.js +2 -2
  91. package/dist/shortcuts/contract/operations/card.js +1 -1
  92. package/dist/shortcuts/contract/operations/clause-library.js +88 -16
  93. package/dist/shortcuts/contract/operations/compare-screen.js +378 -0
  94. package/dist/shortcuts/contract/operations/compare.js +1 -1
  95. package/dist/shortcuts/contract/operations/credit-page.js +1 -1
  96. package/dist/shortcuts/contract/operations/docx-slots.js +1000 -0
  97. package/dist/shortcuts/contract/operations/flow.js +2 -2
  98. package/dist/shortcuts/contract/operations/quote-to-contract.js +495 -0
  99. package/dist/shortcuts/contract/operations/quote.js +2 -229
  100. package/dist/shortcuts/contract/operations/recommend.js +1 -1
  101. package/dist/shortcuts/contract/operations/registry.js +6 -2
  102. package/dist/shortcuts/contract/operations/review.js +230 -4
  103. package/dist/shortcuts/contract/operations/save-recognize.js +122 -3
  104. package/dist/shortcuts/contract/operations/template.js +11 -10
  105. package/dist/shortcuts/data/operations/ds.js +5 -5
  106. package/dist/shortcuts/data/operations/shared.js +76 -4
  107. package/dist/shortcuts/fna/manifest.js +7 -2
  108. package/dist/shortcuts/fna/operations/budget.js +68 -0
  109. package/dist/shortcuts/meeting/minute-doc.js +153 -0
  110. package/dist/shortcuts/meeting/operations/compose-outcome.js +176 -0
  111. package/dist/shortcuts/meeting/operations/eb/catalog.js +1 -1
  112. package/dist/shortcuts/meeting/operations/eb/create-flow.js +26 -0
  113. package/dist/shortcuts/meeting/operations/eb/decision-task-batch.js +144 -0
  114. package/dist/shortcuts/meeting/operations/eb/decision.js +92 -4
  115. package/dist/shortcuts/meeting/operations/eb/index.js +133 -4
  116. package/dist/shortcuts/meeting/operations/eb/meeting-link.js +90 -0
  117. package/dist/shortcuts/meeting/operations/from-group-chat.js +46 -0
  118. package/dist/shortcuts/meeting/operations/minute-content.js +61 -0
  119. package/dist/shortcuts/meeting/operations/registry.js +14 -1
  120. package/dist/shortcuts/meeting/operations/self-check.js +49 -0
  121. package/dist/shortcuts/workflow/endpoints.js +2 -0
  122. package/dist/shortcuts/workflow/operations/read.js +114 -8
  123. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +72 -46
  124. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +41 -0
  125. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +46 -11
  126. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.smartGroup.js +18 -1
  127. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.smartGroupAdd.js +51 -0
  128. package/docs/e10-auth.md +78 -0
  129. package/docs/fna.md +8 -3
  130. package/package.json +4 -2
  131. package/scripts/pack-offline.mjs +228 -0
  132. package/scripts/package-skill.mjs +14 -5
  133. package/skill-template/business-info.json +3 -0
  134. package/skill-template/domains/qiyecheng.md +4 -3
  135. package/skills/weaver-e10-archive-oa/SKILL.md +6 -1
  136. package/skills/weaver-e10-archive-oa/references/contract-search.md +91 -4
  137. package/skills/weaver-e10-jinchengda/SKILL.md +100 -81
  138. package/skills/weaver-e10-jinchengda/references/contract-action-card-template.html +11 -6
  139. package/skills/weaver-e10-jinchengda/references/contract-action-card.md +5 -4
  140. package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +38 -12
  141. package/skills/weaver-e10-jinchengda/references/contract-agent-entry.md +1 -1
  142. package/skills/weaver-e10-jinchengda/references/contract-ai-assistant.md +1 -1
  143. package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +20 -6
  144. package/skills/weaver-e10-jinchengda/references/contract-card-render-internals.md +8 -3
  145. package/skills/weaver-e10-jinchengda/references/contract-clause-library-crud.md +56 -13
  146. package/skills/weaver-e10-jinchengda/references/contract-clause-recommender.md +7 -0
  147. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +4 -4
  148. package/skills/weaver-e10-jinchengda/references/contract-compare-report.md +11 -5
  149. package/skills/weaver-e10-jinchengda/references/contract-credit-page.md +1 -1
  150. package/skills/weaver-e10-jinchengda/references/contract-disabled-capabilities.md +1 -1
  151. package/skills/weaver-e10-jinchengda/references/contract-doc-compare.md +38 -7
  152. package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +13 -25
  153. package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +9 -8
  154. package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +8 -6
  155. package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +10 -7
  156. package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +2 -2
  157. package/skills/weaver-e10-jinchengda/references/contract-ledger-catalog.md +3 -1
  158. package/skills/weaver-e10-jinchengda/references/contract-ledger-query-playbook.md +26 -18
  159. package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +4 -4
  160. package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +18 -13
  161. package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +5 -3
  162. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +105 -49
  163. package/skills/weaver-e10-jinchengda/references/contract-template-recommend.md +1 -1
  164. package/skills/weaver-e10-jinchengda/references/contract-template-selector.md +3 -6
  165. package/skills/weaver-e10-meeting/SKILL.md +47 -9
  166. package/skills/weaver-e10-qiyecheng/SKILL.md +16 -7
  167. package/skills/weaver-e10-qiyecheng/references/budget.md +77 -3
  168. package/skills/weaver-e10-qiyecheng/references/catalog.md +6 -4
  169. package/skills/weaver-e10-qiyecheng/references/getEnabledTemplate-api.md +255 -0
  170. package/skills/weaver-e10-qiyecheng/references/source-manifest.json +70 -25
  171. package/skills/weaver-e10-workflow/SKILL.md +54 -40
  172. package/skills/weaver-e10-workflow/references/todo-dialogue.md +134 -0
  173. package/skills/weaver-e10-workflow/references/todo-smart-convert.md +102 -80
  174. package/skills/weaver-e10-workflow/references/workflow-agent-entry.md +23 -13
  175. package/skills/weaver-e10-workflow/references/workflow-query.md +68 -46
  176. package/skills/weaver-e10-workflow/references/workflow-view.md +21 -13
  177. package/skills/weaver-e10-workflow/tools/todo-summary.cjs +317 -332
  178. package/dist/shortcuts/contract/ooxml/docx.js +0 -295
  179. package/dist/shortcuts/contract/operations/docx-fillfromquote.js +0 -532
  180. package/skills/weaver-e10-jinchengda/references/contract-risk-report-template.html +0 -178
  181. package/skills/weaver-e10-jinchengda/references/source-manifest.json +0 -1270
  182. package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +0 -998
  183. package/skills/weaver-e10-workflow/tools/todo-serve.cjs +0 -327
@@ -0,0 +1,250 @@
1
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { isConnectorMode } from '../../../core/connector.js';
4
+ import { resolveAgentHostKey } from './agent-host-key.js';
5
+ import { getE10AgentsPath, getE10ProfilesRoot } from './paths.js';
6
+ const AGENTS_FILE_VERSION = 1;
7
+ /** 拿锁的最长等待,超时后退化为无锁写:宁可偶尔丢记录,也不能让登录卡死。 */
8
+ const AGENTS_LOCK_TIMEOUT_MS = 600;
9
+ const AGENTS_LOCK_RETRY_MS = 15;
10
+ function asRecord(value) {
11
+ return value && typeof value === 'object' && !Array.isArray(value)
12
+ ? value
13
+ : {};
14
+ }
15
+ function readText(value) {
16
+ return typeof value === 'string' ? value.trim() : '';
17
+ }
18
+ function normalizeOrigin(value) {
19
+ const trimmed = value.trim();
20
+ if (!trimmed)
21
+ return '';
22
+ try {
23
+ const url = new URL(trimmed);
24
+ return `${url.protocol}//${url.host}`.toLowerCase();
25
+ }
26
+ catch {
27
+ return trimmed.toLowerCase().replace(/\/+$/u, '');
28
+ }
29
+ }
30
+ /**
31
+ * 读取宿主记录文件。
32
+ *
33
+ * 损坏、非法 JSON 或 `version` 不认识时整体返回 `null`(按「没有记录」处理),
34
+ * 不抛错也不删除文件:登录状态解析不允许被一个坏文件卡死。
35
+ */
36
+ export function readAgentHosts() {
37
+ const filePath = getE10AgentsPath();
38
+ if (!existsSync(filePath))
39
+ return null;
40
+ try {
41
+ const parsed = asRecord(JSON.parse(readFileSync(filePath, 'utf-8')));
42
+ const version = typeof parsed.version === 'number' ? parsed.version : AGENTS_FILE_VERSION;
43
+ if (!Number.isInteger(version) || version > AGENTS_FILE_VERSION)
44
+ return null;
45
+ const hosts = {};
46
+ for (const [key, raw] of Object.entries(asRecord(parsed.hosts))) {
47
+ const entry = asRecord(raw);
48
+ const profile = readText(entry.profile);
49
+ if (!profile)
50
+ continue;
51
+ hosts[key] = {
52
+ profile,
53
+ ...(readText(entry.baseUrl) ? { baseUrl: readText(entry.baseUrl) } : {}),
54
+ ...(readText(entry.tenantKey) ? { tenantKey: readText(entry.tenantKey) } : {}),
55
+ ...(readText(entry.agentType) ? { agentType: readText(entry.agentType) } : {}),
56
+ updatedAt: readText(entry.updatedAt),
57
+ };
58
+ }
59
+ return { version, hosts };
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ export function readAgentHost(hostKey) {
66
+ if (!hostKey)
67
+ return null;
68
+ const file = readAgentHosts();
69
+ if (!file)
70
+ return null;
71
+ return file.hosts[hostKey] || null;
72
+ }
73
+ function readProfileConfigAt(profile) {
74
+ const configPath = resolve(getE10ProfilesRoot(), profile, 'config.json');
75
+ if (!existsSync(configPath))
76
+ return {};
77
+ try {
78
+ return JSON.parse(readFileSync(configPath, 'utf-8'));
79
+ }
80
+ catch {
81
+ return {};
82
+ }
83
+ }
84
+ /**
85
+ * 查找当前宿主记住的 profile,并给出可用性判定。
86
+ *
87
+ * 返回 `null` 表示**没有该宿主的记录**,调用方应回落到全局 `profile` 指针(旧行为)。
88
+ * 返回非 `ok` 的记录表示「该宿主曾经登录过,但现在不能直接用」:此时调用方必须
89
+ * 视为未登录,**不能**借用其他宿主的 profile,否则就是跨租户串用凭据。
90
+ */
91
+ export function lookupAgentHost(env = process.env, explicitAgentType = '') {
92
+ const hostKey = resolveAgentHostKey(env, explicitAgentType);
93
+ const file = readAgentHosts();
94
+ const record = file?.hosts[hostKey];
95
+ if (!record)
96
+ return null;
97
+ const profileDir = resolve(getE10ProfilesRoot(), record.profile);
98
+ const authFile = resolve(profileDir, 'auth');
99
+ const base = { hostKey, record, profile: record.profile, authFile };
100
+ if (!existsSync(profileDir))
101
+ return { ...base, status: 'profile-missing' };
102
+ if (!existsSync(authFile))
103
+ return { ...base, status: 'auth-missing' };
104
+ // 记录里的域名只是写入时的快照。若 profile 后来被别的宿主重新登录到了另一个
105
+ // 域名,就说明这条记录已经过期,继续用它等于带着 A 租户的票访问 B 租户。
106
+ const recordBaseUrl = normalizeOrigin(record.baseUrl || '');
107
+ const configBaseUrl = normalizeOrigin(readProfileConfigAt(record.profile).baseUrl || '');
108
+ if (recordBaseUrl && configBaseUrl && recordBaseUrl !== configBaseUrl) {
109
+ return { ...base, status: 'domain-mismatch' };
110
+ }
111
+ return { ...base, status: 'ok' };
112
+ }
113
+ /**
114
+ * 决定本次登录写哪个 profile。
115
+ *
116
+ * 默认沿用按域名派生的名字;只有当**另一个宿主已经占用同名 profile 且域名不同**时,
117
+ * 才加 `-<hostKey>` 后缀隔离。`profileNameFromUrl` 只看注册域标签,
118
+ * `weapp.xx.cn` 与 `www.xx.cn` 会撞成同一个名字,不加后缀就会互相把对方挤下线。
119
+ *
120
+ * 两个宿主登同一个域名时**不加后缀**:同租户共用一份凭据是合理的,也不该制造两份登录态。
121
+ */
122
+ export function resolveLoginProfileName(input) {
123
+ const hinted = (input.profileHint || '').trim();
124
+ if (hinted)
125
+ return hinted;
126
+ const derived = (input.derivedName || '').trim() || 'default';
127
+ const hostKey = (input.hostKey || '').trim() || resolveAgentHostKey(input.env || process.env);
128
+ const origin = normalizeOrigin(input.baseUrl);
129
+ const hosts = readAgentHosts()?.hosts || {};
130
+ const claimedByOthers = Object.entries(hosts)
131
+ .filter(([key, record]) => key !== hostKey && record.profile === derived);
132
+ if (!claimedByOthers.length)
133
+ return derived;
134
+ const sharesDomain = claimedByOthers
135
+ .some(([, record]) => normalizeOrigin(record.baseUrl || '') === origin);
136
+ if (sharesDomain)
137
+ return derived;
138
+ return `${derived}-${hostKey}`;
139
+ }
140
+ /** 同步小睡:Node 主线程没有 sync sleep,用 Atomics.wait 代替轮询自旋。 */
141
+ function sleepSync(ms) {
142
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
143
+ }
144
+ /**
145
+ * 串行化 `agents.json` 的读-改-写。
146
+ *
147
+ * 两个宿主几乎同时登录时,无锁的读-改-写会让后写者覆盖前者分区;分区丢失后会回落
148
+ * 全局 `profile` 指针,进而**静默地用上另一个宿主的凭据**。这是唯一会「不报错地用错
149
+ * 账号」的路径,所以这里必须排队。
150
+ *
151
+ * 锁不可用(权限问题、残留锁超时)时退化为直接执行:宁可极少数情况丢记录,
152
+ * 也不能让登录流程卡住。
153
+ */
154
+ function withAgentsLock(task) {
155
+ const lockPath = `${getE10AgentsPath()}.lock`;
156
+ let fd = null;
157
+ try {
158
+ mkdirSync(dirname(lockPath), { recursive: true });
159
+ const deadline = Date.now() + AGENTS_LOCK_TIMEOUT_MS;
160
+ while (fd === null) {
161
+ try {
162
+ fd = openSync(lockPath, 'wx', 0o600);
163
+ }
164
+ catch (error) {
165
+ if (error.code !== 'EEXIST')
166
+ return task();
167
+ if (Date.now() >= deadline) {
168
+ // 残留锁(上次进程崩溃):清掉再抢一次,仍失败就放弃加锁。
169
+ try {
170
+ unlinkSync(lockPath);
171
+ fd = openSync(lockPath, 'wx', 0o600);
172
+ }
173
+ catch {
174
+ return task();
175
+ }
176
+ break;
177
+ }
178
+ sleepSync(AGENTS_LOCK_RETRY_MS);
179
+ }
180
+ }
181
+ }
182
+ catch {
183
+ return task();
184
+ }
185
+ try {
186
+ return task();
187
+ }
188
+ finally {
189
+ if (fd !== null) {
190
+ try {
191
+ closeSync(fd);
192
+ }
193
+ catch { /* 关闭失败不影响结果 */ }
194
+ try {
195
+ unlinkSync(lockPath);
196
+ }
197
+ catch { /* 锁文件可能已被超时清理 */ }
198
+ }
199
+ }
200
+ }
201
+ function writeAgentHosts(file) {
202
+ const filePath = getE10AgentsPath();
203
+ mkdirSync(dirname(filePath), { recursive: true });
204
+ const payload = JSON.stringify(file, null, 2) + '\n';
205
+ const tempPath = `${filePath}.${process.pid}.tmp`;
206
+ writeFileSync(tempPath, payload, { mode: 0o600 });
207
+ renameSync(tempPath, filePath);
208
+ chmodSync(filePath, 0o600);
209
+ }
210
+ /**
211
+ * 记录「当前宿主使用哪个 profile」。
212
+ *
213
+ * 合并写入而非覆盖:只改当前宿主的分区,其他宿主原样保留。写后回读校验,
214
+ * 万一仍被外部写入盖掉就重试一次。失败一律吞掉——登录已经成功,
215
+ * 写偏好记录不该让命令报错。
216
+ */
217
+ export function upsertAgentHost(input) {
218
+ // 连接器授权只新增自己的凭据目录,不应改写用户自己的宿主记忆。
219
+ if (isConnectorMode())
220
+ return null;
221
+ const profile = input.profile?.trim();
222
+ if (!profile)
223
+ return null;
224
+ const env = input.env || process.env;
225
+ const hostKey = input.hostKey?.trim() || resolveAgentHostKey(env);
226
+ const record = {
227
+ profile,
228
+ ...(input.baseUrl ? { baseUrl: input.baseUrl } : {}),
229
+ ...(input.tenantKey ? { tenantKey: input.tenantKey } : {}),
230
+ ...(input.agentType ? { agentType: input.agentType } : {}),
231
+ updatedAt: new Date().toISOString(),
232
+ };
233
+ try {
234
+ return withAgentsLock(() => {
235
+ for (let attempt = 0; attempt < 2; attempt += 1) {
236
+ const hosts = {
237
+ ...(readAgentHosts()?.hosts || {}),
238
+ [hostKey]: record,
239
+ };
240
+ writeAgentHosts({ version: AGENTS_FILE_VERSION, hosts });
241
+ if (readAgentHosts()?.hosts[hostKey]?.profile === profile)
242
+ break;
243
+ }
244
+ return record;
245
+ });
246
+ }
247
+ catch {
248
+ return null;
249
+ }
250
+ }
@@ -3,11 +3,13 @@ import { randomBytes } from 'node:crypto';
3
3
  import { createServer } from 'node:http';
4
4
  import { CliError, ExitCode } from '../../../core/errors.js';
5
5
  import { clearInvoiceTokenForSession } from '../../../shortcuts/invoice/host.js';
6
- import { buildE10CookieHeader, E10AuthSession, clearProfileAuthFile, extractRawSetCookie, extractSessionTicket, findAuthFile, getActiveProfile, getProfileAuthPath, getProfileDir, listProfiles, profileNameFromUrl, readProfileConfig, readTeamsCheckUserInfo, saveAuthFile, saveProfileConfig, setActiveProfile, switchActiveProfile, } from './session.js';
6
+ import { buildE10CookieHeader, E10AuthSession, clearProfileAuthFile, extractRawSetCookie, extractSessionTicket, findAuthFile, getActiveProfile, getProfileAuthPath, getProfileDir, listProfiles, profileNameFromUrl, readProfileConfig, readTeamsCheckUserInfo, resolveActiveProfileForHost, saveAuthFile, saveProfileConfig, setActiveProfile, switchActiveProfile, } from './session.js';
7
+ import { lookupAgentHost, resolveLoginProfileName, upsertAgentHost } from './agent-hosts.js';
8
+ import { resolveAgentHostKey } from './agent-host-key.js';
7
9
  import { getE10AuthRoot } from './paths.js';
8
10
  import { appendXiaoEAuthErrorLog, clearXiaoEAuthErrorLog, getXiaoEAuthErrorLogPath, normalizeXiaoEAuthErrorLogLimit, readXiaoEAuthErrorLog, xiaoEAuthLogSecrets, } from './error-log.js';
9
- import { XIAOE_AGENT_TYPE, createXiaoEUnifiedLoginUnavailableError, hasXiaoEEnv, inspectXiaoEUnifiedLoginSources, resolveXiaoEPreferredBaseUrl, tryXiaoEUnifiedLogin as tryXiaoEUnifiedSessionLogin, } from './xiaoe.js';
10
- export { DEFAULT_E10_BASE_URL, XIAOE_AGENT_TYPE, hasXiaoEEnv, hasXiaoETokenScript, hasXiaoEUnifiedLoginSource, inspectXiaoEUnifiedLoginSources, resolveXiaoEDefaultBaseUrl, resolveXiaoEPreferredBaseUrl, resolveXiaoEUnifiedLoginCredential, } from './xiaoe.js';
11
+ import { XIAOE_AGENT_TYPE, createXiaoEUnifiedLoginUnavailableError, hasXiaoEEnv, inspectXiaoEUnifiedLoginSources, resolveDefaultE10BaseUrl, resolveXiaoEPreferredBaseUrl, tryXiaoEUnifiedLogin as tryXiaoEUnifiedSessionLogin, } from './xiaoe.js';
12
+ export { DEFAULT_E10_BASE_URL, DEFAULT_E10_LOGIN_BASE_URL, XIAOE_AGENT_TYPE, hasXiaoEEnv, hasXiaoETokenScript, hasXiaoEUnifiedLoginSource, isXiaoEHostedEnvironment, inspectXiaoEUnifiedLoginSources, resolveDefaultE10BaseUrl, resolveXiaoEDefaultBaseUrl, resolveXiaoEPreferredBaseUrl, resolveXiaoEUnifiedLoginCredential, } from './xiaoe.js';
11
13
  const DEFAULT_AGENT_TYPE = 'weaver-work-cli';
12
14
  const EXPLICIT_AGENT_TYPE_ENV_KEYS = [
13
15
  'WORKBUDDY_AGENT_TYPE',
@@ -81,6 +83,12 @@ function inferAgentTypeFromEnv(env) {
81
83
  return 'workbuddy';
82
84
  if (hasEnvPrefix(env, 'CODEX'))
83
85
  return 'codex';
86
+ // 豆包办公注入 `DOUBAO_OFFICE_*`(`DOUBAO_OFFICE_AGENT_NAME=doubao_moa` 最稳定),
87
+ // 千问 QwenWork 注入 `QWENWORK_*`。两者都只判存在性,不读值——值随版本变。
88
+ if (hasEnvPrefix(env, 'DOUBAO_OFFICE') || hasEnvPrefix(env, 'DOUBAO'))
89
+ return 'doubao';
90
+ if (hasEnvPrefix(env, 'QWENWORK') || hasEnvPrefix(env, 'QWEN'))
91
+ return 'qwen';
84
92
  return '';
85
93
  }
86
94
  export function resolveAgentType(options = {}, env = process.env) {
@@ -89,6 +97,30 @@ export function resolveAgentType(options = {}, env = process.env) {
89
97
  || inferAgentTypeFromEnv(env)
90
98
  || DEFAULT_AGENT_TYPE;
91
99
  }
100
+ /**
101
+ * 登录类命令的目标解析:先按宿主记忆,再退回全局指针。
102
+ *
103
+ * 优先级的完整定义见 `docs/e10-auth.md`;这里只负责「读哪个 profile 的 config」,
104
+ * 真正拼 baseUrl 时调用方仍把显式 `--base-url` 放在最前面。
105
+ */
106
+ function resolveLoginTarget(input) {
107
+ const explicitAgentType = (input.explicitAgentType || '').trim();
108
+ const hostKey = resolveAgentHostKey(input.env, explicitAgentType);
109
+ const explicitProfile = (input.explicitProfile || '').trim();
110
+ if (explicitProfile) {
111
+ return { hostKey, profile: explicitProfile, cfg: readProfileConfig(explicitProfile) };
112
+ }
113
+ const host = lookupAgentHost(input.env, explicitAgentType);
114
+ if (host) {
115
+ const cfg = readProfileConfig(host.profile);
116
+ // 记录指向的 profile 还有配置就按它走;配置被删干净时退回全局指针,
117
+ // 让登录流程能重新建立一个目标,而不是卡在一条空记录上。
118
+ if (cfg.baseUrl || cfg.tenantKey)
119
+ return { hostKey, profile: host.profile, cfg };
120
+ }
121
+ const active = getActiveProfile();
122
+ return { hostKey, profile: active, cfg: readProfileConfig(active) };
123
+ }
92
124
  function normalizeAgentKey(value) {
93
125
  return value.toLowerCase().replace(/[^a-z0-9]+/gu, '');
94
126
  }
@@ -188,6 +220,7 @@ function formatAuthStatus(status) {
188
220
  'agentType: ' + (status.agentType || ''),
189
221
  'baseUrl: ' + status.baseUrl,
190
222
  'profile: ' + status.profile,
223
+ ...('agentHost' in status && status.agentHost ? ['agentHost: ' + status.agentHost] : []),
191
224
  'authFile: ' + status.authFile,
192
225
  ...('loginSource' in status && status.loginSource ? ['loginSource: ' + status.loginSource] : []),
193
226
  ...('credentialSourceStep' in status && status.credentialSourceStep ? ['credentialSourceStep: ' + status.credentialSourceStep] : []),
@@ -350,7 +383,12 @@ async function saveEteamsIdLogin(input) {
350
383
  throw new CliError('Could not resolve userId. Check whether ETEAMSID is valid for this E10 domain.', ExitCode.AuthError);
351
384
  }
352
385
  const tenantKey = userInfo.tenantKey || input.tenantKeyFallback;
353
- const profile = input.profileHint || profileNameFromUrl(baseUrl);
386
+ const profile = resolveLoginProfileName({
387
+ derivedName: profileNameFromUrl(baseUrl),
388
+ baseUrl,
389
+ hostKey: input.hostKey,
390
+ profileHint: input.profileHint,
391
+ });
354
392
  setActiveProfile(profile);
355
393
  const cookies = { ETEAMSID: input.eteamsId };
356
394
  if (input.rawCookie)
@@ -374,6 +412,7 @@ async function saveEteamsIdLogin(input) {
374
412
  await clearInvoiceTokenCache(profile, authData);
375
413
  const authFile = saveAuthFile(authData, profile);
376
414
  saveProfileConfig(baseUrl, passportUrl, profile, tenantKey);
415
+ upsertAgentHost({ profile, baseUrl, tenantKey, agentType: input.agentType, hostKey: input.hostKey });
377
416
  return {
378
417
  ...userInfo,
379
418
  tenantKey,
@@ -386,7 +425,7 @@ async function saveEteamsIdLogin(input) {
386
425
  version: input.version || '',
387
426
  };
388
427
  }
389
- async function tryXiaoEUnifiedLogin(ctx, baseUrl, tenantKeyFallback, profileHint, allowTokenScript = false, diagnostics) {
428
+ async function tryXiaoEUnifiedLogin(ctx, baseUrl, tenantKeyFallback, profileHint, allowTokenScript = false, diagnostics, hostKey) {
390
429
  const login = await tryXiaoEUnifiedSessionLogin({
391
430
  env: ctx.env,
392
431
  baseUrl,
@@ -396,10 +435,11 @@ async function tryXiaoEUnifiedLogin(ctx, baseUrl, tenantKeyFallback, profileHint
396
435
  allowTokenScript,
397
436
  logger: ctx.logger,
398
437
  diagnostics,
438
+ hostKey,
399
439
  });
400
440
  return login?.result || null;
401
441
  }
402
- async function oidcExchange(code, redirectUri, baseUrl, tenantKeyFallback, agentTypeFallback, profileHint) {
442
+ async function oidcExchange(code, redirectUri, baseUrl, tenantKeyFallback, agentTypeFallback, profileHint, hostKey) {
403
443
  const base = normalizeUrl(baseUrl);
404
444
  const tokenParams = new URLSearchParams({
405
445
  grant_type: 'authorization_code',
@@ -477,11 +517,17 @@ async function oidcExchange(code, redirectUri, baseUrl, tenantKeyFallback, agent
477
517
  cookieSavedAt: Date.now(),
478
518
  ...(ztSession ? { ztSession } : {}),
479
519
  };
480
- const profile = profileHint || profileNameFromUrl(base);
520
+ const profile = resolveLoginProfileName({
521
+ derivedName: profileNameFromUrl(base),
522
+ baseUrl: base,
523
+ hostKey,
524
+ profileHint,
525
+ });
481
526
  setActiveProfile(profile);
482
527
  await clearInvoiceTokenCache(profile, authData);
483
528
  const authFile = saveAuthFile(authData, profile);
484
529
  saveProfileConfig(base, base, profile, tenantKey);
530
+ upsertAgentHost({ profile, baseUrl: base, tenantKey, agentType: agentTypeFallback, hostKey });
485
531
  return {
486
532
  userId: authData.userId,
487
533
  tenantKey,
@@ -515,7 +561,8 @@ async function runXiaoELogin(ctx, options) {
515
561
  const commandOpts = asOptions(options);
516
562
  const globalOptions = ctx.getGlobalOptions();
517
563
  const profileFromGlobal = globalOptions.profile;
518
- const cfg = readProfileConfig(profileFromGlobal || getActiveProfile());
564
+ const hostKey = resolveAgentHostKey(ctx.env);
565
+ const cfg = readProfileConfig(profileFromGlobal || resolveActiveProfileForHost(ctx.env));
519
566
  const explicitBaseUrl = optionString(commandOpts, 'baseUrl') || globalOptions.baseUrl || '';
520
567
  const preferredXiaoEBaseUrl = resolveXiaoEPreferredBaseUrl({
521
568
  explicitBaseUrl,
@@ -554,14 +601,14 @@ async function runXiaoELogin(ctx, options) {
554
601
  ].join(' '));
555
602
  if (useXiaoELogin) {
556
603
  try {
557
- const xiaoEResult = await tryXiaoEUnifiedLogin(ctx, baseUrl, tenantKey, profileFromGlobal, true, diagnostics);
604
+ const xiaoEResult = await tryXiaoEUnifiedLogin(ctx, baseUrl, tenantKey, profileFromGlobal, true, diagnostics, hostKey);
558
605
  if (xiaoEResult)
559
606
  return xiaoEResult;
560
607
  }
561
608
  catch (error) {
562
609
  await appendXiaoEAuthErrorLog({
563
610
  source: 'login',
564
- profile: profileFromGlobal || getActiveProfile(),
611
+ profile: profileFromGlobal || resolveActiveProfileForHost(ctx.env),
565
612
  baseUrl,
566
613
  diagnostics,
567
614
  error,
@@ -574,7 +621,7 @@ async function runXiaoELogin(ctx, options) {
574
621
  const error = createXiaoEUnifiedLoginUnavailableError(baseUrl);
575
622
  await appendXiaoEAuthErrorLog({
576
623
  source: 'login',
577
- profile: profileFromGlobal || getActiveProfile(),
624
+ profile: profileFromGlobal || resolveActiveProfileForHost(ctx.env),
578
625
  baseUrl,
579
626
  diagnostics,
580
627
  error,
@@ -586,19 +633,22 @@ async function runBrowserLogin(ctx, options) {
586
633
  const commandOpts = asOptions(options);
587
634
  const globalOptions = ctx.getGlobalOptions();
588
635
  const profileFromGlobal = globalOptions.profile;
589
- const cfg = readProfileConfig(profileFromGlobal || getActiveProfile());
590
636
  const explicitBaseUrl = optionString(commandOpts, 'baseUrl') || globalOptions.baseUrl || '';
591
- const baseUrl = normalizeUrl(explicitBaseUrl || cfg.baseUrl || '');
637
+ const explicitAgentType = optionString(commandOpts, 'agentType', 'agent_type');
638
+ const agentType = resolveAgentType(commandOpts, ctx.env);
639
+ const target = resolveLoginTarget({
640
+ env: ctx.env,
641
+ explicitProfile: profileFromGlobal,
642
+ explicitAgentType,
643
+ });
644
+ const hostKey = target.hostKey;
645
+ const baseUrl = normalizeUrl(explicitBaseUrl || target.cfg.baseUrl || resolveDefaultE10BaseUrl(ctx.env));
592
646
  const tenantKey = optionString(commandOpts, 'tenantKey');
593
647
  const portText = optionString(commandOpts, 'port') || '19800';
594
648
  const port = Number.parseInt(portText, 10);
595
- const explicitAgentType = optionString(commandOpts, 'agentType', 'agent_type');
596
- const agentType = resolveAgentType(commandOpts, ctx.env);
597
649
  if (!Number.isInteger(port) || port <= 0 || port > 65535) {
598
650
  throw new CliError('Invalid --port value', ExitCode.UsageError);
599
651
  }
600
- if (!baseUrl)
601
- throw new CliError('Missing --base-url', ExitCode.UsageError);
602
652
  const agentReturnTarget = resolveAgentReturnTarget(commandOpts, ctx.env, agentType);
603
653
  const agentReturnToken = agentReturnTarget ? randomBytes(24).toString('base64url') : '';
604
654
  const redirectUri = `http://127.0.0.1:${port}/callback`;
@@ -701,7 +751,7 @@ async function runBrowserLogin(ctx, options) {
701
751
  timer = null;
702
752
  }
703
753
  try {
704
- const result = await oidcExchange(code, redirectUri, baseUrl, tenantKey, redirectAgentType, profileFromGlobal);
754
+ const result = await oidcExchange(code, redirectUri, baseUrl, tenantKey, redirectAgentType, profileFromGlobal, hostKey);
705
755
  const responseHeaders = {
706
756
  'cache-control': 'no-store',
707
757
  'content-security-policy': agentReturnTarget
@@ -907,7 +957,7 @@ function registerXiaoEAuthLogCommands(auth, action) {
907
957
  function registerBrowserLoginCommand(auth, action, name, description, machine = false) {
908
958
  const command = auth.command(name)
909
959
  .description(description)
910
- .option('--base-url <url>', 'E10 base URL')
960
+ .option('--base-url <url>', 'E10 base URL (defaults to https://weapp.eteams.cn)')
911
961
  .option('--tenant-key <key>', 'Tenant key fallback after login')
912
962
  .option('--port <n>', 'Local OAuth callback port', '19800')
913
963
  .option('--agent_type <value>', 'Agent type sent to E10 authorize endpoint')
@@ -941,7 +991,7 @@ function registerBrowserLoginCommand(auth, action, name, description, machine =
941
991
  function registerXiaoELoginCommand(auth, action) {
942
992
  auth.command('xiaoe')
943
993
  .description('Use XiaoE unified login without browser OAuth fallback')
944
- .option('--base-url <url>', 'E10 base URL')
994
+ .option('--base-url <url>', 'E10 base URL (defaults to the host-provided domain)')
945
995
  .option('--tenant-key <key>', 'Tenant key fallback after login')
946
996
  // Keep previously accepted browser flags as no-ops so existing wrappers do
947
997
  // not break. The dedicated handler never parses them or opens a callback.
@@ -970,6 +1020,8 @@ export function registerE10AuthCommands(parent, action) {
970
1020
  const commandOpts = asOptions(options);
971
1021
  const authFile = findAuthFile(ctx.cwd, opts);
972
1022
  const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1023
+ const profile = opts.profile || resolveActiveProfileForHost(ctx.env);
1024
+ const agentHost = resolveAgentHostKey(ctx.env);
973
1025
  const valid = session && commandOpts.check !== false
974
1026
  ? session.isExpired() ? false : await session.checkValid()
975
1027
  : undefined;
@@ -986,7 +1038,8 @@ export function registerE10AuthCommands(parent, action) {
986
1038
  agentType: session.agentType,
987
1039
  baseUrl: session.getBaseUrl(),
988
1040
  passportUrl: session.getPassportUrl(),
989
- profile: opts.profile || getActiveProfile(),
1041
+ profile,
1042
+ agentHost,
990
1043
  authFile,
991
1044
  hasEteamsId: Boolean(session.eteamsId),
992
1045
  ...(session.loginSource ? { loginSource: session.loginSource } : {}),
@@ -998,7 +1051,8 @@ export function registerE10AuthCommands(parent, action) {
998
1051
  }
999
1052
  : {
1000
1053
  loggedIn: false,
1001
- profile: opts.profile || getActiveProfile(),
1054
+ profile,
1055
+ agentHost,
1002
1056
  authFile,
1003
1057
  };
1004
1058
  ctx.output.write(status, { text: formatAuthStatus(status) });
@@ -1012,7 +1066,7 @@ export function registerE10AuthCommands(parent, action) {
1012
1066
  const commandOpts = asOptions(options);
1013
1067
  const authFile = findAuthFile(ctx.cwd, opts);
1014
1068
  const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1015
- const profile = opts.profile || getActiveProfile();
1069
+ const profile = opts.profile || resolveActiveProfileForHost(ctx.env);
1016
1070
  const expired = session ? session.isExpired() : false;
1017
1071
  // 三态探活:只有明确失效(401/403)才算未授权,网络异常保持乐观,避免逼用户重复登录。
1018
1072
  const probe = session && !expired && commandOpts.check !== false
@@ -1035,7 +1089,7 @@ export function registerE10AuthCommands(parent, action) {
1035
1089
  auth.command('set')
1036
1090
  .description('Save E10 auth from an ETEAMSID cookie')
1037
1091
  .requiredOption('--eteamsid <id>', 'ETEAMSID cookie value')
1038
- .option('--base-url <url>', 'E10 base URL')
1092
+ .option('--base-url <url>', 'E10 base URL (defaults to https://weapp.eteams.cn)')
1039
1093
  .option('--passport-url <url>', 'E10 passport URL; defaults to base URL')
1040
1094
  .option('--tenant-key <key>', 'Tenant key fallback')
1041
1095
  .option('--agent_type <value>', 'Agent type used in cookie and User-Agent')
@@ -1044,14 +1098,17 @@ export function registerE10AuthCommands(parent, action) {
1044
1098
  const globalOptions = ctx.getGlobalOptions();
1045
1099
  const commandOpts = asOptions(options);
1046
1100
  const profileFromGlobal = globalOptions.profile;
1047
- const cfg = readProfileConfig(profileFromGlobal || getActiveProfile());
1048
- const baseUrl = normalizeUrl(optionString(commandOpts, 'baseUrl') || globalOptions.baseUrl || cfg.baseUrl || '');
1101
+ const target = resolveLoginTarget({
1102
+ env: ctx.env,
1103
+ explicitProfile: profileFromGlobal,
1104
+ explicitAgentType: optionString(commandOpts, 'agentType', 'agent_type'),
1105
+ });
1106
+ const cfg = target.cfg;
1107
+ const baseUrl = normalizeUrl(optionString(commandOpts, 'baseUrl') || globalOptions.baseUrl || cfg.baseUrl || resolveDefaultE10BaseUrl(ctx.env));
1049
1108
  const passportUrl = normalizeUrl(optionString(commandOpts, 'passportUrl') || globalOptions.passportUrl || cfg.passportUrl || baseUrl);
1050
1109
  const tenantKeyFallback = optionString(commandOpts, 'tenantKey');
1051
1110
  const agentType = resolveAgentType(commandOpts, ctx.env);
1052
1111
  const eteamsId = optionString(commandOpts, 'eteamsid');
1053
- if (!baseUrl)
1054
- throw new CliError('Missing --base-url', ExitCode.UsageError);
1055
1112
  if (!eteamsId)
1056
1113
  throw new CliError('Missing --eteamsid', ExitCode.UsageError);
1057
1114
  ctx.logger.info('Resolving E10 user information...');
@@ -1062,6 +1119,7 @@ export function registerE10AuthCommands(parent, action) {
1062
1119
  tenantKeyFallback,
1063
1120
  agentType,
1064
1121
  profileHint: profileFromGlobal,
1122
+ hostKey: target.hostKey,
1065
1123
  });
1066
1124
  ctx.output.write(result, { text: formatLoginResult(result) });
1067
1125
  }));
@@ -1075,7 +1133,8 @@ export function registerE10AuthCommands(parent, action) {
1075
1133
  .description('Clear saved E10 auth for the current or selected profile')
1076
1134
  .action(action(async (ctx) => {
1077
1135
  const opts = ctx.getGlobalOptions();
1078
- const profile = opts.profile || getActiveProfile();
1136
+ // 当前宿主有记录时清它自己的 profile,避免在 WorkBuddy 里把智能小 E 的登录清掉。
1137
+ const profile = opts.profile || resolveActiveProfileForHost(ctx.env);
1079
1138
  const authFile = getProfileAuthPath(profile);
1080
1139
  const session = E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl);
1081
1140
  if (session) {
@@ -1103,7 +1162,7 @@ export function registerE10AuthCommands(parent, action) {
1103
1162
  const session = authFile ? E10AuthSession.fromFile(authFile, opts.baseUrl, opts.passportUrl) : null;
1104
1163
  if (!session || !session.eteamsId)
1105
1164
  throw new CliError('E10 auth not found.', ExitCode.AuthError);
1106
- const profile = opts.profile || getActiveProfile();
1165
+ const profile = opts.profile || resolveActiveProfileForHost(ctx.env);
1107
1166
  const cached = sessionToCachedUser(session, profile);
1108
1167
  if (!live) {
1109
1168
  ctx.output.write(cached, {
@@ -1183,10 +1242,20 @@ export function registerE10AuthCommands(parent, action) {
1183
1242
  if (typeof name !== 'string')
1184
1243
  throw new CliError('profile name must be a string', ExitCode.UsageError);
1185
1244
  switchActiveProfile(name);
1245
+ // 显式切换同时更新宿主记忆:否则下一次登录会被旧记录带回原来的 profile。
1246
+ const cfg = readProfileConfig(name);
1247
+ const hostRecord = upsertAgentHost({
1248
+ profile: name,
1249
+ ...(cfg.baseUrl ? { baseUrl: cfg.baseUrl } : {}),
1250
+ ...(cfg.tenantKey ? { tenantKey: cfg.tenantKey } : {}),
1251
+ env: ctx.env,
1252
+ });
1186
1253
  const result = {
1187
1254
  active: name,
1188
1255
  dir: getProfileDir(name),
1189
1256
  authFile: getProfileAuthPath(name),
1257
+ agentHost: resolveAgentHostKey(ctx.env),
1258
+ ...(hostRecord ? { agentHostProfile: hostRecord.profile } : {}),
1190
1259
  };
1191
1260
  ctx.output.write(result, { text: 'Active E10 profile: ' + name + '\n' + 'dir: ' + result.dir });
1192
1261
  }));
@@ -10,3 +10,12 @@ export function getE10ProfilesRoot() {
10
10
  export function getE10ActiveProfilePath() {
11
11
  return resolve(getE10AuthRoot(), 'profile');
12
12
  }
13
+ /**
14
+ * 多智能体宿主记录:`hosts[<hostKey>]` 记住该宿主上次登录用的 profile。
15
+ *
16
+ * 与 `profile` 指针同级,但**不受**它的覆盖影响;两者分工是
17
+ * 「`profile` 是无人值守场景的默认值,`agents.json` 是每个宿主各自的记忆」。
18
+ */
19
+ export function getE10AgentsPath() {
20
+ return resolve(getE10AuthRoot(), 'agents.json');
21
+ }
@@ -6,6 +6,7 @@ import { isConnectorMode } from '../../../core/connector.js';
6
6
  import { writeWithRetry } from '../../../core/write-with-retry.js';
7
7
  import { createTimeoutSignal } from '../network-error.js';
8
8
  import { encryptAuthData, parseAuthFile } from './crypto.js';
9
+ import { lookupAgentHost } from './agent-hosts.js';
9
10
  import { getE10ActiveProfilePath, getE10ProfilesRoot } from './paths.js';
10
11
  /**
11
12
  * teamsCheck 与会话探测都是「发业务请求之前的必经往返」,没有上限时一个半开
@@ -169,6 +170,17 @@ export function clearProfileAuthFile(profile = getActiveProfile()) {
169
170
  unlinkSync(authFile);
170
171
  return { profile, authFile, cleared: true };
171
172
  }
173
+ /**
174
+ * 当前宿主应使用的 profile 名。
175
+ *
176
+ * 有宿主记录且记录可用时优先用它;记录缺失(旧数据 / 无宿主标识)时才回到全局
177
+ * `profile` 指针。记录存在但不可用(profile 被删、凭据被清、域名对不上)时
178
+ * **仍然返回该 profile**,让上层按「未登录」处理,而不是静默借用别人的凭据。
179
+ */
180
+ export function resolveActiveProfileForHost(env = process.env) {
181
+ const host = lookupAgentHost(env);
182
+ return host ? host.profile : getActiveProfile();
183
+ }
172
184
  export function findAuthFile(startDir = process.cwd(), options = {}) {
173
185
  if (options.auth)
174
186
  return options.auth;
@@ -180,6 +192,11 @@ export function findAuthFile(startDir = process.cwd(), options = {}) {
180
192
  const envAuth = process.env.E10_AUTH_PATH;
181
193
  if (envAuth && existsSync(envAuth))
182
194
  return envAuth;
195
+ // 宿主记录优先于全局指针:WorkBuddy 与智能小 E 各自认自己的那次登录。
196
+ // 记录存在但不可用时返回 null(视为未登录),不回落——回落等于跨宿主串用凭据。
197
+ const host = lookupAgentHost();
198
+ if (host)
199
+ return host.status === 'ok' ? host.authFile : null;
183
200
  const activeProfileAuth = getProfileAuthPath(getActiveProfile());
184
201
  if (existsSync(activeProfileAuth))
185
202
  return activeProfileAuth;