agy-family 0.6.0 → 0.6.1

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.
package/README.md CHANGED
@@ -58,13 +58,16 @@ npm i -g agy-family
58
58
  ```
59
59
  - **Open the web board passwordlessly** (60s one-time ticket -> 7-day `HttpOnly` cookie; manager machines auto-unlock Admin Console):
60
60
  ```sh
61
- agy-family open # Open directly in your default browser
61
+ agy-family open # Open active hosted or joined board
62
+ agy-family open <car-name|index> # Open a specific hosted board when managing multiple cars
63
+ agy-family open --joined # Open your joined board explicitly
62
64
  agy-family open --link # Print a 5-minute single-use link for mobile
63
65
  ```
64
- - **Invite members, inspect host, or upgrade anytime**:
66
+ - **Overview all cars, accounts & switch hosts**:
65
67
  ```sh
66
- agy-family invite "Alice" --email "alice@gmail.com" --quota 20 # Prints ready-to-paste join command
67
- agy-family host # Show board URL, Admin Key & member list
68
+ agy-family ls # List all hosted cars, URLs, members, joined board & active account (also `/family ls`)
69
+ agy-family host use <car-name|index> # Switch active hosted board
70
+ agy-family invite "Alice" --email "alice@gmail.com" --quota 20 # Prints ready-to-paste join command (optional `--car <name>`)
68
71
  npm i -g agy-family@latest && agy-family deploy # Idempotent zero-downtime upgrade
69
72
  ```
70
73
  - **Join someone's family board & view dashboard** (works for both Antigravity Desktop IDE & `agy` CLI):
package/README.zh-CN.md CHANGED
@@ -58,13 +58,16 @@ npm i -g agy-family
58
58
  ```
59
59
  - **🔐 零密码打开网页看板**(一次性 60s 票据换取 7 天 `HttpOnly` 会话,主号电脑自动免密解锁「家庭组管理」后台):
60
60
  ```sh
61
- agy-family open # 自动打开浏览器
61
+ agy-family open # 自动打开当前默认看板
62
+ agy-family open <车名或序号> # 多车场景下指定打开某一辆自建车
63
+ agy-family open --joined # 打开当前「我上的车」
62
64
  agy-family open --link # 生成 5 分钟单次有效链接(方便手机临时看)
63
65
  ```
64
- - **🎟️ 车主发车票 / 查状态 / 后续升级**:
66
+ - **📋 一览全部开车 / 上车 / 账号信息 & 多车切换**:
65
67
  ```sh
66
- agy-family invite "成员名" --email "member@gmail.com" --quota 20 # 生成一行上车命令
67
- agy-family host # 查看看板地址与 Admin Key
68
+ agy-family ls # 一条命令列出所有开过的车、网址、主号、成员与当前上的车(对话内也可发 /family ls)
69
+ agy-family host use <车名或序号> # 切换当前默认操作的自建车
70
+ agy-family invite "成员名" --email "member@gmail.com" --quota 20 # 生成一行上车命令(可加 --car <车名>)
68
71
  npm i -g agy-family@latest && agy-family deploy # 一键平滑升级云端看板(保留数据与密钥)
69
72
  ```
70
73
  - **🚌 成员上车 & 查看面板**(桌面 IDE 和 `agy` CLI 通用):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Zero-privacy-leak transparent usage dashboard, /family slash command, and fair-use budget guardrail for Google One / Antigravity family groups.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -59,14 +59,19 @@ import {
59
59
  adminApiRequest,
60
60
  createMemberInvite,
61
61
  deployToCloudflare,
62
+ deriveHostEntryId,
62
63
  hostConfigPath,
64
+ hostsRegistryPath,
63
65
  readHostConfig,
64
- removeHostConfig,
66
+ readHostsRegistry,
67
+ removeHostEntry,
68
+ resolveHostEntry,
65
69
  sanitizeWorkerName,
66
- writeHostConfig,
70
+ setActiveHost,
71
+ upsertHostEntry,
67
72
  } from '../src/host.mjs';
68
73
 
69
- const CLI_VERSION = '0.6.0';
74
+ const CLI_VERSION = '0.6.1';
70
75
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
71
76
  const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
72
77
 
