/profile: hot-swap Claude Code accounts and check their usage without leaving the session

Tiếng Việt · English
Một Claude Code, nhiều tài khoản, không ai phải thoát session.
Vì cái cảnh "You've reached your usage limit" lúc 2 giờ sáng, khi code đang chạy dở, không nên xảy ra với ai.
Tính năng · Cài đặt · Bắt đầu nhanh · Web Dashboard · Bảng lệnh · Session song song · Có gì mới · Xử lý sự cố · Bên trong có gì · Đa ngôn ngữ · Phát triển & Test
Bạn có tài khoản công ty, tài khoản cá nhân, tài khoản "dự phòng", và một tài khoản nữa mà chính bạn cũng không nhớ lập ra để làm gì. Mỗi lần đổi là một lần /logout, /login, mở trình duyệt, chờ redirect, và quên mất mình đang nghĩ gì.
claude-swap biến mỗi tài khoản thành một profile. Đổi bằng một lệnh, ngay trong session đang chạy. Ngữ cảnh còn nguyên, cuộc hội thoại còn nguyên, chỉ có tài khoản là khác.
Plugin chạy bằng chính Node.js mà Claude Code đã mang theo: không cần Python, không npm install, đúng 0 dependency. node_modules của dự án này nặng đúng 0 byte, và chúng tôi tự hào về điều đó.
| Nhóm | Nó làm gì cho bạn | |
|---|---|---|
| 🌐 Web Dashboard | /profile web mở một trang điều khiển trên trình duyệt: bấm một cái là đổi tài khoản, kéo thanh trượt để chỉnh cấu hình, có cả trang hướng dẫn. Dành cho những ngày không muốn gõ lệnh. | |
| 💾 Quản lý Profile | Tạo, lưu, đổi, xóa: /profile new, save, delete. Bộ tứ cơ bản. | |
| ✏️ Đổi tên & hoàn tác | /profile rename cũ mới đổi tên mà alias, liên kết, lịch sử đi theo. /profile undo quay về profile trước khi lỡ tay đổi nhầm. | |
| 🔌 Giữ nguyên MCP | Đăng nhập của các MCP server thuộc về máy, không thuộc tài khoản: đổi profile xong không phải đăng nhập lại Linear, Notion, Vercel... | |
| 📟 Status line chi tiết | Trên khung nhập luôn có một dải màu với profile, thanh 5h/7d, giờ reset và cảnh báo sắp cạn (/profile statusline để tắt/bật). | |
| 🎨 Output có màu | Lỗi đỏ, thành công xanh, bảng list thẳng cột kèm giờ reset 5h và 7d. Đọc một cái là biết. | |
| 🔤 Alias | Lười gõ work-company-production-2? Đặt w rồi /profile w. | |
| 🎛️ Picker tương tác | /profile pick cho chọn bằng phím ↑ ↓, dành cho người không nhớ nổi tên profile của mình. | |
| ⚖️ Cân bằng tải | Chia đều công việc cho các tài khoản theo least-used (ai còn nhiều quota thì làm) hoặc round-robin (lần lượt từng người). Không tài khoản nào phải gánh team. | |
| 🔔 Webhook | Báo qua Telegram, Discord, Slack hoặc webhook bất kỳ khi chạm ngưỡng hay đổi tài khoản. Điện thoại rung là biết quota sắp hết. | |
| 💰 Ngân sách | Đặt trần chi tiêu hàng tháng cho từng profile (/profile budget). Ví tiền sẽ cảm ơn bạn. | |
| 🛡️ Che email & chia sẻ an toàn | Email hiện thành us***@domain.com khi bạn share màn hình, và xuất cấu hình không kèm token (/profile mask, /profile share). | |
| ⌨️ Tab completion | Sinh script gợi ý lệnh cho Bash, Zsh, Fish (/profile completion). Gõ nửa chữ rồi bấm Tab. | |
| 🚀 Session song song | /profile run <tên> chạy thêm một Claude Code tách biệt với tài khoản khác. Hai Claude, hai tài khoản, không ai giẫm chân ai. Vẫn dùng chung skill, agent, plugin, settings và memory của bạn. | |
| 🔑 Setup-token & API key | Tạo profile thẳng từ token, không cần trình duyệt (/profile add-token), đọc được cả từ stdin để token không nằm trong lịch sử shell. | |
| 🚫 Cho nghỉ phép | /profile disable <tên> tạm loại một profile khỏi auto-switch mà không cần xóa. | |
| 🌿 Theo nhánh Git | Nhánh work-* dùng tài khoản công ty, feat/* dùng tài khoản dev, tự động. Chẳng còn cảnh lỡ tay dùng tài khoản công ty cho side project. | |
| 📁 Theo thư mục | Mở dự án nào thì tự bật đúng profile của dự án đó (file .claude-profile). | |
| 📈 Dự báo | Đo tốc độ tiêu thụ %/giờ và đoán khi nào cạn (/profile forecast). Cái gì cũng tính được, trừ deadline. | |
| ⏱️ Cooldown & tự quay về | Đếm ngược tới lúc quota 5 giờ reset, rồi tự đưa bạn về profile chính khi tài khoản đó hồi sức. | |
| 🤖 Tự đổi tài khoản | Chạm ngưỡng % hoặc dính rate limit thì tự nhảy sang tài khoản còn nhiều quota nhất hoặc reset sớm nhất. Bạn chỉ việc code tiếp. | |
| 🚨 Bảo vệ hạn mức 7 ngày | Không nhảy vào tài khoản đã dùng gần hết quota tuần (mặc định 85%). | |
| 🧠 Model affinity | Opus chạy tài khoản này, Sonnet chạy tài khoản kia (/profile affinity). | |
| 🩺 Doctor & Cleanup | Khám token hết hạn, đăng nhập MCP hết hạn, profile trùng tài khoản, file hỏng (/profile doctor, /profile cleanup). Thầy thuốc cho credentials. | |
| ☁️ Sync mã hóa | Đẩy và kéo bản sao lưu mã hóa AES-256 giữa các máy (/profile sync push / pull). | |
| 💻 Shell prompt & Tmux | Hiện profile đang dùng kèm % usage trên Starship, Zsh, Bash, Tmux, chạy dưới 5ms. | |
| ⏳ Mượn tạm | Mượn một profile trong 30m hay 1h rồi tự trả. Như mượn sạc của đồng nghiệp, nhưng lần này có người nhắc trả. | |
| 📊 JSON | --json cho list, current, disabled, để script và CI đọc được. | |
| 🌐 Song ngữ | Tiếng Việt hoặc tiếng Anh, `/profile lang [vi\ | en]`. |
| ⚡ Không tốn token | Mọi lệnh /profile chạy local qua plugin hook, không gửi gì cho model và không tốn lượt nào. Chạy ngay cả khi Claude đang bận trả lời, khỏi chờ. |
Gõ ngay trong Claude Code:
/plugin install profile-swap --marketplace thangvofastboy/claude-swap
(Claude hỏi có thêm marketplace không thì bấm y, rồi chọn phạm vi cài đặt.)
Muốn thử thẳng từ source mà chưa cài:
claude --plugin-dir /path/to/claude-swap
Đã cài rồi và muốn bản mới nhất: /profile upgrade. Plugin tự nạp lại (/reload-plugins), không cần thoát session.
Bốn bước, chưa kịp nguội ly cà phê:
claude → /login), rồi lưu lại: ``text /profile new work ``/login sang tài khoản thứ hai, lưu tiếp: ``text /profile new personal ``text /profile list # danh sách kèm thanh usage % /profile web # hoặc mở dashboard ``text /profile work ``Vậy là xong. Không còn phải nhớ mật khẩu nào là của tài khoản nào.
Cho những ngày mắt cần thứ gì đó đẹp hơn terminal:
/profile web # mở dashboard tại http://127.0.0.1:3737
/profile web --port 8080 # đổi cổng
/profile web stop # tắt dashboard đang chạy ngầm
/profile đều có form riêng: alias, tag, gắn thư mục và nhánh Git, model affinity, mượn tạm, ngân sách, webhook, sao lưu / đồng bộ mã hóa, snippet cho shell… Điền rồi bấm ▶, kết quả hiện ngay bên dưới. Mật khẩu sao lưu đi qua stdin, không nằm trên dòng lệnh.Dashboard chỉ lắng nghe trên 127.0.0.1, từ chối request lạ, và mỗi lần khởi động lại tạo một token bí mật mới. Token nằm sau dấu # trong link mà /profile web in ra, nên chỉ trình duyệt của bạn biết. Hàng xóm cùng Wi-Fi hay user khác trên cùng máy đều không đổi tài khoản giùm bạn được. Lỡ đóng tab thì chạy lại /profile web để lấy link.
/profilePhần này nghiêm túc hơn một chút, vì gõ sai lệnh thì không vui.
| Lệnh | Mô tả | |
|---|---|---|
/profile | Tổng quan (profile đang dùng, thanh quota 5h/7d, mọi cài đặt bật/tắt) rồi bảng hướng dẫn đầy đủ. Lạc đường thì gõ cái này | |
/profile list [--json] | Điểm danh cả đội: bảng thẳng cột gồm 🟢/⚪, email, thanh quota 5h/7d, giờ reset và nhãn 🏷️ | |
/profile current [--json] | Câu hỏi triết học "mình là ai?", trả lời bằng tên profile đang dùng | |
| `/profile <tên\ | alias>` | Đổi sang profile hoặc alias <tên>. Claude còn không biết mình vừa đổi chủ |
/profile pick | Chọn bằng phím ↑ ↓, cho ai không nhớ nổi tên profile của chính mình | |
/profile alias <tên> <p> | Đặt biệt danh (vd: /profile alias w work). Gõ một chữ thay vì cả câu | |
/profile unalias <tên> | Xóa biệt danh. Profile gốc vẫn bình an vô sự | |
/profile aliases | Danh bạ biệt danh | |
/profile new <tên> [--force] | Chụp ảnh tài khoản đang đăng nhập rồi cất thành profile mới | |
/profile save <tên> [--force] | Ghi tài khoản đang đăng nhập vào profile, rất hợp sau khi vừa /login lại | |
/profile rename <cũ> <mới> | Đổi tên profile. Alias, liên kết dự án/nhánh, lịch sử, ngân sách đều đi theo, không bỏ rơi ai | |
/profile delete <tên> | Chia tay dứt khoát: xóa profile và dọn đồ đạc liên quan. Không có thùng rác | |
/profile folder | Mở thư mục chứa profile. Ngó thì được, đừng sửa tay | |
| `/profile lang [vi\ | en]` | Xem hoặc đổi ngôn ngữ. Song ngữ, khỏi cần phiên dịch |
/profile version | Đang chạy bản nào |
| Lệnh | Mô tả | |||
|---|---|---|---|---|
/profile web [--port <p>] | Mở Web Dashboard, cho những ngày lười gõ lệnh | |||
/profile web stop | Cho dashboard đi ngủ | |||
| `/profile balance [on\ | off]` | Bật / tắt cân bằng tải. Khi bật, auto-switch chọn profile kế tiếp theo mode (thay cho auto order) | ||
| `/profile balance mode <least-used\ | round-robin>` | Chọn kiểu chia việc: ai còn nhiều quota nhất làm trước, hay lần lượt từng người | ||
| `/profile balance pool <tag\ | all>` | Chỉ chia việc trong nhóm có tag | ||
/profile balance next | Chuyền bóng ngay cho profile kế tiếp theo thuật toán | |||
/profile webhook [status] | Kênh báo nào đang bật. Ngoài báo đổi profile, webhook còn nhận cảnh báo khi tốc độ dùng 7 ngày sẽ làm cạn trước lúc reset và khi một profile hồi quota (mỗi chu kỳ báo một lần) | |||
| `/profile webhook set <telegram\ | discord\ | slack\ | generic> <url>` | Nối dây báo tin về Telegram, Discord, Slack hoặc một URL bất kỳ |
/profile webhook unset <type> | Tắt tiếng một kênh báo | |||
/profile webhook test | Bắn một tin thử cho chắc đường dây thông suốt | |||
/profile budget [status] | Xem trần chi tiêu hàng tháng | |||
/profile budget set <tên> <số_tiền> | Đặt trần chi tiêu cho profile. Ví tiền sẽ cảm ơn bạn | |||
/profile budget unset <tên> | Gỡ trần chi tiêu. Sống thoáng nhưng tự chịu trách nhiệm | |||
| `/profile mask [on\ | off]` | Che email khi share màn hình (us***@domain.com) | ||
/profile share [file.json] | Xuất cấu hình cho đồng đội, không kèm chìa khóa nhà (token) | |||
| `/profile completion [bash\ | zsh\ | fish]` | Gõ nửa chữ, bấm Tab, phần còn lại để shell lo |
| Lệnh | Mô tả | |
|---|---|---|
/profile run <tên> [-- cmd] | Mở thêm một Claude Code chạy tài khoản khác, song song mà không giẫm chân nhau. Dùng chung skill, agent, plugin, settings, memory | |
/profile add-token <tok> [tên] | Tạo profile thẳng từ setup-token hoặc API key, không cần trình duyệt | |
| `echo $TOK \ | node swap.js add-token - [tên]` | Đưa token qua stdin để nó không nằm lại trong lịch sử shell |
/profile upgrade | Kéo bản mới nhất về và tự nạp lại, khỏi khởi động lại Claude Code | |
/profile <tên> current | Chỉ phiên này: không đổi gì, trả lệnh run <tên> để mở session cô lập; các session khác giữ nguyên (/profile <tên> vẫn đổi tất cả) | |
| `/profile settings set update.auto on\ | off` | Tự cập nhật plugin khi mở Claude, 6 giờ một lần (mặc định bật) |
/profile disable <tên> | Cho profile nghỉ phép: auto-switch sẽ không gọi nó dậy | |
/profile enable <tên> | Hết phép, quay lại vòng xoay auto-switch | |
/profile disabled [--json] | Ai đang nghỉ phép |
| Lệnh | Mô tả | ||
|---|---|---|---|
/profile usage | Quota 5h, 7d và từng model (Opus, Sonnet, Haiku…), soi tới từng phần trăm | ||
/profile auto | Auto-switch đang cấu hình ra sao | ||
/profile auto on / off | Bật / tắt tự đổi tài khoản khi vượt ngưỡng. Bật lên rồi cứ code tiếp | ||
/profile auto threshold <%> | Bao nhiêu % thì đổi (mặc định 95%) | ||
/profile auto order <ds> | Xếp hàng xem ai lên thay trước (vd: work,personal,backup) | ||
| `/profile auto pool <tag\ | all>` | Chỉ đổi qua lại trong nhóm có tag | |
| `/profile auto safeguard [on\ | off\ | <%>]` | Không nhảy vào tài khoản đã gần cạn quota tuần (mặc định 85%) |
| `/profile auto step [<%>\ | off]` | Hạn mức mỗi lượt: mỗi tài khoản dùng tối đa N% quota 5h (tính từ lúc được chuyển sang), rồi tự chuyển sang tài khoản kế tiếp theo auto order (hoặc theo tên), xoay vòng liên tục. Mỗi lần chuyển đều có thông báo trong Claude (và desktop nếu bật notify). Ví dụ: /profile auto step 5. | |
| `/profile auto return [on\ | off]` | Tự quay về profile chính khi nó hồi sức | |
/profile auto primary <tên> | Chọn "nhà" để auto-return quay về | ||
/profile auto check | Khỏi chờ prompt kế tiếp: kiểm tra ngay, chạm ngưỡng là đổi. Mỗi prompt chỉ hỏi quota của profile đang dùng, chỉ hỏi cả đội khi cần chọn người thay | ||
/profile forecast | Bói xem bao giờ cạn quota, dựa trên tốc độ tiêu thụ thật. Tính từ lúc đo gần nhất; số liệu cũ quá 20 phút sẽ được đánh dấu "chỉ tham khảo" | ||
/profile cooldown | Đếm ngược tới lúc quota 5h hồi sức | ||
/profile doctor | Khám tổng quát: token OAuth, đăng nhập MCP, file cấu hình, kết nối | ||
/profile settings | Bảng gom mọi cài đặt (auto-switch, ngưỡng, profile chính, cân bằng tải, status line, thông báo, che email, tự sửa token, ngôn ngữ). Trong Claude Code nó mở thành bảng sửa trực tiếp: bấm để bật/tắt hoặc đổi lựa chọn, gõ số vào ô, rồi 💾 Lưu (phím s); Esc để đóng. Từ terminal: /profile settings set <key> <giá trị>, --json để đọc bằng máy | ||
/profile schedule <HH:MM-HH:MM> <tên> | Đổi profile theo lịch, vd 09:00-18:00 work, cả khung qua đêm như 22:00-06:00. Chỉ đổi một lần khi tới giờ (bạn tự đổi trong khung giờ thì vẫn giữ). Chạy cả khi tắt auto-switch. /profile schedule xem lịch, `/profile unschedule <số\ | all>` xóa | |
| `/profile repair auto on\ | off` | Tự chạy repair ở nền 6 giờ một lần khi có profile hết hạn token | |
/profile help <từ khóa> | Chỉ hiện các lệnh có từ khóa đó (vẫn bấm được để đưa xuống ô nhập) | ||
/profile repair [tên] | Làm mới token hết hạn của profile khác mà không cần chuyển sang: chạy một request rất nhỏ (claude -p, model haiku) trong session cô lập rồi lưu token mới vào profile. Không kèm tên thì sửa mọi profile cần sửa; profile không còn token thì in hướng dẫn đăng nhập lại | ||
/profile cleanup [--force] | Tìm profile trùng email/UUID hoặc token hỏng. Thêm --force là dọn thật |
| Lệnh | Mô tả |
|---|---|
/profile bind [tên] | Gắn profile cho thư mục (file .claude-profile). Mở dự án là tự đúng tài khoản |
/profile unbind | Gỡ gắn: thư mục này được tự do |
/profile bind-branch <pat> [tên] | Gắn profile theo mẫu nhánh Git (vd: feat/*, hotfix-*). Checkout là đổi luôn |
/profile unbind-branch [pat] | Cởi trói cho nhánh |
/profile branch-bindings | Nhánh nào đi với tài khoản nào |
/profile tag <tên> <tag> | Dán nhãn phân nhóm (vd: /profile tag work corp) |
/profile untag <tên> <tag> | Bóc nhãn ra. Profile không giận đâu |
/profile tags | Ai thuộc nhóm nào |
/profile affinity <model> <tên> | Cho model một tài khoản riêng (vd: opus ăn quota như tằm ăn dâu) |
/profile affinity apply <model> | Nhảy sang tài khoản đã gán cho model đó |
/profile unaffinity <model> | Model này về làm việc chung với mọi người |
/profile affinities | Model nào đi với tài khoản nào |
| Lệnh | Mô tả | |||
|---|---|---|---|---|
/profile temp <tên> [tg] | Mượn tạm profile có hẹn giờ trả (vd: 30m, 1h). Hết giờ tự trả | |||
/profile untemp | Trả sớm cho giữ uy tín, về profile gốc ngay | |||
| `/profile statusline [on\ | off\ | band\ | line]` | Status line chi tiết: profile, thanh 5h/7d, giờ reset, cảnh báo sắp cạn. Không kèm tham số thì bật/tắt. band (mặc định) là dải màu trên khung nhập, line là dòng chữ thường ghim dưới. statusline ansi in dòng có màu để nhúng vào status line riêng |
/profile prompt [shell] | Snippet để starship, zsh, bash, tmux, powershell biết bạn đang là ai | |||
| `/profile notify [on\ | off]` | Bật / tắt thông báo desktop khi đổi profile (mặc định tắt cho đỡ phiền) | ||
/profile undo | Lỡ tay đổi nhầm? Quay về profile trước đó trong một nốt nhạc (gọi lần nữa thì đi lại) | |||
/profile history [n] | Nhật ký đổi tài khoản: ai, khi nào, vì sao (mặc định 10 dòng) | |||
/profile stats [--project] | Đổi tay bao nhiêu lần, tự động bao nhiêu lần, theo dự án bao nhiêu lần; kèm usage 7 ngày theo từng dự án (ước tính từ % 5h tăng thêm khi đang làm ở thư mục đó). --project chỉ in phần usage | |||
/profile sync setup <path> | Chọn chỗ đặt két đồng bộ (thư mục Dropbox, ổ mạng…) | |||
/profile sync push | Gửi két mã hóa lên chỗ đồng bộ | |||
/profile sync pull | Mang két về máy này rồi mở ra | |||
/profile export <file> | Nhét hết profile vào két AES-256-GCM. Quên mật khẩu là chịu | |||
/profile import-enc <file> | Mở két, mang profile về. Đúng mật khẩu mới mở được | |||
/profile import <thư_mục> [--force] | Dọn nhà cho profile thô từ thư mục khác về đây |
🔑 Mật khẩu sao lưu không bao giờ được ghi xuống đĩa. Đưa nó vào bằng
--password-stdin(an toàn nhất:echo "$PW" | node swap.js export f.enc --password-stdin), biến môi trườngCLAUDE_SWAP_PASSWORD, hoặc--password <pw>(cách này để lại mật khẩu trong lịch sử shell, nên chỉ dùng khi bạn tin cái lịch sử đó).
/profile list: PROFILE EMAIL 5H 7D RESET 5H RESET 7D
───────────────────────────────────────────────────────────────────────────────────────────
🟢 work work@company.com [███░░░░░] 32% [█████░░░] 64% 2h10m 3d4h
⚪ personal user@gmail.com [███████░] 85%🔥 [███░░░░░] 40% 48m 1d9h 🏷️ side
⚪ dev dev@example.com — — — — (disabled)
Cột reset cho biết còn bao lâu nữa thì cửa sổ quota đó hồi sức, để biết nên chờ hay nên đổi.
Màu thanh usage, như đèn giao thông:
< 50%: thoải mái< 80%: bắt đầu để ý< 95%: liệu mà tiết kiệm, từ 80% có thêm 🔥≥ 95%: auto-switch đang xỏ giày/profile statusline):Bật mặc định, cập nhật mỗi khi bạn gửi prompt, thanh và phần trăm đổi màu theo mức tải (cùng bảng màu với /profile list). Có hai kiểu hiển thị:
/profile statusline band (mặc định): một dải nhiều màu vẽ ngay trên khung nhập./profile statusline line: một dòng chữ thường ghim dưới khung nhập, không có màu. Claude Code bỏ ký tự điều khiển màu của dòng ghim nên chỗ đó không thể tô màu./profile statusline không kèm tham số thì bật/tắt, on/off cũng được.
● work │ 5h [███░░░░░] 32% ⏳2h10m │ 7d [█████░░░] 64% ⏳3d4h │ ⚠ 5h ~12p
Muốn nhúng vào status line riêng của bạn (cấu hình statusLine trong settings.json): node <plugin>/swap.js statusline ansi in đúng dòng có màu đó.
⏳ là thời gian còn lại tới lúc reset. ⚠ 5h ~12p chỉ hiện khi tốc độ tiêu thụ cho thấy profile này sẽ chạm ngưỡng auto-switch trong khoảng 30 phút. Gõ /profile statusline để tắt/bật.
Status line tự làm mới mỗi phút, kể cả khi bạn không gõ gì (quota được tải lại 5 phút một lần, kể cả khi đã tắt auto-switch). ⚠ lỗi mạng / ⚠ cũ 2h nghĩa là số liệu đang hiện không còn mới. Khi auto-switch tắt mà profile đang dùng vượt 80% (5h hoặc 7d), dải hiện → <profile> 7d 31% là profile nên chuyển sang, kèm một thông báo nhỏ. Mỗi lần auto-switch tự đổi profile cũng có thông báo. Bên cạnh gợi ý có nút ⇄ <profile> (bấm chuột, hoặc ctrl+x tab để vào dải rồi phím s) để chuyển ngay. Khi 7d vượt 80%, dải hiện 7d ≈0.7%/h: phần quota còn lại chia đều cho số giờ tới lúc reset, hoặc ⚠ 7d 1.2%/h > 0.7%/h khi tốc độ 3 giờ gần đây sẽ làm cạn trước lúc reset (/profile forecast có cùng thông tin cho mọi profile). Một profile khác vừa reset sau khi gần cạn sẽ có thông báo ✅ <profile> đã hồi quota. /profile usage vẽ lịch sử 24 giờ (theo giờ) và 7 ngày (theo ngày). Gõ /profile không kèm gì: mỗi lệnh trong bảng hướng dẫn bấm được, bấm vào là lệnh đó xuống ô nhập để bạn điền nốt rồi gửi. /profile stats --json xuất số liệu cho công cụ khác. Khi hạn mức 7 ngày riêng của một model (vd Fable) vượt 80%, dải hiện Fable 7d 85% → minhvong 13%. Terminal hẹp thì dải bỏ thanh và giờ reset, chỉ giữ phần trăm. Webhook còn nhận báo cáo tuần vào sáng thứ Hai.
Các lệnh dành cho người đọc (swap, undo, history, stats, forecast, tag, alias...) được tô màu theo ý nghĩa: lỗi đỏ, thành công xanh, tên profile vàng, tiêu đề cyan. Lệnh mà hook hay shell phải đọc (current, statusline, auto check, --json) luôn là chữ thường. Muốn tắt màu: --no-color hoặc biến môi trường NO_COLOR=1.
node swap.js list
node swap.js swap work
node swap.js usage
node swap.js balance on
node swap.js web
Hai tài khoản, hai cửa sổ, cùng lúc. Không giành token của nhau:
# Mở một Claude Code riêng cho profile work
node swap.js run work
# Hoặc chạy lệnh tùy ý trong môi trường của profile work
node swap.js run work -- claude --model sonnet
Mỗi session sống ở ~/.config/claude-cli-profiles/.sessions/<tên> và dùng CLAUDE_CONFIG_DIR riêng. Skill, agent, plugin, settings, CLAUDE.md và memory được nối (symlink) từ ~/.claude sang, nên session phụ vẫn "đủ đồ nghề"; chỉ có đăng nhập là riêng theo profile. Khi session kết thúc, token đã được refresh sẽ được đồng bộ ngược về profile. Nếu bên trong session có ai đó đăng nhập sang tài khoản khác, plugin sẽ không chép nhầm tài khoản đó vào profile.
Mỗi profile là một file ~/.config/claude-cli-profiles/<tên>.json (quyền 0600, thư mục 0700, người ngoài không đọc được), gồm:
~/.claude.json: oauthAccount, primaryApiKey, customApiKeyResponses.~/.claude/.credentials.json, hoặc Keychain trên macOS.Skill, agent, plugin, settings và memory nằm trong ~/.claude/ nên không thuộc về profile nào: đổi tài khoản không làm mất cái gì trong số đó.
Khi bạn đổi profile:
~/.claude.json giữ nguyên. Như thay chìa khóa xe, không ai tháo luôn cả cái xe..bak. Mất điện giữa chừng cũng không mất profile.mcpOAuth, tức đăng nhập của các MCP server. Phần này thuộc về máy chứ không thuộc tài khoản, nên khi đổi profile plugin giữ nguyên bản đang dùng thay vì trả về bản chụhooks/register.tsx 989 lines1import type { EngineInterface, Register } from 'claude-code'
2
3const SUBCOMMANDS = new Set([
4 'help',
5 'list',
6 'codex',
7 'agy',
8 'opencode',
9 'dedupe',
10 'note',
11 'restore',
12 'export-config',
13 'import-config',
14 'verify',
15 'current',
16 'usage',
17 'folder',
18 'save',
19 'swap',
20 'rename',
21 'delete',
22 'new',
23 'auto',
24 'bind',
25 'unbind',
26 'notify',
27 'tag',
28 'untag',
29 'tags',
30 'export',
31 'import-enc',
32 'history',
33 'undo',
34 'stats',
35 'cooldown',
36 'doctor',
37 'statusline',
38 'prompt',
39 'temp',
40 'untemp',
41 'alias',
42 'unalias',
43 'aliases',
44 'bind-branch',
45 'unbind-branch',
46 'branch-bindings',
47 'forecast',
48 'pick',
49 'sync',
50 'affinity',
51 'unaffinity',
52 'affinities',
53 'cleanup',
54 'lang',
55 'language',
56 'disable',
57 'enable',
58 'disabled',
59 'add-token',
60 'run',
61 'version',
62 'upgrade',
63 'autoupdate',
64 'web',
65 'dashboard',
66 'balance',
67 'webhook',
68 'budget',
69 'cost',
70 'mask',
71 'share',
72 'completion',
73 'repair',
74 'schedule',
75 'unschedule',
76 'settings',
77 'overview',
78 'panel',
79])
80const USAGE =
81 'Dùng: /profile | /profile list | /profile <tên|alias> | /profile pick | /profile web | /profile balance | /profile webhook | /profile lang [vi|en] | /profile run <tên> | /profile add-token <tok> | /profile disable <tên> | /profile auto | /profile sync | /profile upgrade'
82
83// "" → help, "list" → list, "work" → swap work, "save work" → save work, "import ~/a b" → import ~/a b, "auto ..." → auto ...
84function toArgv(args: string): string[] | undefined {
85 const words = args.trim().split(/\s+/).filter(Boolean)
86 if (words.length === 0 || words[0] === '--help' || words[0] === '-h') return ['help']
87 if (words.length === 1 && words[0] === 'statusline') return ['statusline', 'toggle'] // bare CLI `statusline` prints the shell-prompt string
88 if (words[0] === 'version' || words[0] === '--version' || words[0] === '-v') return ['version']
89 if (words[0] === 'web' || words[0] === 'dashboard') {
90 if (words[1] === 'stop') return words
91 if (!words.includes('--daemon')) return [words[0], '--daemon', ...words.slice(1)]
92 }
93 if (words[0] === 'import') {
94 const path = words.slice(1).filter(w => w !== '--force').join(' ')
95 if (!path) return undefined
96 return ['import', path, ...(words.includes('--force') ? ['--force'] : [])]
97 }
98 if (SUBCOMMANDS.has(words[0])) return words
99 // `<name> current`: this session only. A live session shares the config files with the others, so it is answered
100 // with the terminal command for an isolated one (`run <name>`) instead of a swap
101 if (words.length === 2 && words[1] === 'current') return ['run', words[0]]
102 if (words.length === 1) return ['swap', words[0]]
103 if (words.length === 2 && words[1] === '--project') return ['swap', words[0], '--project']
104 return undefined
105}
106
107// `$.env.get` wants a literal name at its call site (so a module's variables can be listed): pass the call itself
108const safely = async (read: () => Promise<string | undefined>) => {
109 try {
110 return await read()
111 } catch {
112 return undefined
113 }
114}
115
116// Where node may live when the host was started from a GUI (Desktop app from Finder/Dock) and PATH lacks the
117// shell's additions; the login shell last, since it reads the user's profile (nvm, asdf…). The hooks module has no
118// `process`: the environment comes through `$.env`.
119async function nodeCandidates($: EngineInterface, script: string, argv: string[]): Promise<string[][]> {
120 const home = (await safely(() => $.env.get('HOME'))) || (await safely(() => $.env.get('USERPROFILE'))) || ''
121 const windows = (await safely(() => $.env.get('OS'))) === 'Windows_NT'
122 const direct = [
123 'node',
124 'nodejs',
125 '/opt/homebrew/bin/node',
126 '/usr/local/bin/node',
127 '/usr/bin/node',
128 `${home}/.volta/bin/node`,
129 'C:\\Program Files\\nodejs\\node.exe',
130 ].map(node => [node, script, ...argv])
131 const shell = (await safely(() => $.env.get('SHELL'))) || '/bin/sh'
132 return windows ? direct : [...direct, [shell, '-lc', 'exec node "$@"', 'node', script, ...argv]]
133}
134
135// the first launcher that worked, tried first from then on (a reload starts over)
136let launcher = -1
137
138// the plugin is the repo itself: swap.js sits next to .claude-plugin/ and hooks/
139// commands that run `claude` themselves (repair, upgrade) or talk to a remote: past the 30 s default
140const SLOW = new Set(['repair', 'upgrade', 'autoupdate', 'sync', 'run'])
141
142async function runSwap($: EngineInterface, argv: string[], stdin?: string) {
143 // a swap must say which session asks, or swap.js counts this very session as "another one" on the profile
144 if (argv[0] === 'swap' && !argv.includes('--session')) {
145 const sid = await $.session.id().catch(() => '')
146 if (sid) argv = [...argv, '--session', sid]
147 }
148 const script = `${$.plugin.root}/swap.js`
149 const init = { timeoutMs: SLOW.has(argv[0]) ? 600_000 : 30_000, ...(stdin === undefined ? {} : { stdin }) }
150 // the common case, `node` on PATH, costs no `$.env` lookups
151 // a rejection that took the whole timeout is the command running too long, not a missing node: running it again
152 // under another launcher would repeat its work. A quick one means this launcher could not start.
153 const start = Date.now()
154 const timedOut = () => Date.now() - start >= init.timeoutMs - 1000
155 if (launcher <= 0) {
156 try {
157 const ran = await $.process.run(['node', script, ...argv], init)
158 launcher = 0
159 return ran
160 } catch (error) {
161 // a launcher that has worked once stays: rerunning a swap or add-token elsewhere would repeat its work
162 if (launcher >= 0 || timedOut()) throw error
163 }
164 }
165 const all = await nodeCandidates($, script, argv)
166 const order = launcher > 0 ? [launcher, ...all.keys()].filter((i, n, a) => a.indexOf(i) === n) : [...all.keys()].slice(1)
167 let failure: unknown
168 for (const i of order) {
169 try {
170 const ran = await $.process.run(all[i], init)
171 launcher = i
172 return ran
173 } catch (error) {
174 if (launcher >= 0 || timedOut()) throw error
175 failure = error
176 }
177 }
178 throw new Error(
179 `Không tìm thấy Node.js để chạy claude-swap (${String(failure)}). Cài Node.js 18+ rồi mở lại app; ` +
180 'nếu đã cài qua nvm/Homebrew mà app Desktop vẫn không thấy, mở Claude từ terminal hoặc thêm node vào PATH hệ thống.'
181 )
182}
183
184// What `statusLineData` in swap.js returns. Drawn as a coloured band above the prompt: the host's own status line
185// takes plain text only (one colour, prefixed with the plugin name).
186type StatusData = {
187 profile: string
188 rateLimited: boolean
189 windows: { name: string; pct: number; left: string }[]
190 warn: string
191 stale?: string // '⚠ lỗi mạng', '⚠ cũ 2h': the numbers are not current
192 suggest?: string // '→ minhvong 7d 31%': auto-switch is off and this profile is running out
193 next?: string
194 pace?: string // '7d ≈0.7%/h': the 7-day quota left per hour until its reset
195 models?: string // 'Fable 7d 85% → minhvong 13%': a model's own 7-day limit running out
196 fable?: { pct: number; left: string } | null // the Fable 7-day limit, shown even when it is low
197 recovered?: string[] // other profiles whose full window has reset since
198 mode?: 'line' | 'band'
199 text?: string
200}
201
202// The data swap.js last produced. `auto check` reprints it on every prompt, so only a change redraws.
203// A reload loses it; the next prompt brings it back.
204let status: StatusData | null = null
205let lastRaw: string | undefined
206
207function parseStatus(raw: string): StatusData | null {
208 try {
209 const data = JSON.parse(raw)
210 return data && typeof data.profile === 'string' && Array.isArray(data.windows) ? data : null
211 } catch {
212 return null
213 }
214}
215
216// `line` mode pins plain text under the prompt (the host drops the ESC byte of a pinned line, so no colour there);
217// `band` (default) draws the coloured band above it. Whichever is not in use is cleared:
218// a plugin's pinned text survives a reload, so the very first call must clear a line an older version left behind.
219let pinned = true
220
221// What the session itself is running, read off its own model requests: not in swap.js's data.
222const live = { model: '', effort: '', advisor: 0 }
223const shortModel = (id: string) => id.replace(/^claude-/, '').replace(/-\d{8}$/, '')
224
225// the suggestion last toasted, so one profile running out toasts once, not on every refresh
226let lastSuggest = ''
227let lastRecovered: string[] = []
228
229function showStatus($: EngineInterface, raw: string) {
230 lastRaw = raw
231 status = parseStatus(raw)
232 const suggest = status?.suggest || ''
233 if (suggest && status?.next !== lastSuggest) $.ui.toast(`⚠ ${status!.profile} sắp hết quota ${suggest}: /profile ${status!.next}`)
234 lastSuggest = suggest ? status!.next || '' : ''
235 const recovered = status?.recovered || []
236 for (const name of recovered) if (!lastRecovered.includes(name)) $.ui.toast(`✅ ${name} đã hồi quota: /profile ${name}`)
237 lastRecovered = recovered
238 const text = status && status.mode === 'line' ? status.text || undefined : undefined
239 if (text !== undefined || pinned) $.ui.status(text)
240 pinned = text !== undefined
241 $.ui.invalidate('ui.render')
242}
243
244async function refreshStatus($: EngineInterface) {
245 const { stdout } = await runSwap($, ['statusline', 'json'])
246 const raw = stdout.trim()
247 if (raw !== lastRaw) showStatus($, raw)
248}
249
250// Between prompts nothing else redraws: tick once a minute so the countdown moves and the quota (refetched by
251// `statusline json` once USAGE_TTL has passed) stays current while the session sits idle. Started once per load.
252const TICK_MS = 60_000
253let ticking = false
254
255// `auto.confirm`: asks before an automatic swap. A "no" (or a dismissed dialog) keeps that same swap from asking again
256// for CONFIRM_SNOOZE_MS, or the dialog would come back on every prompt.
257const CONFIRM_SNOOZE_MS = 15 * 60_000
258const declined = new Map<string, number>()
259const CONFIRM_YES = 'Đổi ngay'
260
261async function confirmSwap($: EngineInterface, raw: string): Promise<boolean> {
262 let p: { from?: string; to?: string; why?: string }
263 try {
264 p = JSON.parse(raw)
265 } catch {
266 return false
267 }
268 const key = `${p.from}>${p.to}`
269 if (Date.now() - (declined.get(key) ?? 0) < CONFIRM_SNOOZE_MS) return false
270 const question = `Tự động đổi profile '${p.from}' sang '${p.to}'${p.why ? ` (${p.why})` : ''}?`
271 const answer = await $.ui.ask(question, { header: 'claude-swap', options: [CONFIRM_YES, 'Để sau'] }).catch(() => '')
272 if (answer === CONFIRM_YES) return true
273 declined.set(key, Date.now())
274 return false
275}
276
277// the band's "switch" button: the same swap `/profile <name>` does, then the band redraws for the new profile
278async function swapTo($: EngineInterface, name: string) {
279 const ran = await runSwap($, ['swap', name, '--no-color']) // a toast is plain text: `swap` output is coloured
280 $.ui.toast(`${ran.stdout}${ran.stderr}`.trim().split('\n')[0] || name)
281 await refreshStatus($)
282}
283
284// `/profile settings` editor: the rows swap.js reported, the edits not saved yet, and the last save's outcome
285type Setting = { key: string; type: 'bool' | 'number' | 'choice' | 'text'; choices?: string[]; value: boolean | number | string; desc: string }
286let settings: Setting[] = []
287let draft: Record<string, Setting['value']> = {}
288let settingsNote = ''
289
290// the rest of the pane (`panel` in swap.js): every profile, every feature's stored items (each with the argv that removes it),
291// the help's commands, and which tab shows
292type Window = { name: string; pct: number; left: string }
293type PanelProfile = { name: string; email: string; active: boolean; disabled: boolean; tags: string[]; windows: Window[] }
294type Feature = { key: string; title: string; items: { text: string; remove?: string[] }[] }
295type Panel = Omit<Overview, 'settings'> & { profileList: PanelProfile[]; features: Feature[] }
296const TABS = [['overview', '🔀 Tổng quan'], ['profiles', '👤 Profile'], ['settings', '🧰 Cài đặt'], ['features', '🧩 Tính năng'], ['commands', '📜 Lệnh']] as const
297type Tab = (typeof TABS)[number][0]
298let panel: Panel | null = null
299let commands: HelpRow[] = []
300let tab: Tab = 'settings'
301
302// the features tab's add forms: free text in an Input, a profile or a choice in a Select. The values stay here until the add runs.
303// a secret goes on stdin, never argv. `bind` binds the session's folder: swap.js runs there (the cwd $.process.run defaults to)
304type Vals = Record<string, string>
305type FormField = { name: string; label: string; kind: 'text' | 'profile' | 'choice'; choices?: string[]; def?: string; placeholder?: string }
306type Form = { key: string; fields: FormField[]; argv: (v: Vals) => string[]; stdin?: (v: Vals) => string }
307const FORMS: Form[] = [
308 { key: 'alias', fields: [{ name: 'name', label: 'tên', kind: 'text', placeholder: 'pm' }, { name: 'profile', label: 'profile', kind: 'profile' }], argv: v => ['alias', v.name, v.profile] },
309 { key: 'tag', fields: [{ name: 'profile', label: 'profile', kind: 'profile' }, { name: 'tag', label: 'tag', kind: 'text', placeholder: 'work' }], argv: v => ['tag', v.profile, v.tag] },
310 { key: 'bind', fields: [{ name: 'profile', label: 'profile', kind: 'profile' }], argv: v => ['bind', v.profile] },
311 { key: 'bind-branch', fields: [{ name: 'pattern', label: 'pattern', kind: 'text', placeholder: 'feat/*' }, { name: 'profile', label: 'profile', kind: 'profile' }], argv: v => ['bind-branch', v.pattern, v.profile] },
312 { key: 'affinity', fields: [{ name: 'model', label: 'model', kind: 'text', placeholder: 'opus' }, { name: 'profile', label: 'profile', kind: 'profile' }], argv: v => ['affinity', v.model, v.profile] },
313 { key: 'schedule', fields: [{ name: 'range', label: 'khung giờ', kind: 'text', placeholder: '09:00-18:00' }, { name: 'profile', label: 'profile', kind: 'profile' }], argv: v => ['schedule', v.range, v.profile] },
314 { key: 'temp', fields: [{ name: 'profile', label: 'profile', kind: 'profile' }, { name: 'duration', label: 'thời gian', kind: 'text', def: '1h', placeholder: '30m' }], argv: v => ['temp', v.profile, v.duration] },
315 { key: 'budget', fields: [{ name: 'profile', label: 'profile', kind: 'profile' }, { name: 'amount', label: 'hạn mức', kind: 'text', placeholder: '50' }], argv: v => ['budget', 'set', v.profile, v.amount] },
316 { key: 'webhook', fields: [{ name: 'type', label: 'loại', kind: 'choice', choices: ['telegram', 'discord', 'slack', 'generic'] }, { name: 'url', label: 'URL', kind: 'text', placeholder: 'https://…' }], argv: v => ['webhook', 'set', v.type, '--url-stdin'], stdin: v => v.url },
317]
318let formFields: Record<string, string> = {}
319let busy = false // one pane action at a time: a double press must not add a schedule twice or run two repairs
320
321
322// `keepDraft`: a refresh while the pane is open leaves the edits in progress alone, including ones typed during the await
323async function loadSettings($: EngineInterface, keepDraft = false) {
324 const [{ stdout }, help] = await Promise.all([runSwap($, ['panel']), commands.length ? null : runSwap($, ['help', '/profile']).catch(() => null)]) // a keyword on every command line: all of them, without the overview
325 const data = JSON.parse(stdout.trim())
326 settings = data.settings
327 panel = data
328 if (help) commands = helpRows(help.stdout)
329 if (!keepDraft) draft = {}
330}
331
332// a button, or an add form, on the pane: run that subcommand, say how it went, redraw from fresh data. Resolves true when it succeeded.
333async function panelAction($: EngineInterface, argv: string[], stdin?: string): Promise<boolean> {
334 if (busy) {
335 $.ui.toast('⏳ Đang chạy lệnh trước, đợi chút…')
336 return false
337 }
338 busy = true
339 try {
340 const ran = await runSwap($, [...argv, '--no-color'], stdin)
341 const out = `${ran.stdout}${ran.stderr}`.trim()
342 $.ui.toast(out.split('\n')[0] || 'OK')
343 await reloadPanel($)
344 await refreshStatus($).catch(() => undefined)
345 return ran.exitCode === 0
346 } finally {
347 busy = false
348 }
349}
350
351// fresh pane data once the profile or a setting may have changed (an auto-swap, a /profile command); edits in progress stay
352async function reloadPanel($: EngineInterface) {
353 if (!panel) return
354 await loadSettings($, true).catch(() => undefined)
355 $.ui.invalidate('ui.render')
356}
357
358function setFormField($: EngineInterface, key: string, value: string) {
359 formFields = { ...formFields, [key]: value }
360 $.ui.invalidate('ui.render')
361}
362
363const profileNames = (): string[] => panel?.profileList.map(r => r.name) ?? []
364
365// what a form shows: what was typed or picked, else the default (the active profile, the first choice, the field's `def`)
366function formValues(f: Form): Vals {
367 const active = panel?.profileList.find(r => r.active)?.name ?? profileNames()[0] ?? ''
368 return Object.fromEntries(
369 f.fields.map(x => {
370 const fallback = x.kind === 'profile' ? active : x.kind === 'choice' ? (x.choices?.[0] ?? '') : (x.def ?? '')
371 return [x.name, formFields[`${f.key}.${x.name}`] ?? fallback]
372 })
373 )
374}
375
376// the add button: every field must be filled; the form clears only when the subcommand succeeded
377function submitForm($: EngineInterface, f: Form) {
378 const v = Object.fromEntries(Object.entries(formValues(f)).map(([k, x]) => [k, String(x).trim()]))
379 const missing = f.fields.find(x => !v[x.name])
380 if (missing) {
381 $.ui.toast(`⚠ Điền ${missing.label}`)
382 return
383 }
384 void panelAction($, f.argv(v), f.stdin?.(v))
385 .then(ok => {
386 if (!ok) return
387 formFields = Object.fromEntries(Object.entries(formFields).filter(([k]) => !k.startsWith(`${f.key}.`)))
388 $.ui.invalidate('ui.render')
389 })
390 .catch(err => $.ui.toast(`⚠ ${String(err)}`))
391}
392
393function edit($: EngineInterface, key: string, value: Setting['value']) {
394 draft = { ...draft, [key]: value }
395 settingsNote = ''
396 $.ui.invalidate('ui.render')
397}
398
399// every changed row goes through `settings set`, which validates it; a refused one stays in the draft with its error
400async function saveSettings($: EngineInterface) {
401 if (busy) {
402 $.ui.toast('⏳ Đang chạy lệnh trước, đợi chút…')
403 return
404 }
405 busy = true
406 try {
407 const errors: string[] = []
408 const changed = Object.entries(draft)
409 for (const [key, value] of changed) {
410 const text = value === true ? 'on' : value === false ? 'off' : String(value)
411 const ran = await runSwap($, ['settings', 'set', key, text, '--no-color'])
412 if (ran.exitCode !== 0) errors.push(`${key}: ${`${ran.stderr}${ran.stdout}`.trim().replace(/^❌ Lỗi: /, '')}`)
413 }
414 const failed = new Set(errors.map(e => e.split(':')[0]))
415 // a refresh failing after the sets went through must not read as a failed save
416 await loadSettings($, true).catch(() => undefined)
417 // saved rows leave the draft; refused ones, and edits made while saving, stay
418 draft = Object.fromEntries(Object.entries(draft).filter(([k, v]) => failed.has(k) || !changed.some(([ck, cv]) => ck === k && cv === v)))
419 await refreshStatus($).catch(() => undefined)
420 const saved = changed.length - errors.length
421 if (!errors.length) {
422 $.ui.toast(saved ? `✅ Đã lưu ${saved} cài đặt` : 'Không có gì thay đổi')
423 $.ui.invalidate('ui.render') // the pane stays open: the other tabs are still in use
424 return
425 }
426 settingsNote = `⚠ Đã lưu ${saved}/${changed.length}. ${errors.join(' · ')}`
427 $.ui.invalidate('ui.render')
428 } finally {
429 busy = false
430 }
431}
432
433// commands that only read: they cannot change what the band shows (not `list`/`usage`: they refresh the quota cache), so they skip the extra `statusline json` process
434const READ_ONLY = new Set([
435 'help', 'overview', 'panel', 'current', 'folder', 'history', 'stats', 'cooldown', 'forecast', 'doctor', 'tags',
436 'aliases', 'disabled', 'branch-bindings', 'affinities', 'prompt', 'completion', 'version', 'share', 'export', 'web', 'dashboard',
437])
438
439// Same palette as the `/profile list` table (pctCode in swap.js): green < 50, yellow < 80, orange < 95, red above.
440// Raw colours rather than theme keys, so the band and the table look alike on any theme.
441const loadColor = (pct: number) => (pct >= 95 ? 'red' : pct >= 80 ? '#ff8700' : pct >= 50 ? 'yellow' : 'green')
442// setting names and descriptions (overview and settings pane): Claude's orange; `SETTING_SGR` in swap.js is its 256-colour match
443const SETTING_COLOR = '#D97757'
444const BAR_WIDTH = 8
445const METER = 16 // cells in a pane's quota bar
446
447// `/profile` help, row by row: a command (yellow in swap.js's formatHelpReport) with its description, or a title
448const SGR = /\x1b\[[0-9;]*m/g
449const HELP_ARGS = new Set(['', 'help', '--help', '-h'])
450type HelpRow = { cmd?: string; desc?: string; title?: string }
451
452// what bare `/profile` draws above the help (`overview --json`, overviewData in swap.js); the latest one, so an older help
453// in the scrollback shows the current values too
454type Overview = {
455 profile: string
456 email: string
457 profiles: number
458 disabled: number
459 rateLimited: boolean
460 stale: string
461 windows: { name: string; pct: number; left: string }[]
462 settings: (Setting & { icon: string })[]
463}
464let overview: Overview | null = null
465
466function helpRows(text: string): HelpRow[] {
467 return text.split('\n').map(line => {
468 const m = line.match(/^\s*\x1b\[1;33m(\/profile[^\x1b]*)\x1b\[0m\s*(.*)$/)
469 return m ? { cmd: m[1].trim(), desc: m[2].replace(SGR, '') } : { title: line.replace(SGR, '') }
470 })
471}
472
473// what a click puts in the prompt box: the command up to its first placeholder ("/profile alias <tên> <p>" → "/profile alias ")
474export function helpDraft(cmd: string): string {
475 const words: string[] = []
476 for (const w of cmd.split(/\s+/)) {
477 if (/[<[|]/.test(w)) break
478 words.push(w)
479 }
480 return `${words.join(' ')} `
481}
482
483export const register: Register = on => {
484 on('session.start', async ($, e, next) => {
485 await $.command.register({
486 name: 'profile',
487 description: 'Đổi tài khoản Claude ngay trong session: /profile [tên | usage | auto | cooldown | doctor | temp | bind | history]',
488 immediate: true, // runs at once even while a turn is streaming, instead of queueing behind it
489 })
490
491 try {
492 const targetDir = e.cwd || '.'
493 // both at once: each is a node start-up, ~100 ms on Windows
494 const [boundRan, curRan] = await Promise.all([runSwap($, ['bind', 'get', targetDir]), runSwap($, ['current'])])
495 const boundOut = boundRan.stdout.trim()
496 const match = boundOut.match(/(?:đang liên kết với profile|bound to profile|profile):\s*([^\s()]+)/i)
497 if (match && match[1]) {
498 const boundProfile = match[1]
499 const curProfile = curRan.stdout.trim()
500 if (boundProfile !== curProfile) {
501 await runSwap($, ['swap', boundProfile, '--project'])
502 }
503 }
504 } catch {}
505
506 // network call, never awaited: it must not hold the session start. A new version is only on disk until reloaded.
507 void runSwap($, ['autoupdate'])
508 .then(ran => {
509 if (ran.exitCode !== 0 || !ran.stdout.trim()) return
510 $.ui.toast('⬆️ claude-swap đã cập nhật, đang nạp lại plugin...')
511 $.clock.after(500, () => void $.command.run({ command: 'reload-plugins' }).catch(() => undefined))
512 })
513 .catch(() => undefined)
514
515 void refreshStatus($).catch(() => undefined)
516 if (!ticking) {
517 ticking = true
518 $.clock.every(TICK_MS, () => void refreshStatus($).catch(() => undefined))
519 }
520
521 return next(e)
522 })
523
524 on('prompt.submit', async ($, e, next) => {
525 try {
526 const sid = await $.session.id().catch(() => '')
527 const check = async (...extra: string[]) => {
528 const ran = await runSwap($, ['auto', 'check', ...extra, ...(sid ? ['--session', sid] : [])])
529 return `${ran.stdout}${ran.stderr}`.trim()
530 }
531 let out = await check()
532 // `auto.confirm` on: the check found a swap and waits. The prompt waits too, so it goes out on the account chosen.
533 const pending = out.match(/^\[auto-confirm\] (.*)$/m)
534 if (pending && (await confirmSwap($, pending[1]))) out = await check('--yes')
535 // the auto-swap notice would otherwise show nowhere: the hook only reads the [status] line
536 const swapped = out.match(/^\[auto-swap\] (🔀 .*)$/m)
537 if (swapped) {
538 $.ui.toast(swapped[1])
539 void reloadPanel($)
540 }
541 const presence = out.match(/^\[presence\] (.*)$/m)
542 if (presence) $.ui.toast(presence[1])
543 const line = out.match(/^\[status\] ?(.*)$/m)
544 if (line && line[1].trim() !== lastRaw) showStatus($, line[1].trim())
545 } catch {}
546
547 return next(e)
548 })
549
550 // the main loop's model, effort and advisor calls, for the band; a subagent's request is not the session's
551 on('turn.step', async function* ($, e, next) {
552 if (e.agentId === undefined) {
553 const effort = e.effort === undefined ? '' : String(e.effort)
554 if (live.model !== e.model || live.effort !== effort) {
555 live.model = e.model
556 live.effort = effort
557 $.ui.invalidate('ui.render')
558 }
559 }
560 const r = yield* next(e)
561 if (e.agentId === undefined) {
562 const used = (r.serverToolUses ?? []).filter(u => u.name === 'advisor').length
563 if (used) {
564 live.advisor += used
565 $.ui.invalidate('ui.render')
566 }
567 }
568 return r
569 })
570
571 // coloured status band: ● profile │ 5h [███░░░░░] 34% ⏳2h10m │ 7d [██████░░] 73% ⏳3d4h │ ⚠ 5h ~12p
572 on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
573 if (!status || status.mode === 'line' || e.props.hasSurvey) return next(e)
574 const { Box, Text, Button } = $.ui.resolve(e)
575 const suggested = status.next
576 // a narrow terminal drops the bars and countdowns: "● work │ 5h 34% │ 7d 73%"
577 const width = status.text ? status.text.length : status.profile.length + 4 + status.windows.length * 28 // ≈ one full window
578 const compact = typeof e.props.bodyColumns === 'number' && e.props.bodyColumns < width + 8
579 const sep = <Text color="gray"> │ </Text>
580 return (
581 <Box>
582 <Text color="green" bold>● {status.profile}</Text>
583 {status.rateLimited ? <Text color="yellow" bold> ⏳ 429</Text> : null}
584 {status.windows.map(w => {
585 const filled = Math.round((w.pct / 100) * BAR_WIDTH)
586 const color = loadColor(w.pct)
587 return (
588 <Box key={w.name}>
589 {sep}
590 <Text color="cyan" bold>{w.name} </Text>
591 {compact ? null : <Text color="gray">[</Text>}
592 {compact ? null : <Text color={color} bold>{'█'.repeat(filled)}</Text>}
593 {compact ? null : <Text color="gray">{'░'.repeat(BAR_WIDTH - filled)}] </Text>}
594 <Text color={color} bold>{String(w.pct)}%</Text>
595 {w.pct >= 80 && !compact ? <Text> 🔥</Text> : null}
596 {w.left && !compact ? <Text color="cyan"> ⏳{w.left}</Text> : null}
597 </Box>
598 )
599 })}
600 {live.model ? (
601 <Box>
602 {sep}
603 <Text color="magenta" bold>🤖 {shortModel(live.model)}</Text>
604 {live.effort && !compact ? <Text color="magenta"> · effort {live.effort}</Text> : null}
605 {live.advisor > 0 && !compact ? <Text color="magenta"> · advisor ×{live.advisor}</Text> : null}
606 </Box>
607 ) : null}
608 {status.fable && !status.models?.includes('Fable') ? (
609 <Box>
610 {sep}
611 <Text color="cyan" bold>Fable 7d </Text>
612 <Text color={loadColor(status.fable.pct)} bold>{String(status.fable.pct)}%</Text>
613 {status.fable.left && !compact ? <Text color="cyan"> ⏳{status.fable.left}</Text> : null}
614 </Box>
615 ) : null}
616 {[status.warn, status.pace, status.models, status.stale, status.suggest].filter(Boolean).map(note => (
617 <Box key={note}>{sep}<Text color="yellow" bold>{note}</Text></Box>
618 ))}
619 {suggested ? (
620 <Box>
621 <Text> </Text>
622 <Button key="swap-next" hotkey="s" plain onPress={() => void swapTo($, suggested).catch(() => undefined)}>
623 {`⇄ ${suggested}`}
624 </Button>
625 </Box>
626 ) : null}
627 </Box>
628 )
629 })
630
631 // `/profile` help: every command is a button that puts it in the prompt box, ready to complete and send
632 on('ui.render', { component: 'CommandOutput' }, ($, e, next) => {
633 const { command, args, text, isErrored } = e.props
634 if (command !== 'profile' || isErrored || !HELP_ARGS.has(args.trim().split(/\s+/)[0])) return next(e)
635 let rows = helpRows(text)
636 if (!rows.some(r => r.cmd)) return next(e) // not the help after all (a format change, no match): draw it as text
637 const { Box, Text, Button } = $.ui.resolve(e)
638 // bare `/profile`: swap.js printed the overview as text above the help; draw it from the data instead
639 const ov = HELP_ARGS.has(args.trim()) ? overview : null
640 const start = rows.findIndex(r => r.title?.includes('claude-swap —'))
641 if (ov && start > 0) rows = rows.slice(start)
642 const width = ov ? Math.max(...ov.settings.map(r => r.key.length), 8) : 0
643 return (
644 <Box flexDirection="column">
645 {ov ? (
646 <Box flexDirection="column">
647 <Text color="cyan" bold>🔀 claude-swap · Tổng quan</Text>
648 {ov.profile ? (
649 <Box>
650 <Text> 👤 </Text>
651 <Text color="green" bold>{ov.profile}</Text>
652 {ov.email ? <Text color="gray">{` ${ov.email}`}</Text> : null}
653 <Text>{` 📦 ${ov.profiles} profile`}</Text>
654 {ov.disabled ? <Text color="red">{` · 🚫 ${ov.disabled} tắt`}</Text> : null}
655 </Box>
656 ) : (
657 <Text color="yellow" bold> ⚠ Chưa có profile nào active. Tạo bằng: /profile new {'<tên>'}</Text>
658 )}
659 {ov.windows.map(w => {
660 const filled = Math.round((w.pct / 100) * 16)
661 const color = loadColor(w.pct)
662 return (
663 <Box key={`ov:${w.name}`}>
664 <Text>{w.name === '5h' ? ' ⌛ ' : ' 📅 '}</Text>
665 <Text color="cyan" bold>{w.name === '5h' ? '5 giờ ' : '7 ngày '}</Text>
666 <Text color="gray">[</Text>
667 <Text color={color} bold>{'█'.repeat(filled)}</Text>
668 <Text color="gray">{'░'.repeat(16 - filled)}] </Text>
669 <Text color={color} bold>{`${String(w.pct).padStart(3)}%`}</Text>
670 {w.pct >= 80 ? <Text> 🔥</Text> : null}
671 {w.left ? <Text color="cyan">{` ⏳ ${w.left}`}</Text> : null}
672 </Box>
673 )
674 })}
675 {ov.rateLimited ? <Text color="yellow" bold> ⏳ máy chủ usage đang bận (429), quota sẽ hiện lại sau</Text> : null}
676 {ov.stale ? <Text color="yellow" bold>{` ${ov.stale}`}</Text> : null}
677 <Text> </Text>
678 <Box>
679 <Text color="cyan" bold>🧰 Cài đặt </Text>
680 <Button key="overview-settings" plain onPress={() => void $.prompt.fill({ text: '/profile settings' }).catch(() => undefined)}>
681 <Text color="gray">(sửa: /profile settings)</Text>
682 </Button>
683 </Box>
684 {ov.settings.map(r => {
685 const v = r.value
686 const off = v === false || v === '' || v === 'off'
687 return (
688 <Box key={`ov:${r.key}`}>
689 <Text>{` ${r.icon} `}</Text>
690 <Text color={SETTING_COLOR} bold>{`${r.key.padEnd(width)} `}</Text>
691 <Text color={v === true ? 'green' : off ? 'gray' : 'cyan'} bold={!off}>
692 {(v === true ? '● bật' : v === false ? '○ tắt' : v === '' ? '—' : String(v)).padEnd(14)}
693 </Text>
694 <Text color={SETTING_COLOR}>{r.desc}</Text>
695 </Box>
696 )
697 })}
698 <Text> </Text>
699 </Box>
700 ) : null}
701 {rows.map((r, i) =>
702 r.cmd ? (
703 <Box key={`row${i}`}>
704 <Text> </Text>
705 <Button key={`help:${r.cmd}`} plain onPress={() => void $.prompt.fill({ text: helpDraft(r.cmd!) }).catch(() => undefined)}>
706 <Text color="yellow" bold>{r.cmd.padEnd(28)}</Text>
707 </Button>
708 <Text> {r.desc}</Text>
709 </Box>
710 ) : (
711 <Text key={`row${i}`} color="cyan" bold>{r.title || ' '}</Text>
712 )
713 )}
714 <Text dimColor>💡 Bấm vào một lệnh để đưa nó xuống ô nhập.</Text>
715 </Box>
716 )
717 })
718
719 // `/profile settings`: one pane, a row of tabs, everything a click away. Each item sits on a card (rounded border);
720 // a row lights up under the pointer (`hover` scope, one per row). Keys: 1-5 change tab, s saves.
721 on('ui.render', { component: 'Pane', requestId: 'settings' }, ($, e) => {
722 const { Box, Text, Button, Input, Select } = $.ui.resolve(e)
723 const run = (argv: string[]) => void panelAction($, argv).catch(err => $.ui.toast(`⚠ ${String(err)}`))
724 const fill = (text: string) => void $.prompt.fill({ text }).catch(() => undefined)
725 const goTo = (id: Tab) => () => {
726 tab = id
727 $.ui.invalidate('ui.render')
728 }
729 const p = panel
730
731 // one quota window: its name, a bar coloured by load, the percentage, the time to reset
732 const meter = (w: Window) => {
733 const filled = Math.round((w.pct / 100) * METER)
734 const color = loadColor(w.pct)
735 return (
736 <Box key={`w:${w.name}`} marginRight={2}>
737 <Text color="cyan" bold>{`${w.name} `}</Text>
738 <Text color="gray">[</Text>
739 <Text color={color}>{'█'.repeat(filled)}</Text>
740 <Text color="gray">{'░'.repeat(METER - filled)}]</Text>
741 <Text color={color} bold>{` ${String(w.pct).padStart(3)}%`}</Text>
742 {w.left ? <Text color="cyan">{` ⏳${w.left}`}</Text> : null}
743 </Box>
744 )
745 }
746
747 const tabs = (
748 <Box>
749 {TABS.map(([id, label], i) => (
750 <Box key={`tab:${id}`} marginRight={1}>
751 <Button key={`tab:${id}`} variant={tab === id ? 'primary' : 'secondary'} hotkey={String(i + 1)} onPress={goTo(id)}>
752 {label}
753 </Button>
754 </Box>
755 ))}
756 </Box>
757 )
758
759 const overviewBody = !p?.profile ? (
760 <Text color="yellow" bold>⚠ Chưa có profile nào active. Tạo bằng: /profile new {'<tên>'}</Text>
761 ) : (
762 <Box flexDirection="column">
763 <Box marginBottom={1}>
764 <Text color="green" bold>{`👤 ${p.profile}`}</Text>
765 {p.email ? <Text color="gray">{` ${p.email}`}</Text> : null}
766 </Box>
767 {p.windows.length ? p.windows.map(meter) : <Text dimColor>chưa có số liệu quota (mở /profile usage để tải)</Text>}
768 {p.rateLimited ? <Text color="yellow" bold>⏳ máy chủ usage đang bận (429), quota sẽ hiện lại sau</Text> : null}
769 {p.stale ? <Text color="yellow">{p.stale}</Text> : null}
770 <Box marginTop={1}>
771 <Text color="gray">{`📦 ${p.profiles} profile`}</Text>
772 {p.disabled ? <Text color="red">{` 🚫 ${p.disabled} tắt`}</Text> : null}
773 <Text color="gray">{` 🧰 ${settings.filter(r => r.type === 'bool' && r.value === true).length} tính năng bật`}</Text>
774 </Box>
775 </Box>
776 )
777
778 const profilesBody = (
779 <Box flexDirection="column">
780 {(p?.profileList || []).map(r => (
781 <Box key={`p:${r.name}`} hover={{ scope: `pf:${r.name}` }} flexDirection="column" borderStyle="round" borderColor={r.active ? 'green' : 'gray'} paddingX={1} marginBottom={1}>
782 <Box>
783 <Text color={r.active ? 'green' : 'white'} bold>{`${r.active ? '● ' : '○ '}${r.name}`}</Text>
784 <Text color="gray">{` ${r.email}`}</Text>
785 {r.tags.map(t => <Text key={`t:${r.name}:${t}`} color="magenta">{` #${t}`}</Text>)}
786 {r.disabled ? <Text color="red" bold>{' 🚫 tắt'}</Text> : null}
787 </Box>
788 {r.windows.length ? <Box>{r.windows.map(meter)}</Box> : <Text dimColor>chưa có số liệu quota</Text>}
789 <Box marginTop={1}>
790 {r.active ? (
791 <Text color="green" bold>✓ đang dùng</Text>
792 ) : (
793 <Button key={`p-swap:${r.name}`} variant="primary" onPress={() => run(['swap', r.name])}>{'⇄ Dùng'}</Button>
794 )}
795 <Text> </Text>
796 <Button key={`p-dis:${r.name}`} onPress={() => run([r.disabled ? 'enable' : 'disable', r.name])}>
797 {r.disabled ? '↺ Bật lại' : '⊘ Tắt'}
798 </Button>
799 <Text> </Text>
800 <Button key={`p-repair:${r.name}`} onPress={() => run(['repair', r.name])}>{'🔧 Repair'}</Button>
801 <Text> </Text>
802 <Button key={`p-del:${r.name}`} onPress={() => fill(`/profile delete ${r.name}`)}>{'🗑 Xóa…'}</Button>
803 </Box>
804 </Box>
805 ))}
806 <Box>
807 <Button key="p-new" variant="primary" onPress={() => fill('/profile new ')}>{'+ Tạo từ login hiện tại'}</Button>
808 <Text> </Text>
809 <Button key="p-token" onPress={() => fill('/profile add-token ')}>{'+ Thêm bằng token'}</Button>
810 </Box>
811 <Text dimColor>{'🗑 Xóa… đưa lệnh xuống ô nhập, bạn gửi đi mới thật sự xóa.'}</Text>
812 </Box>
813 )
814
815 // one add form: its fields in a row, each a text Input or a Select, then the add button
816 const control = (f: Form, x: FormField) => {
817 const key = `${f.key}.${x.name}`
818 const current = formValues(f)[x.name]
819 if (x.kind === 'text') {
820 return (
821 <Input key={`in:${key}`} value={current} placeholder={x.placeholder} onInput={v => setFormField($, key, v)} onSubmit={v => setFormField($, key, v)} />
822 )
823 }
824 const names = x.kind === 'profile' ? profileNames() : (x.choices ?? [])
825 if (!names.length) return <Text color="yellow">chưa có profile</Text>
826 return <Select key={`sel:${key}`} options={names.map(n => ({ value: n }))} value={current} onSelect={v => setFormField($, key, v)} />
827 }
828
829 const featuresBody = (
830 <Box flexDirection="column">
831 {(p?.features || []).map(f => {
832 const form = FORMS.find(x => x.key === f.key)
833 return (
834 <Box key={`f:${f.key}`} flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1} marginBottom={1}>
835 <Text color="cyan" bold>{`${f.title} ${f.items.length ? `(${f.items.length})` : ''}`}</Text>
836 {f.items.length ? f.items.map((it, i) => (
837 <Box key={`fi:${f.key}:${i}`} hover={{ scope: `fi:${f.key}:${i}` }}>
838 <Text>{` ${it.text} `}</Text>
839 {it.remove ? (
840 <Button key={`f-rm:${f.key}:${i}`} onPress={() => run(it.remove!)}>{'✕ Gỡ'}</Button>
841 ) : null}
842 </Box>
843 )) : <Text dimColor>{' chưa có'}</Text>}
844 {form ? (
845 <Box flexWrap="wrap" marginTop={1} alignItems="center">
846 {form.fields.map(x => (
847 <Box key={`ff:${f.key}:${x.name}`} marginRight={2} alignItems="center">
848 <Text color="gray">{`${x.label} `}</Text>
849 {control(form, x)}
850 </Box>
851 ))}
852 <Button key={`add:${f.key}`} variant="primary" onPress={() => submitForm($, form)}>{'+ Thêm'}</Button>
853 </Box>
854 ) : null}
855 </Box>
856 )
857 })}
858 </Box>
859 )
860
861 const settingsBody = (() => {
862 const width = Math.max(...settings.map(r => r.key.length), 8)
863 const shown = (v: Setting['value']) => (v === '' ? '—' : String(v))
864 return (
865 <Box flexDirection="column">
866 {settings.map(r => {
867 const value = r.key in draft ? draft[r.key] : r.value
868 const changed = r.key in draft && draft[r.key] !== r.value
869 const control =
870 r.type === 'bool' ? (
871 <Button key={`set:${r.key}`} onPress={() => edit($, r.key, !value)}>
872 {value ? '● bật' : '○ tắt'}
873 </Button>
874 ) : r.type === 'choice' ? (
875 <Button
876 key={`set:${r.key}`}
877 onPress={() => {
878 const list = r.choices || []
879 edit($, r.key, list[(list.indexOf(String(value)) + 1) % list.length] ?? '')
880 }}
881 >
882 {`⇄ ${shown(value)}`}
883 </Button>
884 ) : (
885 <Input key={`set:${r.key}`} value={String(value)} placeholder="—" onInput={v => edit($, r.key, v)} onSubmit={v => edit($, r.key, v)} />
886 )
887 return (
888 <Box key={`row:${r.key}`} hover={{ scope: `st:${r.key}` }}>
889 <Text color={changed ? 'yellow' : SETTING_COLOR} bold>{`${changed ? '* ' : ' '}${r.key.padEnd(width)} `}</Text>
890 {control}
891 <Text color={SETTING_COLOR}>{` ${r.desc}`}</Text>
892 </Box>
893 )
894 })}
895 {settingsNote ? <Text color="yellow">{settingsNote}</Text> : null}
896 <Box marginTop={1}>
897 <Button key="settings-save" variant="primary" hotkey="s" onPress={() =>
898 void saveSettings($).catch(err => {
899 settingsNote = `⚠ ${String(err)}`
900 $.ui.invalidate('ui.render')
901 })
902 }>
903 {`💾 Lưu${Object.keys(draft).length ? ` (${Object.keys(draft).length})` : ''}`}
904 </Button>
905 <Text> </Text>
906 <Button key="settings-cancel" role="dismiss" onPress={() => void $.ui.close({ id: 'settings' })}>
907 Đóng
908 </Button>
909 </Box>
910 </Box>
911 )
912 })()
913
914 const commandsBody = (
915 <Box flexDirection="column">
916 {commands.map((r, i) =>
917 r.cmd ? (
918 <Box key={`c${i}`} hover={{ scope: `cm:${i}` }}>
919 <Button key={`cmd:${r.cmd}`} plain onPress={() => fill(helpDraft(r.cmd!))}>
920 <Text color="yellow" bold>{r.cmd.padEnd(30)}</Text>
921 </Button>
922 <Text dimColor>{` ${r.desc}`}</Text>
923 </Box>
924 ) : r.title?.trim() ? <Text key={`c${i}`} color="cyan" bold>{r.title}</Text> : null
925 )}
926 <Text dimColor>{'💡 Bấm một lệnh để đưa nó xuống ô nhập.'}</Text>
927 </Box>
928 )
929
930 const body = tab === 'overview' ? overviewBody : tab === 'profiles' ? profilesBody : tab === 'features' ? featuresBody : tab === 'commands' ? commandsBody : settingsBody
931 return (
932 <Box flexDirection="column">
933 <Box>
934 <Text color="cyan" bold>{'🔀 claude-swap'}</Text>
935 {p?.profile ? <Text color="green" bold>{` ● ${p.profile}`}</Text> : null}
936 </Box>
937 <Box marginTop={1}>{tabs}</Box>
938 <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1} marginTop={1}>
939 {body}
940 </Box>
941 <Text dimColor>{'Bấm tab hoặc phím 1–5 · trỏ chuột vào dòng để làm nổi · sửa rồi 💾 Lưu (phím s) · Esc đóng'}</Text>
942 </Box>
943 )
944 })
945
946 on('command.run', { command: 'profile' }, async ($, e) => {
947 const argv = toArgv(e.args)
948 if (!argv) return { text: USAGE }
949 // an interactive `claude` has no terminal here: the hook only collects output
950 if (argv[0] === 'run' && !argv.includes('--')) return { text: `Chạy trong terminal: node "${$.plugin.root}/swap.js" run ${argv[1] || '<tên>'}` }
951
952 // bare `/profile settings` opens the editor; with arguments (`settings set k v`) it runs as any command
953 if (argv[0] === 'settings' && argv.length === 1) {
954 await loadSettings($)
955 settingsNote = ''
956 const opened = await $.ui.open({ id: 'settings', title: 'claude-swap', focus: true, closeOnEscape: true })
957 if (opened.isPlaced) return { text: '⚙️ Đã mở bảng điều khiển: phím 1-5 đổi tab, sửa cài đặt rồi bấm 💾 Lưu (phím s), Esc để đóng.' }
958 await $.ui.close({ id: 'settings' })
959 }
960
961 // bare `/profile`: the overview's data, for the render hook to draw in colour above the help
962 // the token goes on stdin, not argv, where `ps` would show it
963 const token = argv[0] === 'add-token' && argv[1] && !argv[1].startsWith('--') ? argv[1] : undefined
964 const [ran, ov] = await Promise.all([
965 token ? runSwap($, ['add-token', '--token-stdin', ...argv.slice(2)], token) : runSwap($, argv),
966 argv.length === 1 && argv[0] === 'help' ? runSwap($, ['overview', '--json']).catch(() => null) : null,
967 ])
968 if (ov) {
969 try {
970 overview = JSON.parse(ov.stdout.trim())
971 } catch {}
972 }
973 if (!READ_ONLY.has(argv[0]) || ran.exitCode !== 0) {
974 await refreshStatus($).catch(() => undefined)
975 if (argv[0] !== 'settings') await reloadPanel($)
976 }
977 const out = `${ran.stdout}${ran.stderr}`.trim()
978 // the new version is only on disk: have the host re-read plugins once this command has returned
979 if (argv[0] === 'upgrade' && ran.exitCode === 0) {
980 $.clock.after(500, () => void $.command.run({ command: 'reload-plugins' }).catch(() => undefined))
981 return { text: `${out}\n🔄 Đang nạp lại plugin (/reload-plugins)...`.trim() }
982 }
983 // the host draws the first line beside its own prefix, which would push a table's header out of line
984 if (out) return { text: argv[0] === 'list' || argv[0] === 'usage' ? `\n${out}` : out }
985
986 return { text: argv[0] === 'list' ? 'Chưa có profile nào. Tạo bằng: /profile new <tên>' : 'OK' }
987 })
988}
989