@aiti-ai/aiti-agent-manager 0.0.0-stage → 0.2.8

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.

Potentially problematic release.


This version of @aiti-ai/aiti-agent-manager might be problematic. Click here for more details.

@@ -0,0 +1,483 @@
1
+ /**
2
+ * agent-manager-client — 统一 Agent 管理面板(零构建原生 h();docs/aiti-codebuddy-agent-plan.md §9)。
3
+ *
4
+ * 列表 = 服务端 GET /agents 聚合(authState/flowState/modes/installed/accounts);
5
+ * 行操作经 /ctl/{agent}/{action} 代理到各扩展既有 /login/*(本面板不实现任何登录协议);
6
+ * 账号档(备份/切换/登出)走本扩展 /accounts/{agent}/{action}——单文件存储,服务端实现,
7
+ * 登录/切换/登出前的当前状态由服务端自动存 _auto-* 保险档。
8
+ * 样式:自持样式层 agent-manager-styles.mjs(am-* 类,config-button 设计语言 + 主题 var 跟随)。
9
+ * 打开期间 3s 轮询(§3.6 拍板例外:弹窗打开期间的登录状态轮询);操作后立即刷新(refreshNonce)。
10
+ *
11
+ * export default function register(ctx) { registerAgentManagerClient(ctx, { extId: "aiti-agent-manager" }); }
12
+ */
13
+
14
+ import { ensureStyles } from "./agent-manager-styles.mjs";
15
+
16
+ /** 自动保险档别名 → 展示名(服务端在各覆盖性操作前自动生成)。 */
17
+ const AUTO_LABEL = {
18
+ "_auto-before-switch": "自动·切换前",
19
+ "_auto-before-login": "自动·登录前",
20
+ "_auto-before-logout": "自动·登出前",
21
+ };
22
+
23
+ /** 过期时间戳(ms)→ 本地短日期(YYYY-MM-DD)。 */
24
+ function fmtDate(ms) {
25
+ try { return new Date(ms).toLocaleDateString(); } catch { return String(ms); }
26
+ }
27
+
28
+ /** 数字千分位(最多 2 位小数)。 */
29
+ function fmtNum(n) {
30
+ try { return Number(n).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch { return String(n); }
31
+ }
32
+
33
+ /** 额度 chip 文案(display 优先;否则 剩余/总量 归一)。 */
34
+ function quotaText(q) {
35
+ if (typeof q.display === "string" && q.display.trim()) return q.display.trim();
36
+ const unit = q.unit ?? "";
37
+ if (q.remaining !== undefined && q.total !== undefined) return `额度 ${fmtNum(q.remaining)} / ${fmtNum(q.total)} ${unit}`.trim();
38
+ if (q.remaining !== undefined) return `额度 剩余 ${fmtNum(q.remaining)} ${unit}`.trim();
39
+ if (q.usedPercent !== undefined) return `额度 剩余 ${fmtNum(100 - q.usedPercent)}%`;
40
+ return "额度";
41
+ }
42
+
43
+ /** 额度 tooltip(分包明细 + 更新时间)。 */
44
+ function quotaTitle(q) {
45
+ const pkgs = (q.packages ?? []).map((p, i) => {
46
+ const name = p.name ?? `包${i + 1}`;
47
+ if (p.remaining !== undefined && p.total !== undefined) return `${name}:${fmtNum(p.remaining)} / ${fmtNum(p.total)} ${p.unit ?? q.unit ?? ""}`.trim();
48
+ if (p.usedPercent !== undefined) return `${name}:已用 ${fmtNum(p.usedPercent)}%`;
49
+ if (p.remaining !== undefined) return `${name}:剩余 ${fmtNum(p.remaining)} ${p.unit ?? q.unit ?? ""}`.trim();
50
+ return p.note ? `${name}:${p.note}` : name;
51
+ }).join("\n");
52
+ const extra = q.note ? `\n${q.note}` : "";
53
+ return `额度(点击刷新)${pkgs ? "\n" + pkgs : ""}${extra}\n更新于 ${new Date(q.fetchedAt).toLocaleTimeString()}`;
54
+ }
55
+
56
+ export function registerAgentManagerClient(ctx, config) {
57
+ ensureStyles(); // 自持样式层(am-* 类):register 即注入,先于任何 UI 渲染
58
+ const h = (...a) => ctx.h(...a);
59
+ const useState = (v) => ctx.useState(v);
60
+ const useEffect = (fn, deps) => ctx.useEffect(fn, deps);
61
+ const api = (p, init) => fetch(ctx.apiUrl("/api/extensions/" + config.extId + p), { cache: "no-store", ...init });
62
+ const jsonInit = (body) => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
63
+
64
+ ctx.registerItems("toolbar", [{
65
+ id: `${config.extId}-panel`,
66
+ meta: {
67
+ label: "Agent 管理",
68
+ title: "Agent 管理(统一登录态)",
69
+ icon: "icons/bot.svg",
70
+ onClick: () => requestOpen(),
71
+ },
72
+ }]);
73
+ ctx.registerItems("dialogs", [{
74
+ id: `${config.extId}-panel-dialog`,
75
+ render: () => h(AgentManagerPanel),
76
+ }]);
77
+
78
+ let moduleSetOpen = null;
79
+ // 懒加载(clientImmediately:false)下 toolbar 静态条目点击时面板组件可能尚未挂载:
80
+ // 记 pending,挂载 effect 消费——避免首点失效。
81
+ let pendingOpen = false;
82
+ function requestOpen() {
83
+ if (moduleSetOpen) moduleSetOpen(true);
84
+ else pendingOpen = true;
85
+ }
86
+
87
+ // ── 稳定子组件(定义提升到 register 作用域,⚠ 勿移回 AgentManagerPanel 内!)──
88
+ // 2026-09-13 焦点窃取事故:子组件内联定义在父组件函数体内时,父组件每次渲染都会生成
89
+ // 新的函数身份,React diff 视为「不同组件类型」→ 整个子树卸载重建——账号档输入框在
90
+ // 3s 轮询 setData / 每次按键 setState / 宿主重渲染时被反复销毁重建(focusout + DOM removed),
91
+ // 焦点不断被“窃取”、无法连续输入。提升到此处(register 仅执行一次 → 身份跨渲染稳定),
92
+ // 状态与回调经 props 传入。
93
+
94
+ /** 账号档面板:只列已保存的档(切换·删除);新增保存入口在「当前登录」行。 */
95
+ function AccountPanel({ agent, accounts, busy, actAccounts, setNotice, confirmDel, setConfirmDel }) {
96
+ return h("div", { className: "am-accounts" },
97
+ h("div", { className: "am-accounts-title" },
98
+ "账号档",
99
+ h("span", { className: "am-acc-chip" }, `${accounts.length} 个`),
100
+ ),
101
+ h("div", { className: "am-hint" },
102
+ "这里只列已保存的账号档(供切换 / 删除);新增保存用上方「当前登录」旁的「保存为账号档…」;登录 / 切换前旧状态自动存 _auto-before-* 保险档。"),
103
+ accounts.length === 0
104
+ ? h("div", { className: "am-empty" }, "暂无账号档——先保存当前登录,或直接登录新账号")
105
+ : h("div", { className: "am-acc-list" }, ...accounts.map((acc) => h(AccountRow, { key: acc.alias, acc, agent, busy, actAccounts, setNotice, confirmDel, setConfirmDel }))),
106
+ );
107
+ }
108
+
109
+ /** 账号档行:别名/账号信息(user+uin+有效期)/凭据数/保存日 + 切换/删除(删除二次确认)。 */
110
+ function AccountRow({ acc, agent, busy, actAccounts, setNotice, confirmDel, setConfirmDel }) {
111
+ const label = AUTO_LABEL[acc.alias] ?? acc.alias;
112
+ const delPending = confirmDel && confirmDel.agent === agent && confirmDel.alias === acc.alias;
113
+ const name = acc.user ?? acc.note;
114
+ const who = name ? `账号 ${name}${acc.uin ? `(uin ${acc.uin})` : ""}` : null;
115
+ const expiry = typeof acc.expiresAt === "number" ? `有效期至 ${fmtDate(acc.expiresAt)}` : null;
116
+ const meta = [who, expiry, `${acc.slotCount} 项凭据`, `保存于 ${fmtDate(acc.savedAt)}`].filter(Boolean).join(" · ");
117
+ return h("div", { className: "am-acc-item" + (acc.current ? " is-current" : "") },
118
+ h("span", { className: "am-acc-label" + (acc.auto ? " is-auto" : "") }, label),
119
+ acc.current && h("span", { className: "am-acc-chip is-current" }, "当前"),
120
+ h("span", { className: "am-acc-meta", title: meta }, meta),
121
+ h("div", { className: "am-acc-actions" },
122
+ !acc.current && h("button", {
123
+ className: "am-btn is-sm",
124
+ disabled: busy === `${agent}:accounts-switch`,
125
+ title: "恢复该账号档到本机登录位置(当前状态若未存档会先自动存 _auto-before-switch)",
126
+ onClick: async () => {
127
+ const d = await actAccounts(agent, "switch", { alias: acc.alias }, `已切换到「${label}」:新会话生效(旧会话保持原账号)`);
128
+ if (d?.autoSaved) setNotice({ ok: true, text: `已切换到「${label}」;切换前状态已自动存为「${AUTO_LABEL["_auto-before-switch"]}」` });
129
+ },
130
+ }, busy === `${agent}:accounts-switch` ? "切换中…" : "切换"),
131
+ h("button", {
132
+ className: "am-btn is-sm" + (delPending ? " is-danger" : ""),
133
+ disabled: busy === `${agent}:accounts-remove`,
134
+ onClick: () => {
135
+ if (delPending) {
136
+ setConfirmDel(null);
137
+ void actAccounts(agent, "remove", { alias: acc.alias }, `已删除账号档「${label}」`);
138
+ } else {
139
+ setConfirmDel({ agent, alias: acc.alias });
140
+ setTimeout(() => setConfirmDel((cur) => (cur && cur.agent === agent && cur.alias === acc.alias ? null : cur)), 2500);
141
+ }
142
+ },
143
+ }, delPending ? "确认删除?" : "删除"),
144
+ ),
145
+ );
146
+ }
147
+
148
+ /** CodeBuddy API Key 表单(内部 useState 自持;组件身份稳定 → 输入不被打断)。 */
149
+ function KeyForm({ agent, onDone, call: callFn }) {
150
+ const [apiKey, setApiKey] = useState("");
151
+ const [authToken, setAuthToken] = useState("");
152
+ const [baseUrl, setBaseUrl] = useState("");
153
+ return h("div", { className: "am-subpanel" },
154
+ h("input", { className: "am-input", placeholder: "CODEBUDDY_API_KEY(平台个人 key)", value: apiKey, onInput: (e) => setApiKey(e?.target?.value ?? "") }),
155
+ h("input", { className: "am-input", placeholder: "CODEBUDDY_AUTH_TOKEN(可选,优先级更高)", value: authToken, onInput: (e) => setAuthToken(e?.target?.value ?? "") }),
156
+ h("input", { className: "am-input", placeholder: "CODEBUDDY_BASE_URL(可选,第三方网关)", value: baseUrl, onInput: (e) => setBaseUrl(e?.target?.value ?? "") }),
157
+ h("div", { className: "am-actions is-end" },
158
+ h("button", { className: "am-btn", onClick: onDone }, "收起"),
159
+ h("button", {
160
+ className: "am-btn is-primary",
161
+ disabled: !apiKey.trim() && !authToken.trim() && !baseUrl.trim(),
162
+ onClick: async () => { await callFn(`${agent}:set-key`, `/ctl/${agent}/set-key`, jsonInit({ apiKey, authToken, baseUrl })); onDone(); },
163
+ }, "保存(空串=清除该字段)"),
164
+ ),
165
+ );
166
+ }
167
+
168
+ function AgentManagerPanel() {
169
+ const [open, setOpen] = useState(false);
170
+ const [data, setData] = useState(null); // /agents 响应
171
+ const [reqError, setReqError] = useState(null);
172
+ const [notice, setNotice] = useState(null); // 操作结果反馈 {ok, text}
173
+ const [busy, setBusy] = useState(null); // 进行中动作 key(`${agent}:${action}`)
174
+ const [keyForm, setKeyForm] = useState(null); // codebuddy apikey 表单 {agent} | null
175
+ const [accOpen, setAccOpen] = useState(null); // 展开账号档的 agent
176
+ const [saveForm, setSaveForm] = useState(null); // {agent, alias} 保存账号档弹窗
177
+ const [pasteCode, setPasteCode] = useState({}); // {agent: code}
178
+ const [refreshNonce, setRefreshNonce] = useState(0);
179
+ const [confirmDel, setConfirmDel] = useState(null); // {agent, alias} 删除账号档二次确认
180
+ const [confirmLogout, setConfirmLogout] = useState(null); // agent 登出二次确认
181
+
182
+ useEffect(() => {
183
+ moduleSetOpen = setOpen;
184
+ if (pendingOpen) { pendingOpen = false; setOpen(true); }
185
+ return () => { if (moduleSetOpen === setOpen) moduleSetOpen = null; };
186
+ }, []);
187
+
188
+ // 打开期间 3s 轮询聚合状态(弹窗期例外);关闭即停;refreshNonce 变化 = 操作后立即刷新
189
+ useEffect(() => {
190
+ if (!open) return;
191
+ let stopped = false;
192
+ let timer = null;
193
+ const tick = async () => {
194
+ try {
195
+ const r = await api("/agents");
196
+ const d = await r.json();
197
+ if (!stopped && d?.agents) { setData(d); setReqError(null); }
198
+ } catch { /* 网络抖动忽略 */ }
199
+ if (!stopped) timer = setTimeout(tick, 3000);
200
+ };
201
+ tick();
202
+ return () => { stopped = true; if (timer) clearTimeout(timer); };
203
+ }, [open, refreshNonce]);
204
+
205
+ const refresh = () => setRefreshNonce((n) => n + 1);
206
+
207
+ async function call(actionKey, p, init) {
208
+ setBusy(actionKey);
209
+ setReqError(null);
210
+ let d = null;
211
+ try {
212
+ const r = await api(p, init);
213
+ d = await r.json();
214
+ if (d && d.error) setReqError(`${actionKey}: ${d.error}`);
215
+ } catch (e) {
216
+ setReqError(`${actionKey}: ${e?.message || e}`);
217
+ }
218
+ setBusy(null);
219
+ return d;
220
+ }
221
+ const ctl = (agent, action, body) => call(`${agent}:${action}`, `/ctl/${agent}/${action}`, jsonInit(body ?? {}));
222
+
223
+ /** 直接打开 aiti-cmd 终端面板渲染指定会话(svc 优先;懒加载时先物化;兼容旧全局兑底)。 */
224
+ async function openCmdTerminal(sid, title) {
225
+ const key = "aiti-cmd.open-session";
226
+ let svc = ctx.getExtService?.(key);
227
+ if (typeof svc !== "function" && typeof ctx.ensureMaterialized === "function") {
228
+ try { await ctx.ensureMaterialized("aiti-cmd"); } catch { /* 未部署等 */ }
229
+ svc = ctx.getExtService?.(key);
230
+ }
231
+ if (typeof svc === "function") { try { svc(sid, title); return true; } catch { /* 下落 */ } }
232
+ const legacy = typeof window !== "undefined" ? window.__aitiCmd?.openSession : null;
233
+ if (typeof legacy === "function") { legacy(sid, title); return true; }
234
+ return false;
235
+ }
236
+
237
+ /** 账号档动作(本扩展 /accounts/*):成功 → 绿色反馈 + 立即刷新。 */
238
+ async function actAccounts(agent, action, body, okText) {
239
+ const d = await call(`${agent}:accounts-${action}`, `/accounts/${agent}/${action}`, jsonInit(body ?? {}));
240
+ if (d && !d.error) { setNotice({ ok: true, text: okText }); refresh(); }
241
+ else if (d?.error) setNotice({ ok: false, text: `${action} 失败:${d.error}` });
242
+ return d;
243
+ }
244
+
245
+ /** 登出(二次确认;服务端先自动存 _auto-before-logout 保险档再清凭据)。 */
246
+ function handleLogout(agent) {
247
+ if (confirmLogout !== agent) {
248
+ setConfirmLogout(agent);
249
+ setTimeout(() => setConfirmLogout((cur) => (cur === agent ? null : cur)), 2500);
250
+ return;
251
+ }
252
+ setConfirmLogout(null);
253
+ void actAccounts(agent, "logout", {}, "已登出:本机凭据已清(保险档保留在账号档列表)");
254
+ }
255
+
256
+ if (!open) return null;
257
+ const agents = data?.agents ?? [];
258
+
259
+ return h(
260
+ "div",
261
+ { className: "am-panel", "data-ext-float": "1", "data-ext-float-w": "560", "data-ext-float-h": "460" },
262
+ h("div", { className: "am-head" },
263
+ h("b", { className: "am-title" }, "Agent 管理"),
264
+ h("span", { className: "am-head-sub" }, "统一登录态 · 账号档"),
265
+ h("span", { className: "am-spacer" }),
266
+ h("button", { className: "am-btn is-ghost is-sm", onClick: () => setOpen(false), title: "关闭" }, "✕"),
267
+ ),
268
+ h("div", { className: "am-body" },
269
+ reqError && h("div", { className: "am-error" }, reqError),
270
+ notice && h("div", { className: "am-notice" }, notice.text),
271
+ !agents.length && h("div", { className: "am-empty" }, "加载中…"),
272
+ ...agents.map((a) => hAgentRow(a)),
273
+ hPiHost(data?.piHost),
274
+ h("div", { className: "am-foot" },
275
+ "登录操作代理到各扩展既有 /login/* 端点;账号档存于 configDir/agent-accounts.json(备份加密)。CodeBuddy 浏览器 OAuth 的终端渲染在 aiti-cmd 面板(sid 共享,可一键打开)。"),
276
+ ),
277
+ // 保存账号档弹窗(命名后提交;紧跟「当前登录」的保存入口)
278
+ saveForm && h("div", { className: "am-modal-mask", onClick: () => setSaveForm(null) },
279
+ h("div", { className: "am-modal", onClick: (e) => e.stopPropagation() },
280
+ h("div", { className: "am-accounts-title" }, "保存为账号档"),
281
+ h("div", { className: "am-hint" }, `把「${saveForm.agent}」当前登录保存为账号档,起个别名便于日后切换与识别。`),
282
+ h("input", {
283
+ className: "am-input", autoFocus: true, placeholder: "别名(如 主账号 / 团队号 / 客户A)",
284
+ value: saveForm.alias,
285
+ onInput: (e) => setSaveForm((f) => (f ? { ...f, alias: e?.target?.value ?? "" } : f)),
286
+ onKeyDown: (e) => {
287
+ if (e?.key === "Enter") void saveNow();
288
+ else if (e?.key === "Escape") setSaveForm(null);
289
+ },
290
+ }),
291
+ h("div", { className: "am-actions is-end" },
292
+ h("button", { className: "am-btn", onClick: () => setSaveForm(null) }, "取消"),
293
+ h("button", {
294
+ className: "am-btn is-primary",
295
+ disabled: !saveForm.alias.trim() || busy === `${saveForm.agent}:accounts-save`,
296
+ onClick: () => void saveNow(),
297
+ }, busy === `${saveForm.agent}:accounts-save` ? "保存中…" : "保存"),
298
+ ),
299
+ ),
300
+ ),
301
+ );
302
+
303
+ // §9.5 步 5:pi 宿主订阅 provider(auth.json 只读,无 provider 时整组隐藏)
304
+ function hPiHost(piHost) {
305
+ if (!Array.isArray(piHost) || piHost.length === 0) return null;
306
+ return h(
307
+ "div",
308
+ { className: "am-row" },
309
+ h("div", { className: "am-meta", style: { marginBottom: 4 } }, "pi 宿主订阅(模型向导 OAuth,只读展示)"),
310
+ ...piHost.map((p) => h("div", { key: p.provider, className: "am-acc-item" },
311
+ h("b", { className: "am-acc-label" }, p.provider),
312
+ p.user && h("span", { className: "am-acc-meta" }, p.user),
313
+ h("span", { className: "am-spacer" }),
314
+ p.expired === true
315
+ ? h("span", { className: "am-acc-chip", style: { color: "#d97706", borderColor: "rgba(217,119,6,.4)" } }, "token 已过期,重新登录可续期")
316
+ : h("span", { className: "am-acc-chip is-current" }, "已授权"),
317
+ )),
318
+ );
319
+ }
320
+
321
+ function badge(authState, flowState) {
322
+ if (flowState === "logging-in") return h("span", { className: "am-badge is-logging" }, "登录中");
323
+ if (authState === "ready") return h("span", { className: "am-badge is-ready" }, "已登录");
324
+ if (authState === "missing") return h("span", { className: "am-badge is-missing" }, "未登录");
325
+ return h("span", { className: "am-badge is-unknown" }, "未知");
326
+ }
327
+
328
+ // 保存账号档弹窗的提交
329
+ async function saveNow() {
330
+ const f = saveForm;
331
+ const alias = (f?.alias ?? "").trim();
332
+ if (!f || !alias) return;
333
+ const d = await actAccounts(f.agent, "save", { alias }, `已保存账号档「${alias}」`);
334
+ if (d && !d.error) setSaveForm(null);
335
+ }
336
+
337
+ function hAgentRow(a) {
338
+ const key = a.agent;
339
+ const isCb = a.agent === "codebuddy";
340
+ const ext = a.ext ?? {};
341
+ const accounts = a.accounts ?? [];
342
+ const hasContent = a.hasContent === true;
343
+ const tuiActive = Boolean(a.tui?.tuiSid);
344
+ return h(
345
+ "div",
346
+ { key, className: "am-row" },
347
+ h("div", { className: "am-row-head" },
348
+ h("span", { className: "am-name" }, a.label),
349
+ badge(a.authState, a.flowState),
350
+ a.authSource === "fs" && h("span", { className: "am-flag" }, "(探测)"),
351
+ h("span", { className: "am-spacer" }),
352
+ !a.installed && h("span", { className: "am-flag" }, "扩展未部署"),
353
+ ),
354
+ h("div", { className: "am-meta" },
355
+ "登录形态:" + (a.modes ?? []).map((m) => ({ url: "授权链接", paste: "粘贴 code", apikey: "API Key", tui: "浏览器 OAuth" }[m] ?? m)).join(" / ")
356
+ + (a.dependencyHint ? ` · 依赖:${a.dependencyHint}` : "")),
357
+ // 当前登录:展示账号/过期 + 保存入口紧贴(新增档从这里存,账号档卡片只列已存的)
358
+ (ext?.account?.user || hasContent) && h("div", { className: "am-acct-line " + (ext?.account?.expired ? "is-warn" : "is-ok") },
359
+ ext?.account?.user
360
+ ? `CLI 登录账号:${ext.account.user}${ext.account.uin ? `(uin ${ext.account.uin})` : ""}`
361
+ + (ext.account.expired
362
+ ? " · 已过期,请在 CLI 内重新登录"
363
+ : ext.account.expiresAt ? ` · 有效期至 ${fmtDate(ext.account.expiresAt)}` : "")
364
+ : "当前登录:已检测到本机凭据",
365
+ hasContent && h("button", {
366
+ className: "am-btn is-sm", style: { marginLeft: 8 },
367
+ title: "把当前本机登录保存为账号档(起别名)",
368
+ onClick: () => setSaveForm({ agent: key, alias: "" }),
369
+ }, "保存为账号档…"),
370
+ // 官方账号额度(descriptor.accountQuota;点击强制刷新)
371
+ a.quota?.available === true && h("button", {
372
+ className: "am-btn is-ghost is-sm", style: { marginLeft: 8 },
373
+ title: quotaTitle(a.quota),
374
+ onClick: async () => {
375
+ const r = await fetch(ctx.apiUrl(`/api/extensions/${config.extId}/quota/${key}?force=1`), { cache: "no-store" });
376
+ const d = await r.json().catch(() => null);
377
+ if (d && d.error) setNotice({ ok: false, text: d.error });
378
+ refresh();
379
+ },
380
+ }, quotaText(a.quota)),
381
+ a.quota?.available === false && a.quota.reason === "fetch-failed" && h("span", {
382
+ className: "am-flag", style: { marginLeft: 8 },
383
+ title: `额度查询失败:${a.quota.error ?? ""}`,
384
+ }, "额度查询失败"),
385
+ ),
386
+ // ── 操作条 1:登录 / 授权 ──
387
+ h("div", { className: "am-actions" },
388
+ !isCb && (a.modes ?? []).includes("url") && h("button",
389
+ { className: "am-btn", disabled: busy === `${key}:start`, onClick: () => ctl(key, "start") },
390
+ busy === `${key}:start` ? "发起中…" : "登录"),
391
+ !isCb && (a.modes ?? []).includes("paste") && h("button",
392
+ { className: "am-btn", disabled: busy === `${key}:start`, onClick: () => ctl(key, "start") },
393
+ busy === `${key}:start` ? "发起中…" : "登录"),
394
+ !isCb && h("button", { className: "am-btn", disabled: busy === `${key}:cancel`, onClick: () => ctl(key, "cancel") }, "取消"),
395
+ !isCb && (a.modes ?? []).includes("paste") && h("span", { className: "am-inline" },
396
+ h("input", {
397
+ className: "am-input", placeholder: "粘贴授权完成页 code(或回调链接)",
398
+ value: pasteCode[key] ?? "",
399
+ onInput: (e) => setPasteCode({ ...pasteCode, [key]: e?.target?.value ?? "" }),
400
+ }),
401
+ h("button", {
402
+ className: "am-btn is-primary",
403
+ disabled: !(pasteCode[key] ?? "").trim() || busy === `${key}:submit`,
404
+ onClick: () => ctl(key, "submit", { code: pasteCode[key] }),
405
+ }, "提交"),
406
+ ),
407
+ isCb && h("button", { className: "am-btn" + (keyForm === key ? " is-primary" : ""), onClick: () => setKeyForm(keyForm === key ? null : key) }, "API Key…"),
408
+ isCb && h("button", {
409
+ className: "am-btn",
410
+ disabled: busy === `${key}:tui-start`,
411
+ title: "发起新的浏览器 OAuth 登录(会覆盖 CLI 当前登录;覆盖前自动存 _auto-before-login 保险档)",
412
+ onClick: async () => {
413
+ const d = await ctl(key, "tui-start");
414
+ if (d && !d.error) {
415
+ setNotice({ ok: true, text: d.backupDir ? "OAuth 已发起:旧登录已备份并暂离(随时可从「账号档」切回);完成后把新账号存档起别名" : "OAuth 已发起:完成登录后到「账号档」把新账号存档并起别名" });
416
+ // 直接打开 aiti-cmd 终端面板(浏览器 OAuth 的交互面在该面板里)
417
+ if (d.sid) { const okOpen = await openCmdTerminal(d.sid, "cbc-login"); if (!okOpen) setNotice({ ok: false, text: "OAuth 已发起,但未能打开 aiti-cmd 终端面板(未部署/未加载)" }); }
418
+ }
419
+ },
420
+ }, busy === `${key}:tui-start` ? "发起中…" : "浏览器 OAuth"),
421
+ isCb && h("button", {
422
+ className: "am-btn",
423
+ disabled: busy === `${key}:tui-cancel` || !tuiActive,
424
+ title: tuiActive ? "终止进行中的 OAuth 登录会话" : "当前无进行中的 OAuth 登录",
425
+ onClick: async () => {
426
+ const d = await ctl(key, "tui-cancel");
427
+ if (d && !d.error) { setNotice({ ok: true, text: "已取消 OAuth 登录会话" }); refresh(); }
428
+ },
429
+ }, "取消 OAuth"),
430
+ ),
431
+ // ── 操作条 2:账号档 / 登出(右对齐) ──
432
+ a.installed && h("div", { className: "am-actions is-end" },
433
+ h("button", {
434
+ className: "am-btn" + (accOpen === key ? " is-primary" : ""),
435
+ onClick: () => setAccOpen(accOpen === key ? null : key),
436
+ title: "多账号备份 / 切换",
437
+ }, accOpen === key ? "收起账号档" : `账号档${accounts.length ? `(${accounts.length})` : "…"}`),
438
+ h("button", {
439
+ className: "am-btn" + (confirmLogout === key ? " is-danger" : ""),
440
+ disabled: busy === `${key}:accounts-logout` || !hasContent,
441
+ title: hasContent
442
+ ? "清空本机当前登录凭据(自动先存 _auto-before-logout 保险档)"
443
+ : "当前无登录态可登出",
444
+ onClick: () => handleLogout(key),
445
+ }, confirmLogout === key ? "确认登出?" : "登出"),
446
+ ),
447
+ // 流程错误(失败/超时)透传展示——等价退役的扩展内登录弹窗 error 行
448
+ ext?.error && h("div", { className: "am-error" }, String(ext.error)),
449
+ // URL 展示(A url-only 模式:ext.url 由聚合透传)
450
+ ext?.url && h("div", { className: "am-url-line" },
451
+ h("a", { className: "am-url", href: ext.url, target: "_blank", rel: "noreferrer" }, ext.url.slice(0, 90) + (ext.url.length > 90 ? "…" : "")),
452
+ h("button", { className: "am-btn is-ghost is-sm", onClick: () => { try { navigator.clipboard?.writeText(ext.url); } catch { /* 无剪贴板权限 */ } } }, "复制"),
453
+ ),
454
+ // codebuddy TUI OAuth 状态行
455
+ isCb && a.tui?.tuiSid && h("div", { className: "am-tui-line" },
456
+ `OAuth ${a.tui.tuiState ?? "waiting"} · 终端会话 ${a.tui.tuiSid}`,
457
+ h("button", {
458
+ className: "am-btn is-sm",
459
+ style: { marginLeft: 6 },
460
+ title: "在 aiti-cmd 终端面板中打开该会话(共享 sid)",
461
+ onClick: async () => {
462
+ const okOpen = await openCmdTerminal(a.tui.tuiSid, "cbc-login");
463
+ if (!okOpen) setNotice({ ok: false, text: "未能打开 aiti-cmd 终端面板(未部署/未加载)" });
464
+ },
465
+ }, "打开终端"),
466
+ a.tui.tuiUrl && h("a", { href: a.tui.tuiUrl, target: "_blank", rel: "noreferrer" }, "打开授权页"),
467
+ ),
468
+ // codebuddy apikey 表单
469
+ isCb && keyForm === key && h(KeyForm, { agent: key, onDone: () => setKeyForm(null), call }),
470
+ // 账号档面板(所有 agent 一致)
471
+ accOpen === key && h(AccountPanel, {
472
+ agent: key, accounts,
473
+ busy, actAccounts, setNotice, confirmDel, setConfirmDel,
474
+ }),
475
+ );
476
+ }
477
+
478
+ }
479
+ }
480
+
481
+ export default function register(ctx) {
482
+ registerAgentManagerClient(ctx, { extId: "aiti-agent-manager" });
483
+ }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * agent-manager-styles — aiti-agent-manager 自持样式层(零构建,am- 前缀)。
3
+ *
4
+ * 设计语言复刻 pi-web `app/settings.css` 的 config-button 系列:
5
+ * 5px 圆角 / .14s 过渡 / primary|secondary|danger|ghost 四态 / focus-visible 描边 /
6
+ * disabled 0.5 透明度;主题跟随 `var(--x, 兜底)` 弱引用宿主令牌(亮/暗/主题色自动适配)。
7
+ * ensureStyles() 幂等注入 <style>(多次 register / 多副本加载安全)。
8
+ */
9
+
10
+ export const STYLES = `
11
+ /* ===== 面板外壳(aiti-float 未接管时的回退锚定;接管后由属性驱动覆盖) ===== */
12
+ .am-panel {
13
+ position: fixed; top: 8%; right: 3%; z-index: 9999;
14
+ width: 560px; max-width: 94vw;
15
+ display: flex; flex-direction: column;
16
+ max-height: 78vh;
17
+ background: var(--bg, #fff); color: var(--text, #1a1a1a);
18
+ border: 1px solid var(--border, #e0e0e0); border-radius: 10px;
19
+ box-shadow: 0 12px 36px rgba(0, 0, 0, .28);
20
+ font-size: 13px; line-height: 1.5;
21
+ }
22
+ .am-head {
23
+ display: flex; align-items: center; gap: 8px;
24
+ padding: 10px 14px 9px;
25
+ border-bottom: 1px solid var(--border, #e0e0e0);
26
+ flex-shrink: 0;
27
+ }
28
+ .am-title { font-weight: 600; font-size: 13px; }
29
+ .am-head-sub { font-size: 11px; color: var(--text-dim, #5e6673); }
30
+ .am-spacer { flex: 1; }
31
+ .am-body { flex: 1; min-height: 0; overflow-y: auto; padding: 2px 14px 12px; }
32
+
33
+ /* ===== 提示条(操作结果 / 错误) ===== */
34
+ .am-notice, .am-error {
35
+ margin: 8px 0 2px; padding: 6px 10px; border-radius: 6px;
36
+ font-size: 12px; line-height: 17px; white-space: pre-wrap;
37
+ }
38
+ .am-notice { background: rgba(22, 163, 74, .08); border: 1px solid rgba(22, 163, 74, .28); color: #16a34a; }
39
+ .am-error { background: rgba(220, 38, 38, .07); border: 1px solid rgba(220, 38, 38, .28); color: #dc2626; }
40
+
41
+ /* ===== agent 行 ===== */
42
+ .am-row { padding: 10px 0; border-top: 1px solid var(--border, #e0e0e0); }
43
+ .am-row:first-child { border-top: 0; }
44
+ .am-row-head { display: flex; align-items: center; gap: 8px; }
45
+ .am-name { font-weight: 600; font-size: 13px; }
46
+ .am-badge { font-size: 12px; font-weight: 600; white-space: nowrap; }
47
+ .am-badge.is-ready { color: #16a34a; }
48
+ .am-badge.is-missing { color: #d97706; }
49
+ .am-badge.is-unknown { color: var(--text-dim, #5e6673); }
50
+ .am-badge.is-logging { color: var(--accent, #245bce); }
51
+ .am-flag { font-size: 11px; color: var(--text-dim, #5e6673); }
52
+ .am-meta {
53
+ margin: 3px 0 8px; font-size: 11px; line-height: 16px;
54
+ color: var(--text-muted, #515c6b);
55
+ }
56
+ .am-acct-line { font-size: 11px; line-height: 16px; margin: 0 0 8px; }
57
+ .am-acct-line.is-ok { color: #16a34a; }
58
+ .am-acct-line.is-warn { color: #d97706; }
59
+
60
+ /* ===== 操作条(分组换行;账号组右对齐) ===== */
61
+ .am-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
62
+ .am-actions + .am-actions { margin-top: 6px; }
63
+ .am-actions.is-end { justify-content: flex-end; }
64
+ .am-inline { display: inline-flex; align-items: center; gap: 6px; min-width: 0; flex: 1; }
65
+
66
+ /* ===== 按钮(config-button 设计语言:primary / danger / ghost / small / disabled) ===== */
67
+ .am-btn {
68
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;
69
+ height: 26px; padding: 0 10px;
70
+ font-family: inherit; font-size: 12px; line-height: 1; letter-spacing: 0;
71
+ border: 1px solid var(--border, #e0e0e0); border-radius: 5px;
72
+ background: transparent; color: var(--text-muted, #515c6b);
73
+ cursor: pointer; white-space: nowrap;
74
+ transition: background-color .14s ease, border-color .14s ease, color .14s ease;
75
+ }
76
+ .am-btn:not(:disabled):hover { background: var(--bg-hover, #eeeeee); color: var(--text, #1a1a1a); }
77
+ .am-btn:focus-visible { outline: 2px solid var(--accent, #245bce); outline-offset: 2px; }
78
+ .am-btn:disabled { opacity: .5; cursor: default; }
79
+ .am-btn.is-primary {
80
+ border-color: var(--accent, #245bce); background: var(--accent, #245bce);
81
+ color: var(--accent-contrast, #fff); font-weight: 600;
82
+ }
83
+ .am-btn.is-primary:not(:disabled):hover { border-color: var(--accent-hover, #1d4ed8); background: var(--accent-hover, #1d4ed8); color: var(--accent-contrast, #fff); }
84
+ .am-btn.is-danger { border-color: color-mix(in srgb, var(--danger, #ef4444) 35%, transparent); background: color-mix(in srgb, var(--danger, #ef4444) 6%, transparent); color: var(--danger, #ef4444); }
85
+ .am-btn.is-danger:not(:disabled):hover { border-color: color-mix(in srgb, var(--danger, #ef4444) 50%, transparent); background: color-mix(in srgb, var(--danger, #ef4444) 12%, transparent); }
86
+ .am-btn.is-ghost { border-color: transparent; background: transparent; }
87
+ .am-btn.is-sm { height: 22px; padding: 0 8px; font-size: 11px; }
88
+
89
+ /* ===== 输入框 ===== */
90
+ .am-input {
91
+ flex: 1; min-width: 0; height: 26px; padding: 0 8px;
92
+ font-family: inherit; font-size: 12px;
93
+ border: 1px solid var(--border, #e0e0e0); border-radius: 5px;
94
+ background: var(--bg, #fff); color: inherit;
95
+ }
96
+ .am-input:focus-visible { outline: none; border-color: var(--accent, #245bce); box-shadow: 0 0 0 2px rgba(36, 91, 206, .18); }
97
+ .am-input::placeholder { color: var(--text-dim, #5e6673); opacity: .85; }
98
+
99
+ /* ===== 账号档卡片 ===== */
100
+ .am-accounts {
101
+ margin-top: 8px; padding: 10px 12px; display: grid; gap: 8px;
102
+ background: var(--bg-subtle, rgba(0, 0, 0, .03));
103
+ border: 1px solid var(--border, #e0e0e0); border-radius: 8px;
104
+ }
105
+ .am-accounts-title { display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 600; }
106
+ .am-hint { font-size: 11px; line-height: 17px; color: var(--text-muted, #515c6b); }
107
+ .am-save-row { display: flex; gap: 6px; }
108
+ .am-acc-list { display: grid; gap: 4px; }
109
+ .am-acc-item {
110
+ display: flex; align-items: center; gap: 8px;
111
+ padding: 5px 8px; border-radius: 6px; border: 1px solid transparent;
112
+ }
113
+ .am-acc-item:hover { background: var(--bg-hover, #eeeeee); }
114
+ .am-acc-item.is-current { border-color: rgba(22, 163, 74, .35); background: rgba(22, 163, 74, .06); }
115
+ .am-acc-label { font-size: 12px; font-weight: 600; white-space: nowrap; }
116
+ .am-acc-label.is-auto { font-weight: 500; color: var(--text-dim, #5e6673); }
117
+ .am-acc-chip {
118
+ font-size: 10px; line-height: 16px; padding: 0 6px; border-radius: 999px;
119
+ border: 1px solid var(--border, #e0e0e0); color: var(--text-muted, #515c6b); white-space: nowrap;
120
+ }
121
+ .am-acc-chip.is-current { color: #16a34a; border-color: rgba(22, 163, 74, .4); }
122
+ .am-acc-meta {
123
+ flex: 1; min-width: 0; font-size: 11px; color: var(--text-muted, #515c6b);
124
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
125
+ }
126
+ .am-acc-actions { display: flex; gap: 4px; flex-shrink: 0; }
127
+ .am-empty { font-size: 12px; color: var(--text-dim, #5e6673); padding: 2px 0; }
128
+
129
+ /* ===== 子面板(codebuddy API Key 表单) ===== */
130
+ .am-subpanel {
131
+ margin-top: 8px; padding: 10px 12px; display: grid; gap: 6px;
132
+ background: var(--bg-subtle, rgba(0, 0, 0, .03));
133
+ border: 1px solid var(--border, #e0e0e0); border-radius: 8px;
134
+ }
135
+
136
+ /* ===== URL / TUI 状态行 ===== */
137
+ .am-url-line { margin-top: 6px; display: flex; gap: 6px; align-items: center; }
138
+ .am-url { font-size: 12px; word-break: break-all; color: var(--accent, #245bce); }
139
+ .am-tui-line { margin-top: 6px; font-size: 12px; color: var(--text-muted, #515c6b); }
140
+ .am-tui-line a { color: var(--accent, #245bce); margin-left: 6px; }
141
+
142
+ /* ===== 页脚说明 ===== */
143
+ .am-foot {
144
+ margin-top: 10px; padding-top: 8px; border-top: 1px dashed var(--border, #e0e0e0);
145
+ font-size: 11px; line-height: 16px; color: var(--text-dim, #5e6673);
146
+ }
147
+ /* ===== 命名弹窗(保存账号档) ===== */
148
+ .am-modal-mask {
149
+ position: fixed; inset: 0; z-index: 10000;
150
+ background: rgba(0, 0, 0, .35);
151
+ display: flex; align-items: center; justify-content: center;
152
+ }
153
+ .am-modal {
154
+ width: 360px; max-width: 92vw; display: grid; gap: 8px;
155
+ padding: 14px; border-radius: 10px;
156
+ background: var(--bg, #fff); color: var(--text, #1a1a1a);
157
+ border: 1px solid var(--border, #e0e0e0);
158
+ box-shadow: 0 16px 44px rgba(0, 0, 0, .32);
159
+ font-size: 13px;
160
+ }
161
+ `;
162
+
163
+ /** 幂等注入样式(<style id> 防重复;多次 register / 多副本加载安全)。 */
164
+ export function ensureStyles() {
165
+ if (typeof document === "undefined") return;
166
+ const ID = "aiti-agent-manager-styles";
167
+ if (document.getElementById(ID)) return;
168
+ const el = document.createElement("style");
169
+ el.id = ID;
170
+ el.textContent = STYLES;
171
+ document.head.appendChild(el);
172
+ }