@@ -144,14 +149,17 @@ function printHelp() {
144
149
  console.log(`agy-family v${CLI_VERSION} — Google Family Group Transparent Usage Board & /family Hook CLI
145
150
  One CLI for both joining a family group ("上车") and hosting your own board ("自己开车").
146
151
 
152
+ Overview & Quick Access:
153
+ agy-family ls [--offline] [--json] List all hosted cars, joined car, active Google account, members & daemon status
154
+ agy-family open [car] [--joined] [--link] [--readonly] [--ttl 60]
155
+ Open a board in your browser passwordlessly via a one-time CLI ticket
156
+
147
157
  Join a Family Group (Member):
148
158
  agy-family join <agyfam://join?...> [--no-hook] [--daemon]
149
159
  Join a Google Family Group board & enable /family in IDE + CLI
150
- agy-family open [--link] [--readonly] [--ttl 60]
151
- Open the family board in your browser passwordlessly via a one-time CLI ticket
152
160
  agy-family sync [--dry-run] [--watch] [--full] [--quiet]
153
161
  Sync local Desktop IDE + CLI numeric usage (delta by default)
154
- agy-family status [--period today|7d|cycle|30d]
162
+ agy-family status [--period today|7d|cycle|30d] [--car <name|index>]
155
163
  View your quota progress and family leaderboard
156
164
  agy-family audit Inspect the exact last transmitted JSON payload
157
165
  agy-family pricing [sync] View or sync 3-tier model pricing cache (models.dev / litellm)
@@ -160,14 +168,15 @@ Join a Family Group (Member):
160
168
  agy-family leave Disconnect this device and delete local invite token
161
169
  agy-family uninstall Remove hook, /family skill, OS daemon, and local credentials
162
170
 
163
- Host Your Own Board (Family Manager):
171
+ Host Your Own Board (Family Manager — supports multiple cars):
164
172
  agy-family deploy [--name agy-family] [--title "..."] [--admin-key <key>] [--self] [--member <name>] [--email <gmail>] [--daemon]
165
173
  One-command deploy/upgrade on Cloudflare Workers + D1 (free tier, no git clone)
166
- agy-family master [bind|sync|set|status|unlink] [--email <gmail>] [--daemon]
174
+ agy-family host [show|ls|use <car>|link|unlink [car]]
175
+ List, switch, link, or unlink hosted boards on this machine
176
+ agy-family master [bind|sync|set|status|unlink] [--car <car>] [--email <gmail>] [--daemon]
167
177
  Bind master account & auto-capture live 5h / weekly subscription quota (100% standalone, zero secrets)
168
- agy-family invite <name> [--email <gmail>] [--quota <pct>] [--role member|manager]
178
+ agy-family invite <name> [--car <car>] [--email <gmail>] [--quota <pct>] [--role member|manager]
169
179
  Create a member and print their ready-to-paste one-line join command
170
- agy-family host [show|link|unlink] View or link your hosted board URL, Admin Key, and D1 metadata
171
180
  agy-family serve [--port 8787] [--db path] [--admin-key <key>] [--title "..."]
172
181
  Start a self-hosted Node.js + SQLite board server locally or on a VPS
173
182
 
@@ -621,32 +630,313 @@ async function main() {
621
630
  return;
622
631
  }
623
632
 
633
+ if (cmd === 'ls' || cmd === 'list' || cmd === 'info' || cmd === 'cars') {
634
+ const offline = args.includes('--offline') || args.includes('--no-net');
635
+ const asJson = args.includes('--json');
636
+
637
+ const reg = readHostsRegistry();
638
+ const clientCfg = readJsonSafe(clientConfigPath());
639
+ const localAcct = readLocalActiveEmailHint();
640
+ const mCfg = readMasterConfig();
641
+ const hookSt = inspectAntigravityIntegration();
642
+ const daemonSt = inspectBackgroundDaemon();
643
+ const tapSt = inspectStatusLineTap();
644
+
645
+ const hostInfos = await Promise.all(
646
+ reg.hosts.map(async (h, idx) => {
647
+ const isActive = h.id === reg.active;
648
+ let overview = null;
649
+ let fetchError = null;
650
+ if (!offline && h.url && h.adminKey) {
651
+ try {
652
+ overview = await adminApiRequest({
653
+ url: h.url,
654
+ adminKey: h.adminKey,
655
+ path: '/api/admin/overview',
656
+ timeoutMs: 6_000,
657
+ });
658
+ } catch (err) {
659
+ fetchError = err?.message || 'unreachable';
660
+ }
661
+ }
662
+ const activeMembers = (overview?.members || []).filter((m) => m.active);
663
+ const nowMs = Date.now();
664
+ const onlineWindowMs = 15 * 60 * 1000;
665
+ return {
666
+ index: idx + 1,
667
+ id: h.id,
668
+ name: h.name || h.workerName || h.id,
669
+ active: isActive,
670
+ url: h.url || '',
671
+ provider: h.provider || 'cloudflare',
672
+ workerName: h.workerName || '',
673
+ databaseName: h.databaseName || '',
674
+ boardTitle: overview?.settings?.boardTitle || h.boardTitle || 'Antigravity 家庭组',
675
+ accessMode: overview?.settings?.boardAccessMode || '',
676
+ memberCount: overview ? activeMembers.length : null,
677
+ members: activeMembers.map((m) => {
678
+ const lastSeenAt = Number(m.last_seen_at ?? m.lastSeenAt ?? 0) || 0;
679
+ const isOnline =
680
+ typeof m.online === 'boolean'
681
+ ? m.online
682
+ : Boolean(lastSeenAt && nowMs - lastSeenAt <= onlineWindowMs);
683
+ return {
684
+ id: m.id,
685
+ name: m.name,
686
+ role: m.role || 'member',
687
+ emailHint: m.email_hint || m.emailHint || '',
688
+ online: isOnline,
689
+ lastSeenAt: lastSeenAt || null,
690
+ quotaPct: m.effective_quota_pct ?? m.quotaPct ?? null,
691
+ accountStatus: m.account_status || m.accountStatus || 'unbound',
692
+ };
693
+ }),
694
+ masterSubscriptionQuota: overview?.masterSubscriptionQuota || null,
695
+ fetchError,
696
+ };
697
+ }),
698
+ );
699
+
700
+ const joinedUrl = String(clientCfg?.url || '').replace(/\/+$/, '');
701
+ const matchedHosted = joinedUrl ? hostInfos.find((h) => h.url === joinedUrl) || null : null;
702
+ let joinedBoard = null;
703
+ let joinedFetchError = null;
704
+ if (!offline && joinedUrl && clientCfg?.token && !matchedHosted) {
705
+ try {
706
+ joinedBoard = await fetchBoardSummary({
707
+ url: joinedUrl,
708
+ token: clientCfg.token,
709
+ viewKey: clientCfg.viewKey || '',
710
+ period: 'today',
711
+ timeoutMs: 6_000,
712
+ });
713
+ } catch (err) {
714
+ joinedFetchError = err?.message || 'unreachable';
715
+ }
716
+ }
717
+
718
+ const joinedMemberLive =
719
+ matchedHosted?.members?.find((m) => (clientCfg?.memberId && m.id === clientCfg.memberId) || (clientCfg?.memberName && m.name === clientCfg.memberName)) ||
720
+ joinedBoard?.members?.find((m) => (clientCfg?.memberId && m.id === clientCfg.memberId) || (clientCfg?.memberName && m.name === clientCfg.memberName)) ||
721
+ null;
722
+
723
+ let joinedAccountMatch = 'unbound';
724
+ if (clientCfg?.expectedEmailHash) {
725
+ if (!localAcct?.emailHash) joinedAccountMatch = 'unknown';
726
+ else joinedAccountMatch = localAcct.emailHash === clientCfg.expectedEmailHash ? 'matched' : 'mismatch';
727
+ }
728
+
729
+ const joinedInfo = clientCfg?.url
730
+ ? {
731
+ url: joinedUrl,
732
+ boardTitle: matchedHosted?.boardTitle || joinedBoard?.boardTitle || clientCfg.boardTitle || '',
733
+ sameAsHostedIndex: matchedHosted?.index || null,
734
+ sameAsHostedId: matchedHosted?.id || null,
735
+ memberId: clientCfg.memberId || '',
736
+ memberName: joinedMemberLive?.name || clientCfg.memberName || '',
737
+ role: joinedMemberLive?.role || '',
738
+ emailHint: joinedMemberLive?.emailHint || '',
739
+ online: joinedMemberLive ? Boolean(joinedMemberLive.online) : null,
740
+ accountMatch: joinedAccountMatch,
741
+ hasExpectedEmailHash: Boolean(clientCfg.expectedEmailHash),
742
+ deviceId: clientCfg.deviceId || '',
743
+ fetchError: joinedFetchError,
744
+ }
745
+ : null;
746
+
747
+ if (asJson) {
748
+ console.log(
749
+ JSON.stringify(
750
+ {
751
+ version: CLI_VERSION,
752
+ localAccount: localAcct
753
+ ? { maskedEmail: localAcct.maskedEmail, source: localAcct.source }
754
+ : null,
755
+ hosted: hostInfos,
756
+ joined: joinedInfo,
757
+ masterBinding: mCfg
758
+ ? { maskedEmail: mCfg.maskedEmail || '', tapInstalled: tapSt.installed, tapChained: tapSt.chained }
759
+ : null,
760
+ integrations: {
761
+ hookEnabled: Boolean(hookSt.hookInstalled && hookSt.hookEnabled),
762
+ skillInstalled: Boolean(hookSt.skillInstalled),
763
+ daemonInstalled: Boolean(daemonSt.installed),
764
+ daemonKind: daemonSt.kind,
765
+ },
766
+ },
767
+ null,
768
+ 2,
769
+ ),
770
+ );
771
+ return;
772
+ }
773
+
774
+ const accessModeLabel = (mode) => {
775
+ if (mode === 'cli-only') return 'cli-only (仅 CLI 免密登录)';
776
+ if (mode === 'view-key') return 'view-key (访问口令)';
777
+ if (mode === 'public') return 'public (公开只读)';
778
+ return mode || '';
779
+ };
780
+
781
+ console.log(`agy-family v${CLI_VERSION} — 车辆与账号总览\n`);
782
+
783
+ console.log('👤 本机当前 Antigravity 账号:');
784
+ if (localAcct) {
785
+ console.log(` ${localAcct.maskedEmail} (来源: ${localAcct.source})`);
786
+ } else {
787
+ console.log(' (未检测到本地已登录的 Antigravity 账号)');
788
+ }
789
+
790
+ console.log(`\n🚗 我开的车 (Hosted Boards — ${hostInfos.length}):`);
791
+ if (hostInfos.length === 0) {
792
+ console.log(' (暂无 — 运行 "agy-family deploy --self --daemon" 免费一键开车)');
793
+ } else {
794
+ for (const h of hostInfos) {
795
+ const star = h.active ? '★ ' : ' ';
796
+ const activeTag = h.active ? ' [当前默认]' : '';
797
+ console.log(` [${h.index}] ${star}${h.id} (${h.boardTitle})${activeTag}`);
798
+ console.log(` 网址 : ${h.url || '(未知)'}`);
799
+ const infra = [
800
+ h.provider,
801
+ h.workerName ? `Worker: ${h.workerName}` : '',
802
+ h.databaseName ? `D1: ${h.databaseName}` : '',
803
+ ]
804
+ .filter(Boolean)
805
+ .join(' · ');
806
+ if (infra) console.log(` 部署 : ${infra}`);
807
+ if (h.accessMode) console.log(` 权限 : ${accessModeLabel(h.accessMode)}`);
808
+ const mqLine = formatMasterQuotaLine(h.masterSubscriptionQuota);
809
+ if (mqLine) {
810
+ const acctSuffix = h.masterSubscriptionQuota?.accountLabel
811
+ ? ` (${h.masterSubscriptionQuota.accountLabel})`
812
+ : '';
813
+ console.log(` 主号 : ${mqLine}${acctSuffix}`);
814
+ }
815
+ if (h.fetchError) {
816
+ console.log(` 状态 : 离线或无法连接 (${h.fetchError})`);
817
+ } else if (offline) {
818
+ console.log(' 成员 : (已跳过联网查询,去掉 --offline 查看实时成员)');
819
+ } else {
820
+ console.log(` 成员 : ${h.memberCount}/6`);
821
+ for (const m of h.members) {
822
+ const roleTag = m.role === 'manager' ? '[主号]' : '[成员]';
823
+ const emailStr = m.emailHint ? ` ${m.emailHint}` : '';
824
+ const quotaStr = m.quotaPct != null ? ` · 份额 ${m.quotaPct}%` : '';
825
+ const stateStr = m.online ? 'online' : 'offline';
826
+ console.log(` • ${m.name} ${roleTag}${emailStr}${quotaStr} · ${stateStr}`);
827
+ }
828
+ }
829
+ }
830
+ }
831
+
832
+ console.log('\n🎫 我上的车 (Joined Board):');
833
+ if (!joinedInfo) {
834
+ console.log(' (未上车 — 运行 "agy-family join <邀请码> --daemon" 加入家庭组)');
835
+ } else {
836
+ const sameTag = joinedInfo.sameAsHostedIndex
837
+ ? ` (同我开的车 [${joinedInfo.sameAsHostedIndex}] ${joinedInfo.sameAsHostedId})`
838
+ : '';
839
+ console.log(` 网址 : ${joinedInfo.url}${sameTag}`);
840
+ if (joinedInfo.boardTitle) console.log(` 看板 : ${joinedInfo.boardTitle}`);
841
+ const roleTag = joinedInfo.role === 'manager' ? ' [主号]' : joinedInfo.role ? ' [成员]' : '';
842
+ const onlineTag = joinedInfo.online === true ? ' · online' : joinedInfo.online === false ? ' · offline' : '';
843
+ console.log(` 车位 : ${joinedInfo.memberName || '(已绑定)'}${roleTag}${onlineTag}`);
844
+ if (joinedInfo.emailHint || joinedInfo.hasExpectedEmailHash) {
845
+ const matchLabel =
846
+ joinedInfo.accountMatch === 'matched'
847
+ ? '✓ 与本机当前账号匹配'
848
+ : joinedInfo.accountMatch === 'mismatch'
849
+ ? `⚠ 与本机当前账号(${localAcct?.maskedEmail || '未知'})不匹配,已暂停上报`
850
+ : '已绑定 SHA-256 邮箱';
851
+ console.log(` 绑定号 : ${joinedInfo.emailHint ? `${joinedInfo.emailHint} · ` : ''}${matchLabel}`);
852
+ }
853
+ if (joinedInfo.deviceId) console.log(` 设备ID : ${joinedInfo.deviceId}`);
854
+ if (joinedInfo.fetchError) console.log(` 状态 : 无法连接 (${joinedInfo.fetchError})`);
855
+ }
856
+
857
+ console.log('\n⚙ 本地自动化:');
858
+ console.log(` /family 钩子 : ${hookSt.hookInstalled && hookSt.hookEnabled ? '已启用' : '未启用'}`);
859
+ console.log(` 定时守护进程 : ${daemonSt.installed ? `已安装 (${daemonSt.kind})` : '未安装'}`);
860
+ console.log(
861
+ ` 主号余量采集 : ${mCfg ? `${mCfg.maskedEmail || '已绑定'} · ${tapSt.installed ? (tapSt.chained ? '已激活 (与原状态栏链式共存)' : '已激活 (独立)') : '未安装 statusLine 钩子'}` : '未绑定'}`,
862
+ );
863
+
864
+ console.log('\n快捷命令:');
865
+ if (hostInfos.length > 1) {
866
+ console.log(' 切换当前主车 : agy-family host use <车名或序号>');
867
+ console.log(' 打开指定看板 : agy-family open <车名或序号> | agy-family open --joined');
868
+ console.log(' 向指定车邀人 : agy-family invite "名字" --car <车名或序号> --email "xxx@gmail.com"');
869
+ } else {
870
+ console.log(' 免密打开看板 : agy-family open');
871
+ if (hostInfos.length === 1 && joinedInfo && !joinedInfo.sameAsHostedIndex) {
872
+ console.log(' 打开我上的车 : agy-family open --joined');
873
+ }
874
+ if (hostInfos.length === 1) {
875
+ console.log(' 再开一辆新车 : agy-family deploy --name <新车名> --title "<看板标题>"');
876
+ }
877
+ }
878
+ return;
879
+ }
880
+
624
881
  if (cmd === 'open') {
625
882
  const printLinkOnly = args.includes('--link') || args.includes('--print-link') || args.includes('--url-only');
626
883
  const readonly = args.includes('--readonly') || args.includes('--member');
884
+ const openJoined = args.includes('--joined');
627
885
  const ttlFlag = readFlag(args, '--ttl');
628
886
  const ttlSec = ttlFlag ? Number(ttlFlag) || 60 : printLinkOnly ? 300 : 60;
629
887
  const urlOverride = readFlag(args, '--url');
630
888
  const adminKeyOverride = readFlag(args, '--admin-key');
889
+ const carFlag = readFlag(args, '--car') || readFlag(args, '--host');
890
+
891
+ const openValueFlags = new Set(['--ttl', '--url', '--admin-key', '--car', '--host']);
892
+ let carPositional = '';
893
+ for (let i = 1; i < args.length; i++) {
894
+ const a = args[i];
895
+ if (openValueFlags.has(a)) {
896
+ i += 1;
897
+ continue;
898
+ }
899
+ if (a.startsWith('--')) continue;
900
+ if (!carPositional) carPositional = a;
901
+ }
902
+ const carSelector = carFlag || carPositional;
903
+
904
+ let selectedHost = null;
905
+ if (carSelector) {
906
+ selectedHost = resolveHostEntry(carSelector);
907
+ if (!selectedHost) {
908
+ console.error(`Hosted car not found: "${carSelector}". Run "agy-family ls" to see all cars.`);
909
+ process.exit(1);
910
+ }
911
+ } else if (!openJoined) {
912
+ selectedHost = resolveHostEntry('');
913
+ }
631
914
 
632
- const host = readHostConfig();
633
915
  const cfg = getOrCreateClientConfig();
634
- const targetUrl = (urlOverride || host?.url || cfg?.url || '').replace(/\/+$/, '');
916
+ const targetUrl = (urlOverride || (openJoined ? cfg?.url : selectedHost?.url || cfg?.url) || '').replace(/\/+$/, '');
635
917
  if (!targetUrl) {
636
- console.error('Not joined or linked to any family board yet. Run "agy-family join <invite>" or "agy-family deploy".');
918
+ console.error(
919
+ openJoined
920
+ ? 'Not joined to any family board yet. Run "agy-family join <invite>".'
921
+ : 'Not joined or linked to any family board yet. Run "agy-family join <invite>" or "agy-family deploy".',
922
+ );
637
923
  process.exit(1);
638
924
  }
639
925
 
640
- const hostMatches = Boolean(host?.url && host.url.replace(/\/+$/, '') === targetUrl && host.adminKey);
926
+ const matchedHostForUrl =
927
+ selectedHost && selectedHost.url && selectedHost.url.replace(/\/+$/, '') === targetUrl
928
+ ? selectedHost
929
+ : readHostsRegistry().hosts.find((h) => h.url && h.url.replace(/\/+$/, '') === targetUrl) || null;
930
+ const hostMatches = Boolean(!openJoined && matchedHostForUrl?.adminKey);
641
931
  const clientMatches = Boolean(cfg?.url && cfg.url.replace(/\/+$/, '') === targetUrl && cfg.token);
642
- const useAdminKey = readonly ? '' : (adminKeyOverride || (hostMatches ? host.adminKey : ''));
932
+ const useAdminKey = readonly || openJoined ? '' : (adminKeyOverride || (hostMatches ? matchedHostForUrl.adminKey : ''));
643
933
  const useToken = clientMatches ? cfg.token : (!useAdminKey && cfg?.token ? cfg.token : '');
644
934
 
645
935
  const res = await requestWebLoginTicket({
646
936
  url: targetUrl,
647
937
  token: useToken,
648
938
  adminKey: useAdminKey,
649
- readonly,
939
+ readonly: readonly || openJoined,
650
940
  ttlSec,
651
941
  });
652
942
 
@@ -667,8 +957,13 @@ async function main() {
667
957
 
668
958
  if (cmd === 'status') {
669
959
  const cfg = getOrCreateClientConfig();
670
- const host = readHostConfig();
671
- const targetUrl = cfg.url || host?.url || '';
960
+ const carSelector = readFlag(args, '--car') || readFlag(args, '--host');
961
+ const host = carSelector ? resolveHostEntry(carSelector) : resolveHostEntry('');
962
+ if (carSelector && !host) {
963
+ console.error(`Hosted car not found: "${carSelector}". Run "agy-family ls" to see all cars.`);
964
+ process.exit(1);
965
+ }
966
+ const targetUrl = (carSelector ? host?.url : cfg.url || host?.url) || '';
672
967
  if (!targetUrl) {
673
968
  console.error('Not joined to any family group yet. Run: agy-family join <agyfam://join?...>');
674
969
  process.exit(1);
@@ -677,11 +972,13 @@ async function main() {
677
972
  const period = pIdx >= 0 ? args[pIdx + 1] || 'today' : 'today';
678
973
  const kIdx = args.indexOf('--view-key');
679
974
  const viewKey = kIdx >= 0 ? args[kIdx + 1] || '' : cfg.viewKey || '';
680
- const hostMatches = Boolean(host?.url && host.url.replace(/\/+$/, '') === targetUrl.replace(/\/+$/, '') && host.adminKey);
975
+ const normTargetUrl = targetUrl.replace(/\/+$/, '');
976
+ const hostMatches = Boolean(host?.url && host.url.replace(/\/+$/, '') === normTargetUrl && host.adminKey);
977
+ const clientMatches = Boolean(cfg?.url && cfg.url.replace(/\/+$/, '') === normTargetUrl && cfg.token);
681
978
  const board = await fetchBoardSummary({
682
979
  url: targetUrl,
683
980
  viewKey,
684
- token: cfg.token || '',
981
+ token: clientMatches ? cfg.token : '',
685
982
  adminKey: hostMatches ? host.adminKey : '',
686
983
  period,
687
984
  });
@@ -830,7 +1127,7 @@ async function main() {
830
1127
  }
831
1128
 
832
1129
  if (cmd === 'invite') {
833
- const valueFlags = new Set(['--email', '--quota', '--role', '--color', '--url', '--admin-key']);
1130
+ const valueFlags = new Set(['--email', '--quota', '--role', '--color', '--url', '--admin-key', '--car', '--host']);
834
1131
  const pos = [];
835
1132
  for (let i = 1; i < args.length; i++) {
836
1133
  const a = args[i];
@@ -843,10 +1140,15 @@ async function main() {
843
1140
  }
844
1141
  const memberName = pos.join(' ').trim();
845
1142
  if (!memberName) {
846
- console.error('Usage: agy-family invite <name> [--email <gmail>] [--quota <pct>] [--role member|manager]');
1143
+ console.error('Usage: agy-family invite <name> [--car <car>] [--email <gmail>] [--quota <pct>] [--role member|manager]');
1144
+ process.exit(1);
1145
+ }
1146
+ const carSelector = readFlag(args, '--car') || readFlag(args, '--host');
1147
+ const hostCfg = carSelector ? resolveHostEntry(carSelector) : resolveHostEntry('');
1148
+ if (carSelector && !hostCfg) {
1149
+ console.error(`Hosted car not found: "${carSelector}". Run "agy-family ls" to see all cars.`);
847
1150
  process.exit(1);
848
1151
  }
849
- const hostCfg = readHostConfig();
850
1152
  const url = readFlag(args, '--url') || hostCfg?.url || '';
851
1153
  const adminKey = readFlag(args, '--admin-key') || hostCfg?.adminKey || process.env.AGY_FAMILY_ADMIN_KEY || '';
852
1154
  if (!url || !adminKey) {
@@ -890,7 +1192,12 @@ async function main() {
890
1192
  const action = (args[1] || 'status').toLowerCase();
891
1193
  const urlOverride = readFlag(args, '--url');
892
1194
  const adminKeyOverride = readFlag(args, '--admin-key');
893
- const host = readHostConfig();
1195
+ const carSelector = readFlag(args, '--car') || readFlag(args, '--host');
1196
+ const host = carSelector ? resolveHostEntry(carSelector) : resolveHostEntry('');
1197
+ if (carSelector && !host) {
1198
+ console.error(`Hosted car not found: "${carSelector}". Run "agy-family ls" to see all cars.`);
1199
+ process.exit(1);
1200
+ }
894
1201
  const targetUrl = urlOverride || host?.url || '';
895
1202
  const targetKey = adminKeyOverride || host?.adminKey || '';
896
1203
 
@@ -1039,43 +1346,104 @@ async function main() {
1039
1346
 
1040
1347
  if (cmd === 'host') {
1041
1348
  const action = (args[1] || 'show').toLowerCase();
1349
+ if (action === 'ls' || action === 'list') {
1350
+ const reg = readHostsRegistry();
1351
+ if (args.includes('--json')) {
1352
+ console.log(JSON.stringify(reg, null, 2));
1353
+ return;
1354
+ }
1355
+ if (reg.hosts.length === 0) {
1356
+ console.log('No hosted boards configured on this machine yet.');
1357
+ console.log(' Deploy a free Cloudflare board : agy-family deploy --self --daemon');
1358
+ console.log(' Or link an existing board : agy-family host link --url <https://...> --admin-key <adm_...>');
1359
+ return;
1360
+ }
1361
+ console.log(`Hosted Family Boards (${reg.hosts.length}) — Registry: ${hostsRegistryPath()}`);
1362
+ reg.hosts.forEach((h, idx) => {
1363
+ const star = h.id === reg.active ? '★' : ' ';
1364
+ const tag = h.id === reg.active ? ' [active]' : '';
1365
+ console.log(` [${idx + 1}] ${star} ${h.id} (${h.boardTitle || 'Antigravity 家庭组'})${tag}`);
1366
+ console.log(` URL : ${h.url || '(unknown)'}`);
1367
+ console.log(` Infra : ${h.provider || 'cloudflare'}${h.workerName ? ` · Worker: ${h.workerName}` : ''}${h.databaseName ? ` · D1: ${h.databaseName}` : ''}`);
1368
+ });
1369
+ console.log('\nSwitch active car: agy-family host use <name|index>');
1370
+ return;
1371
+ }
1372
+ if (action === 'use' || action === 'switch') {
1373
+ const selector = args[2] || '';
1374
+ if (!selector) {
1375
+ console.error('Usage: agy-family host use <car-name|index|url>');
1376
+ process.exit(1);
1377
+ }
1378
+ const switched = setActiveHost(selector);
1379
+ if (!switched) {
1380
+ console.error(`Hosted car not found: "${selector}". Run "agy-family host ls" to view saved cars.`);
1381
+ process.exit(1);
1382
+ }
1383
+ console.log(`✓ Switched active hosted board -> ${switched.entry.id} (${switched.entry.boardTitle || 'Antigravity 家庭组'})`);
1384
+ console.log(` Board URL : ${switched.entry.url}`);
1385
+ return;
1386
+ }
1042
1387
  if (action === 'link') {
1043
1388
  const url = readFlag(args, '--url').replace(/\/+$/, '');
1044
1389
  const adminKey = readFlag(args, '--admin-key');
1045
1390
  if (!url || !adminKey) {
1046
1391
  console.error(
1047
- 'Usage: agy-family host link --url <https://...> --admin-key <adm_...> [--name <worker>] [--db-name <db>] [--db-id <uuid>] [--title <title>]',
1392
+ 'Usage: agy-family host link --url <https://...> --admin-key <adm_...> [--name <alias>] [--db-name <db>] [--db-id <uuid>] [--title <title>]',
1048
1393
  );
1049
1394
  process.exit(1);
1050
1395
  }
1051
- const existing = readHostConfig() || {};
1052
- const workerName = sanitizeWorkerName(readFlag(args, '--name') || existing.workerName || 'agy-family');
1053
- const databaseName = readFlag(args, '--db-name') || existing.databaseName || `${workerName}-db`;
1396
+ const explicitName = readFlag(args, '--name');
1397
+ const existing = resolveHostEntry(explicitName || url) || {};
1398
+ const entryId = explicitName ? sanitizeWorkerName(explicitName) : deriveHostEntryId({ ...existing, url });
1399
+ const workerName = explicitName
1400
+ ? sanitizeWorkerName(explicitName)
1401
+ : existing.workerName || (url.includes('.workers.dev') ? entryId : '');
1402
+ const databaseName = readFlag(args, '--db-name') || existing.databaseName || (workerName ? `${workerName}-db` : '');
1054
1403
  const databaseId = readFlag(args, '--db-id') || existing.databaseId || '';
1055
- const boardTitle = readFlag(args, '--title') || existing.boardTitle || 'Antigravity Family Board';
1056
- const saved = writeHostConfig({
1057
- provider: url.includes('.workers.dev') || databaseId ? 'cloudflare' : 'self-hosted',
1058
- workerName,
1059
- databaseName,
1060
- databaseId,
1061
- url,
1062
- adminKey,
1063
- boardTitle,
1064
- version: CLI_VERSION,
1065
- linkedAt: Date.now(),
1066
- });
1067
- console.log(`✓ Linked hosted board -> ${url}`);
1068
- console.log(` Saved to : ${saved} (chmod 600)`);
1069
- console.log(' You can now run "agy-family invite <name>" or "agy-family deploy" (to upgrade).');
1404
+ const boardTitle = readFlag(args, '--title') || existing.boardTitle || 'Antigravity 家庭组';
1405
+ const saved = upsertHostEntry(
1406
+ {
1407
+ id: entryId,
1408
+ name: entryId,
1409
+ provider: url.includes('.workers.dev') || databaseId ? 'cloudflare' : 'self-hosted',
1410
+ ...(workerName ? { workerName } : {}),
1411
+ ...(databaseName ? { databaseName } : {}),
1412
+ ...(databaseId ? { databaseId } : {}),
1413
+ url,
1414
+ adminKey,
1415
+ boardTitle,
1416
+ version: CLI_VERSION,
1417
+ linkedAt: Date.now(),
1418
+ },
1419
+ { setActive: true },
1420
+ );
1421
+ console.log(`✓ Linked hosted board "${saved.entry.id}" -> ${url}`);
1422
+ console.log(` Saved to : ${saved.hostsRegistryPath} (chmod 600, active)`);
1423
+ console.log(' You can now run "agy-family ls", "agy-family open", or "agy-family invite <name>".');
1070
1424
  return;
1071
1425
  }
1072
1426
  if (action === 'unlink' || action === 'remove') {
1073
- const removed = removeHostConfig();
1074
- console.log(`✓ Local host config: ${removed ? 'removed' : 'not configured'}.`);
1427
+ const selector = args[2] && !args[2].startsWith('--') ? args[2] : '';
1428
+ const res = removeHostEntry(selector);
1429
+ if (!res.removed) {
1430
+ console.log(selector ? `Hosted car not found: "${selector}".` : 'Local host config: not configured.');
1431
+ return;
1432
+ }
1433
+ console.log(`✓ Unlinked hosted board "${res.removed.id}"${res.removed.url ? ` (${res.removed.url})` : ''}.`);
1434
+ if (res.nextActive) {
1435
+ console.log(` Active board is now: ${res.nextActive.id} (${res.nextActive.url})`);
1436
+ }
1075
1437
  return;
1076
1438
  }
1077
- const cfg = readHostConfig();
1439
+ const selector = action !== 'show' && !action.startsWith('--') ? args[1] : '';
1440
+ const reg = readHostsRegistry();
1441
+ const cfg = selector ? resolveHostEntry(selector) : resolveHostEntry('');
1078
1442
  if (!cfg) {
1443
+ if (selector) {
1444
+ console.error(`Hosted car not found: "${selector}". Run "agy-family host ls" to view saved cars.`);
1445
+ process.exit(1);
1446
+ }
1079
1447
  console.log('No hosted board configured on this machine yet.');
1080
1448
  console.log(' Deploy a free Cloudflare board : agy-family deploy --self --daemon');
1081
1449
  console.log(' Or link an existing board : agy-family host link --url <https://...> --admin-key <adm_...>');
@@ -1085,7 +1453,8 @@ async function main() {
1085
1453
  console.log(JSON.stringify(cfg, null, 2));
1086
1454
  return;
1087
1455
  }
1088
- console.log('Hosted Family Board:');
1456
+ console.log(`Hosted Family Board${reg.hosts.length > 1 ? ` (${cfg.id === reg.active ? 'active' : 'saved'}, ${reg.hosts.length} total)` : ''}:`);
1457
+ console.log(` Name / ID : ${cfg.id || cfg.workerName || 'agy-family'}`);
1089
1458
  console.log(` Provider : ${cfg.provider || 'cloudflare'}`);
1090
1459
  console.log(` Board URL : ${cfg.url || '(unknown)'}`);
1091
1460
  console.log(` Admin Key : ${cfg.adminKey || '(not saved)'}`);
@@ -1101,6 +1470,9 @@ async function main() {
1101
1470
  // Offline or unreachable — skip live count quietly.
1102
1471
  }
1103
1472
  }
1473
+ if (reg.hosts.length > 1) {
1474
+ console.log(' All Cars : run "agy-family ls" or "agy-family host ls"');
1475
+ }
1104
1476
  return;
1105
1477
  }
1106
1478
 
@@ -17,10 +17,14 @@ import {
17
17
  fetchBoardSummary,
18
18
  getOrCreateSharedDeviceId,
19
19
  hashEmailSha256,
20
+ inspectStatusLineTap,
20
21
  pushSyncPayload,
22
+ readLocalActiveEmailHint,
23
+ readMasterConfig,
21
24
  requestWebLoginTicket,
22
25
  writeActiveAccountCache,
23
26
  } from '../../core/src/index.mjs';
27
+ import { readHostsRegistry, resolveHostEntry } from './host.mjs';
24
28
 
25
29
  export const FAMILY_HOOK_NAME = 'agy-family';
26
30
  export const LAUNCHD_LABEL = 'io.agy-family.sync';
@@ -38,6 +42,8 @@ description: View Google Family Group Antigravity usage board, agreed cap progre
38
42
 
39
43
  When the \`agy-family\` \`PreInvocation\` hook is active in \`~/.gemini/config/hooks.json\`, bare commands such as:
40
44
  - \`/family\` or \`/family today|7d|cycle|30d\`
45
+ - \`/family ls\` (list hosted cars, joined car, URLs, and bound accounts)
46
+ - \`/family open [car]\` (passwordless one-time browser login link)
41
47
  - \`/family sync\` or \`/family sync --full\`
42
48
  - \`/family audit\`
43
49
  - \`/family join agyfam://join?d=...\`
@@ -405,10 +411,19 @@ export function parseFamilySlashCommand(rawInput) {
405
411
  if (flag && flag !== '--full' && flag !== 'full') return null;
406
412
  return { kind: 'sync', fullSync: Boolean(flag) };
407
413
  }
414
+ if ((sub === 'ls' || sub === 'list' || sub === 'info' || sub === 'cars') && rest.length === 1) {
415
+ return { kind: 'ls' };
416
+ }
408
417
  if (sub === 'open' && rest.length <= 2) {
409
- const flag = rest[1]?.toLowerCase();
410
- if (flag && flag !== '--link' && flag !== 'link') return null;
411
- return { kind: 'open', linkOnly: Boolean(flag) };
418
+ const arg = rest[1] || '';
419
+ const low = arg.toLowerCase();
420
+ if (!arg || low === '--link' || low === 'link') {
421
+ return { kind: 'open', linkOnly: Boolean(arg), car: '', joined: false };
422
+ }
423
+ if (low === '--joined' || low === 'joined') {
424
+ return { kind: 'open', linkOnly: false, car: '', joined: true };
425
+ }
426
+ return { kind: 'open', linkOnly: false, car: arg, joined: false };
412
427
  }
413
428
  if (sub === 'audit' && rest.length === 1) {
414
429
  return { kind: 'audit' };
@@ -542,7 +557,7 @@ function formatStatusMarkdown(board, cfg) {
542
557
  if (link) {
543
558
  lines.push('', `🔗 看板地址:${link}`);
544
559
  }
545
- lines.push('', '`命令:/family [today|7d|cycle|30d] · /family sync · /family audit`');
560
+ lines.push('', '`命令:/family [today|7d|cycle|30d] · /family ls · /family open · /family sync · /family audit`');
546
561
  return lines.join('\n');
547
562
  }
548
563
 
@@ -627,7 +642,8 @@ export async function handlePreInvocation(
627
642
  '### `/family` 指令速查 *(0 tokens)*',
628
643
  '',
629
644
  '- `/family` 或 `/family 7d` / `/family cycle` / `/family 30d` — 查看家庭组用量排行与主号订阅余量',
630
- '- `/family open` — 生成一次性免密登录链接打开网页看板(无需任何密码)',
645
+ '- `/family ls` — 一览本机开过的所有车(网址、主号)、当前上的车与登录账号',
646
+ '- `/family open [车名或序号]` — 生成一次性免密登录链接打开网页看板(无需密码)',
631
647
  '- `/family sync` 或 `/family sync --full` — 立即增量/全量同步本机 IDE + CLI 用量',
632
648
  '- `/family audit` — 查看最近一次上报的脱敏 JSON(隐私审计)',
633
649
  '- `/family join agyfam://join?d=...` — 粘贴邀请码加入或切换家庭组',
@@ -636,6 +652,64 @@ export async function handlePreInvocation(
636
652
  );
637
653
  }
638
654
 
655
+ if (cmd.kind === 'ls') {
656
+ const reg = readHostsRegistry({ home });
657
+ const cfgLocal = readJsonSafe(cfgPath);
658
+ const localAcct = readLocalActiveEmailHint({ home });
659
+ const mCfg = readMasterConfig({ home });
660
+ const tapSt = inspectStatusLineTap({ home });
661
+
662
+ const lines = ['### `agy-family` 车辆与账号总览 *(0 tokens)*', ''];
663
+ lines.push(
664
+ `**本机当前 Antigravity 账号**:${localAcct ? `\`${localAcct.maskedEmail}\` (${localAcct.source})` : '未检测到本地登录'}`,
665
+ );
666
+ lines.push('');
667
+
668
+ lines.push(`#### 🚗 我开的车(${reg.hosts.length})`);
669
+ if (reg.hosts.length === 0) {
670
+ lines.push('- 暂无(终端运行 `agy-family deploy --self --daemon` 可一键免费开车)');
671
+ } else {
672
+ reg.hosts.forEach((h, idx) => {
673
+ const activeBadge = h.id === reg.active ? ' `当前默认`' : '';
674
+ lines.push(
675
+ `- **[${idx + 1}] ${h.id}**(${h.boardTitle || 'Antigravity 家庭组'})${activeBadge} — ${h.url || '(未知)'}`,
676
+ );
677
+ });
678
+ }
679
+ lines.push('');
680
+
681
+ lines.push('#### 🎫 我上的车');
682
+ if (!cfgLocal?.url) {
683
+ lines.push('- 尚未上车(执行 `/family join agyfam://join?d=...` 加入家庭组)');
684
+ } else {
685
+ const joinedUrl = String(cfgLocal.url).replace(/\/+$/, '');
686
+ const sameIdx = reg.hosts.findIndex((h) => h.url === joinedUrl);
687
+ const sameNote = sameIdx >= 0 ? ` *(同我开的车 [${sameIdx + 1}] ${reg.hosts[sameIdx].id})*` : '';
688
+ let acctNote = '';
689
+ if (cfgLocal.expectedEmailHash) {
690
+ if (localAcct?.emailHash) {
691
+ acctNote =
692
+ localAcct.emailHash === cfgLocal.expectedEmailHash
693
+ ? ' · `✓ 账号匹配`'
694
+ : ' · `⚠ 账号不匹配(暂停上报)`';
695
+ } else {
696
+ acctNote = ' · 已绑定 SHA-256 邮箱';
697
+ }
698
+ }
699
+ lines.push(
700
+ `- **${cfgLocal.boardTitle || joinedUrl}**${sameNote} — ${joinedUrl}`,
701
+ );
702
+ lines.push(` - 车位:**${cfgLocal.memberName || '(已绑定)'}**${acctNote}`);
703
+ }
704
+ lines.push('');
705
+
706
+ lines.push(
707
+ `**主号余量采集**:${mCfg ? `\`${mCfg.maskedEmail || '已绑定'}\`(${tapSt.installed ? (tapSt.chained ? '已激活 · 链式共存' : '已激活 · 独立') : '未安装 statusLine'})` : '未绑定'}`,
708
+ );
709
+ lines.push('', '`终端完整实时详情:agy-family ls · 切换主车:agy-family host use <车名或序号>`');
710
+ return buildZeroTokenMarkdownResponse(lines.join('\n'));
711
+ }
712
+
639
713
  if (cmd.kind === 'join') {
640
714
  try {
641
715
  const parsed = decodeInviteInput(cmd.invite);
@@ -691,37 +765,59 @@ export async function handlePreInvocation(
691
765
  }
692
766
 
693
767
  const cfg = readJsonSafe(cfgPath);
694
- const hostCfg = readJsonSafe(join(clientConfigDir(home), 'host.json'));
695
- const effectiveUrl = cfg?.url || hostCfg?.url || '';
696
- const effectiveToken = cfg?.token || '';
697
- const effectiveAdminKey =
698
- hostCfg?.url && effectiveUrl && hostCfg.url.replace(/\/+$/, '') === effectiveUrl.replace(/\/+$/, '')
699
- ? hostCfg.adminKey || ''
700
- : '';
768
+ const hostCfg = resolveHostEntry('', { home });
701
769
 
702
770
  if (cmd.kind === 'open') {
703
- if (!effectiveUrl || (!effectiveToken && !effectiveAdminKey)) {
771
+ let targetHost = null;
772
+ if (cmd.car) {
773
+ targetHost = resolveHostEntry(cmd.car, { home });
774
+ if (!targetHost) {
775
+ return buildZeroTokenMarkdownResponse(
776
+ `❌ 未找到名为 \`${cmd.car}\` 的自建车。输入 \`/family ls\` 查看所有已记录的车辆。`,
777
+ );
778
+ }
779
+ } else if (!cmd.joined) {
780
+ targetHost = hostCfg;
781
+ }
782
+
783
+ const openUrl = (cmd.joined ? cfg?.url : targetHost?.url || cfg?.url || '').replace(/\/+$/, '');
784
+ const matchedHost =
785
+ targetHost && targetHost.url === openUrl
786
+ ? targetHost
787
+ : readHostsRegistry({ home }).hosts.find((h) => h.url === openUrl) || null;
788
+ const openAdminKey = cmd.joined ? '' : matchedHost?.adminKey || '';
789
+ const openToken = cfg?.url && cfg.url.replace(/\/+$/, '') === openUrl ? cfg.token || '' : '';
790
+
791
+ if (!openUrl || (!openToken && !openAdminKey)) {
704
792
  return buildZeroTokenMarkdownResponse(
705
793
  '尚未加入家庭组。请粘贴家庭组管理员发来的邀请码执行:\n\n`/family join agyfam://join?d=...`',
706
794
  );
707
795
  }
708
796
  try {
709
797
  const ticketRes = await requestWebLoginTicket({
710
- url: effectiveUrl,
711
- token: effectiveToken,
712
- adminKey: effectiveAdminKey,
798
+ url: openUrl,
799
+ token: openToken,
800
+ adminKey: openAdminKey,
801
+ readonly: Boolean(cmd.joined),
713
802
  ttlSec: 120,
714
803
  fetchFn,
715
804
  });
716
805
  const roleNote = ticketRes.scope === 'admin' ? '管理员免密会话' : '成员免密会话';
717
806
  return buildZeroTokenMarkdownResponse(
718
- `### 一次性免密登录链接(${roleNote} · ${ticketRes.expiresInSec}s 单次有效 · 0 tokens)\n\n${ticketRes.enterUrl}\n\n也可在终端直接运行 \`agy-family open\` 自动拉起浏览器。`,
807
+ `### 一次性免密登录链接(${roleNote} · ${ticketRes.expiresInSec}s 单次有效 · 0 tokens)\n\n${ticketRes.enterUrl}\n\n也可在终端直接运行 \`agy-family open${cmd.car ? ` ${cmd.car}` : ''}\` 自动拉起浏览器。`,
719
808
  );
720
809
  } catch (err) {
721
810
  return buildZeroTokenMarkdownResponse(`❌ 无法签发一次性登录票据:${err?.message || err}`);
722
811
  }
723
812
  }
724
813
 
814
+ const effectiveUrl = cfg?.url || hostCfg?.url || '';
815
+ const effectiveToken = cfg?.token || '';
816
+ const effectiveAdminKey =
817
+ hostCfg?.url && effectiveUrl && hostCfg.url.replace(/\/+$/, '') === effectiveUrl.replace(/\/+$/, '')
818
+ ? hostCfg.adminKey || ''
819
+ : '';
820
+
725
821
  if (!cfg?.url || !cfg?.token) {
726
822
  if (effectiveUrl && effectiveAdminKey && cmd.kind === 'status') {
727
823
  try {
@@ -794,7 +890,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
794
890
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
795
891
  deviceId,
796
892
  clientKind: 'cli',
797
- clientVersion: '0.6.0',
893
+ clientVersion: '0.6.1',
798
894
  home,
799
895
  fileCache: cache,
800
896
  syncedHashes: prevHashes,
@@ -23,6 +23,56 @@ export function hostConfigPath(home = homedir()) {
23
23
  return join(home, '.config', 'agy-family', 'host.json');
24
24
  }
25
25
 
26
+ export function hostsRegistryPath(home = homedir()) {
27
+ return join(home, '.config', 'agy-family', 'hosts.json');
28
+ }
29
+
30
+ function normalizeHostUrl(rawUrl) {
31
+ return String(rawUrl || '').trim().replace(/\/+$/, '');
32
+ }
33
+
34
+ export function deriveHostEntryId(entry = {}) {
35
+ const explicit = String(entry.id || entry.name || entry.workerName || '').trim();
36
+ if (explicit) return sanitizeWorkerName(explicit);
37
+ const url = normalizeHostUrl(entry.url || '');
38
+ if (url) {
39
+ try {
40
+ const host = new URL(url).hostname;
41
+ const firstLabel = host.split('.')[0] || host;
42
+ return sanitizeWorkerName(firstLabel);
43
+ } catch {
44
+ // Fallback below.
45
+ }
46
+ }
47
+ return 'agy-family';
48
+ }
49
+
50
+ function normalizeHostEntry(raw) {
51
+ if (!raw || typeof raw !== 'object') return null;
52
+ const url = normalizeHostUrl(raw.url || '');
53
+ const workerName = raw.workerName ? sanitizeWorkerName(raw.workerName) : '';
54
+ const id = deriveHostEntryId({ ...raw, url, workerName });
55
+ return {
56
+ ...raw,
57
+ id,
58
+ name: String(raw.name || workerName || id).trim() || id,
59
+ provider: raw.provider || (url.includes('.workers.dev') || raw.databaseId ? 'cloudflare' : 'self-hosted'),
60
+ ...(workerName ? { workerName } : {}),
61
+ url,
62
+ };
63
+ }
64
+
65
+ function writeJsonPrivate(filePath, data) {
66
+ mkdirSync(dirname(filePath), { recursive: true });
67
+ writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
68
+ try {
69
+ chmodSync(filePath, 0o600);
70
+ } catch {
71
+ // Ignore on platforms without POSIX chmod semantics.
72
+ }
73
+ return filePath;
74
+ }
75
+
26
76
  export function readHostConfig({ home = homedir() } = {}) {
27
77
  const p = hostConfigPath(home);
28
78
  try {
@@ -35,15 +85,7 @@ export function readHostConfig({ home = homedir() } = {}) {
35
85
  }
36
86
 
37
87
  export function writeHostConfig(data, { home = homedir() } = {}) {
38
- const p = hostConfigPath(home);
39
- mkdirSync(dirname(p), { recursive: true });
40
- writeFileSync(p, `${JSON.stringify(data, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
41
- try {
42
- chmodSync(p, 0o600);
43
- } catch {
44
- // Ignore on platforms without POSIX chmod semantics.
45
- }
46
- return p;
88
+ return writeJsonPrivate(hostConfigPath(home), data);
47
89
  }
48
90
 
49
91
  export function removeHostConfig({ home = homedir() } = {}) {
@@ -53,6 +95,162 @@ export function removeHostConfig({ home = homedir() } = {}) {
53
95
  return existed;
54
96
  }
55
97
 
98
+ export function readHostsRegistry({ home = homedir() } = {}) {
99
+ const regPath = hostsRegistryPath(home);
100
+ let active = '';
101
+ let list = [];
102
+ try {
103
+ if (existsSync(regPath)) {
104
+ const parsed = JSON.parse(readFileSync(regPath, 'utf8').replace(/^\uFEFF/, ''));
105
+ if (parsed && typeof parsed === 'object') {
106
+ active = String(parsed.active || '').trim();
107
+ if (Array.isArray(parsed.hosts)) {
108
+ list = parsed.hosts.map(normalizeHostEntry).filter(Boolean);
109
+ }
110
+ }
111
+ }
112
+ } catch {
113
+ list = [];
114
+ }
115
+
116
+ // Seamlessly migrate/include legacy single-car `host.json` if not yet present in `hosts.json`.
117
+ const legacy = readHostConfig({ home });
118
+ if (legacy && (legacy.url || legacy.workerName)) {
119
+ const normLegacy = normalizeHostEntry(legacy);
120
+ if (normLegacy) {
121
+ const idx = list.findIndex(
122
+ (h) => (normLegacy.url && h.url === normLegacy.url) || h.id === normLegacy.id,
123
+ );
124
+ if (idx < 0) {
125
+ list.unshift(normLegacy);
126
+ if (!active) active = normLegacy.id;
127
+ } else if (!active) {
128
+ active = list[idx].id;
129
+ }
130
+ }
131
+ }
132
+
133
+ if (list.length > 0 && !list.some((h) => h.id === active)) {
134
+ active = list[0].id;
135
+ }
136
+
137
+ return { version: 1, active, hosts: list };
138
+ }
139
+
140
+ function writeHostsRegistry(registry, { home = homedir() } = {}) {
141
+ return writeJsonPrivate(hostsRegistryPath(home), {
142
+ version: 1,
143
+ active: registry.active || '',
144
+ hosts: registry.hosts || [],
145
+ });
146
+ }
147
+
148
+ export function upsertHostEntry(entry, { home = homedir(), setActive = true } = {}) {
149
+ const norm = normalizeHostEntry(entry);
150
+ if (!norm) throw new Error('Invalid host entry.');
151
+ const reg = readHostsRegistry({ home });
152
+ const now = Date.now();
153
+ const idx = reg.hosts.findIndex(
154
+ (h) =>
155
+ (norm.url && h.url && h.url === norm.url) ||
156
+ (norm.id && h.id === norm.id) ||
157
+ (norm.workerName && h.workerName && h.workerName === norm.workerName),
158
+ );
159
+
160
+ let merged;
161
+ if (idx >= 0) {
162
+ const prev = reg.hosts[idx];
163
+ merged = normalizeHostEntry({
164
+ ...prev,
165
+ ...norm,
166
+ id: norm.id || prev.id,
167
+ deployedAt: norm.deployedAt || prev.deployedAt,
168
+ linkedAt: norm.linkedAt || prev.linkedAt,
169
+ updatedAt: now,
170
+ });
171
+ reg.hosts[idx] = merged;
172
+ } else {
173
+ merged = { ...norm, updatedAt: now };
174
+ reg.hosts.push(merged);
175
+ }
176
+
177
+ if (setActive || !reg.active) {
178
+ reg.active = merged.id;
179
+ }
180
+ const registryPath = writeHostsRegistry(reg, { home });
181
+ let activeHostPath = hostConfigPath(home);
182
+ if (reg.active === merged.id) {
183
+ activeHostPath = writeHostConfig(merged, { home });
184
+ }
185
+ return { entry: merged, registry: reg, hostConfigPath: activeHostPath, hostsRegistryPath: registryPath };
186
+ }
187
+
188
+ export function resolveHostEntry(selector = '', { home = homedir() } = {}) {
189
+ const reg = readHostsRegistry({ home });
190
+ if (reg.hosts.length === 0) return null;
191
+ const q = String(selector || '').trim();
192
+ if (!q) {
193
+ return reg.hosts.find((h) => h.id === reg.active) || reg.hosts[0] || null;
194
+ }
195
+ // 1-based numeric index matching `agy-family ls` order
196
+ if (/^\d+$/.test(q)) {
197
+ const idx = Number(q) - 1;
198
+ if (idx >= 0 && idx < reg.hosts.length) return reg.hosts[idx];
199
+ }
200
+ const low = q.toLowerCase().replace(/\/+$/, '');
201
+ const exact = reg.hosts.find(
202
+ (h) =>
203
+ h.id.toLowerCase() === low ||
204
+ String(h.name || '').toLowerCase() === low ||
205
+ String(h.workerName || '').toLowerCase() === low ||
206
+ String(h.url || '').toLowerCase() === low,
207
+ );
208
+ if (exact) return exact;
209
+
210
+ const partial = reg.hosts.filter(
211
+ (h) =>
212
+ h.id.toLowerCase().includes(low) ||
213
+ String(h.name || '').toLowerCase().includes(low) ||
214
+ String(h.boardTitle || '').toLowerCase().includes(low) ||
215
+ String(h.url || '').toLowerCase().includes(low),
216
+ );
217
+ if (partial.length === 1) return partial[0];
218
+ return null;
219
+ }
220
+
221
+ export function setActiveHost(selector, { home = homedir() } = {}) {
222
+ const target = resolveHostEntry(selector, { home });
223
+ if (!target) return null;
224
+ const reg = readHostsRegistry({ home });
225
+ reg.active = target.id;
226
+ writeHostsRegistry(reg, { home });
227
+ writeHostConfig(target, { home });
228
+ return { entry: target, registry: reg };
229
+ }
230
+
231
+ export function removeHostEntry(selector = '', { home = homedir() } = {}) {
232
+ const reg = readHostsRegistry({ home });
233
+ if (reg.hosts.length === 0) {
234
+ const hadLegacy = removeHostConfig({ home });
235
+ return { removed: hadLegacy ? { id: 'default' } : null, nextActive: null, remaining: 0 };
236
+ }
237
+ const target = resolveHostEntry(selector, { home });
238
+ if (!target) return { removed: null, nextActive: resolveHostEntry('', { home }), remaining: reg.hosts.length };
239
+
240
+ reg.hosts = reg.hosts.filter((h) => h.id !== target.id);
241
+ const nextActive = reg.hosts.length > 0 ? (reg.hosts.find((h) => h.id === reg.active) || reg.hosts[0]) : null;
242
+ reg.active = nextActive ? nextActive.id : '';
243
+
244
+ if (reg.hosts.length > 0) {
245
+ writeHostsRegistry(reg, { home });
246
+ writeHostConfig(nextActive, { home });
247
+ } else {
248
+ rmSync(hostsRegistryPath(home), { force: true });
249
+ removeHostConfig({ home });
250
+ }
251
+ return { removed: target, nextActive, remaining: reg.hosts.length };
252
+ }
253
+
56
254
  export function generateAdminKey() {
57
255
  return `adm_${randomBytes(16).toString('hex')}`;
58
256
  }
@@ -286,8 +484,18 @@ export async function deployToCloudflare({
286
484
  fetchFn = globalThis.fetch,
287
485
  log = console.log,
288
486
  } = {}) {
289
- const existing = readHostConfig({ home }) || {};
290
- const finalWorkerName = sanitizeWorkerName(workerName || existing.workerName || 'agy-family');
487
+ const reg = readHostsRegistry({ home });
488
+ const requestedWorker = workerName ? sanitizeWorkerName(workerName) : '';
489
+ const activeHost = resolveHostEntry('', { home });
490
+ const matchedHost = requestedWorker
491
+ ? reg.hosts.find(
492
+ (h) =>
493
+ (h.workerName && sanitizeWorkerName(h.workerName) === requestedWorker) ||
494
+ h.id === requestedWorker,
495
+ ) || null
496
+ : activeHost;
497
+ const existing = matchedHost || {};
498
+ const finalWorkerName = requestedWorker || sanitizeWorkerName(existing.workerName || 'agy-family');
291
499
  const finalDbName = String(
292
500
  databaseName || (existing.workerName === finalWorkerName ? existing.databaseName : '') || `${finalWorkerName}-db`,
293
501
  ).trim();
@@ -433,6 +641,8 @@ export async function deployToCloudflare({
433
641
  }
434
642
 
435
643
  const hostRecord = {
644
+ id: finalWorkerName,
645
+ name: finalWorkerName,
436
646
  provider: 'cloudflare',
437
647
  workerName: finalWorkerName,
438
648
  databaseName: finalDbName,
@@ -443,14 +653,15 @@ export async function deployToCloudflare({
443
653
  version,
444
654
  deployedAt: Date.now(),
445
655
  };
446
- const savedPath = writeHostConfig(hostRecord, { home });
656
+ const upserted = upsertHostEntry(hostRecord, { home, setActive: true });
447
657
 
448
658
  return {
449
659
  ok: true,
450
- ...hostRecord,
660
+ ...upserted.entry,
451
661
  secretUpdated: needSecretPut,
452
662
  pricingSync,
453
- hostConfigPath: savedPath,
663
+ hostConfigPath: upserted.hostConfigPath,
664
+ hostsRegistryPath: upserted.hostsRegistryPath,
454
665
  };
455
666
  } finally {
456
667
  rmSync(stageDir, { recursive: true, force: true });
@@ -83,7 +83,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
83
83
  export async function buildSyncPayload({
84
84
  deviceId,
85
85
  clientKind = 'cli',
86
- clientVersion = '0.6.0',
86
+ clientVersion = '0.6.1',
87
87
  home,
88
88
  roots = null,
89
89
  sourceFilter = 'all',
@@ -164,7 +164,7 @@ export async function buildSyncPayload({
164
164
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
165
165
  client: {
166
166
  kind: clientKind === 'extension' ? 'extension' : 'cli',
167
- version: String(clientVersion || '0.6.0').slice(0, 24),
167
+ version: String(clientVersion || '0.6.1').slice(0, 24),
168
168
  ...(platformLabel ? { platform: platformLabel } : {}),
169
169
  },
170
170
  account: {
@@ -26,7 +26,7 @@ import {
26
26
  import { FAVICON_SVG, renderDashboardHtml } from './ui.mjs';
27
27
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
28
28
 
29
- export const SERVER_VERSION = '0.6.0';
29
+ export const SERVER_VERSION = '0.6.1';
30
30
  const MAX_BUCKETS_PER_SYNC = 1000;
31
31
  const MAX_DEVICES_PER_MEMBER = 8;
32
32
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -1924,7 +1924,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity 家庭组' } = {
1924
1924
 
1925
1925
  <footer class="foot">
1926
1926
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1927
- <span class="mono">agy-family v0.6.0 · MIT</span>
1927
+ <span class="mono">agy-family v0.6.1 · MIT</span>
1928
1928
  </footer>
1929
1929
  </main>
1930
1930