agy-family 0.2.1 → 0.2.3

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
@@ -20,8 +20,8 @@ Google One (AI Pro / AI Ultra) family groups (1 family manager + up to 5 family
20
20
  `agy-family` solves this with an open-source, self-hosted, zero-privacy-leak architecture:
21
21
  1. **Desktop IDE Extension (`.vsix`) First + Lightweight CLI**: Members install the bilingual (`zh` / `en`) extension in Antigravity IDE (or VS Code), paste a one-line `agyfam://join?...` invite code (which also auto-carries optional board view keys), and are live in 30 seconds — **zero Node setup, zero terminal commands, zero Google OAuth**.
22
22
  2. **Auditable Privacy Guarantee + Live SQLite WAL Scanning**: Clients scan local `conversations/*.db` **plus active `.db-wal` transaction frames** strictly read-only, extracting **only numeric step metadata** (hour bucket, source, model, token counts, reference USD estimate). **Prompts, replies, file paths, session IDs, and Google credentials never leave the device.** Members can inspect the exact raw JSON payload anytime inside the IDE or via `agy-family audit`.
23
- 3. **Public Fair-Use Board + Drill-Down + CSV Settlement + Soft Cap Guardrails**: Normalizes mixed models (with conservative fallback estimation for newly launched models) into comparable API-equivalent USD, supports expandable per-member 7-day trends & model breakdowns, 1-click UTF-8 CSV export, a built-in **"How to Join"** modal, visible offline status in the IDE status bar, and separate **80% / 100%** daily/weekly/cycle reminders & deduped Webhook alerts (Feishu, DingTalk, WeCom, Telegram, Discord, or Generic JSON).
24
- 4. **Anti-Tamper Guardrails & Shared AI Credits Reconciliation**: Enforces a server-side **monotonic high-water mark (`MAX()`)** so reported usage can never be rolled back downward, tracks zero-PII local odometers (`dbFiles`, `allTimeSteps`, `allTimeTokens`) to flag local DB deletion, runs a **6-hour Cron offline check**, and flags **Unattributed Shared Credits Drops** alongside both **offline** and **online-but-$0 ("Ghost Online")** members.
23
+ 3. **Percentage-First Fair-Use Board + `/family` Zero-Token Command + CSV Settlement**: Evaluates members primarily by **usage percentage (`%`) vs. allocated family quota share (`%`)** (auto-equal split by default, or custom per-member `%`, plus optional monthly AI Pro `1,000` / AI Ultra `25,000` Credits pool progress), with API-equivalent USD (`$`) shown quietly as secondary reference; includes a zero-token `/family` slash command in both Antigravity IDE & `agy` CLI, expandable 7-day trends & cache hit efficiency, 1-click UTF-8 CSV export, and deduped Webhook alerts (Feishu, DingTalk, WeCom, Telegram, Discord, or Generic JSON).
24
+ 4. **Anti-Tamper Guardrails, Optional SHA-256 Family Email Binding & Shared AI Credits Reconciliation**: Optionally bind each member's Google Family email (**stored only as SHA-256 hash** — plaintext emails never leave the client or appear on `/api/board`) so switching to a personal/work Google account automatically excludes non-family deltas (`非家庭组号 · 免计`); enforces a server-side **monotonic high-water mark (`MAX()`)**, tracks zero-PII local odometers (`dbFiles`, `allTimeSteps`, `allTimeTokens`), runs a **6-hour Cron offline check**, and flags **Unattributed Shared Credits Drops** alongside **offline**, **non-family paused**, and **Ghost Online** members.
25
25
  5. **Free-Tier-Friendly Dual Self-Hosting**: Clients perform **delta-bucket sync** (`--full` optional), paired with **Cloudflare D1 `batch()` / SQLite transactional writes** and per-isolate schema caching — cutting Cloudflare D1 writes by **98%+** while running identically on **Cloudflare Workers + D1** or **Docker Compose (Node 22 + built-in SQLite)**.
26
26
 
27
27
  ---
package/README.zh-CN.md CHANGED
@@ -20,7 +20,7 @@ Google One(AI Pro / AI Ultra)家庭组(最多 6 人:1 位家庭组管理
20
20
  `agy-family` 用一套**纯开源、零隐私、30 秒上手**的方案解决这个问题:
21
21
  1. **桌面 IDE 插件(`.vsix`)为主,CLI 为辅**:家庭成员在 Antigravity IDE 安装扩展后,只需点击家庭组管理员发来的「一键拉起 IDE 链接」或粘贴 `agyfam://join?...` 邀请码即可上线(自动跟随中英文界面、自动携带可选查看密码),**无需装 Node、无需敲命令、无需登录 Google**。
22
22
  2. **严格隐私边界 + 实时 WAL 捕获(成员随时肉眼可查)**:客户端以只读模式解析本机 `conversations/*.db` 与实时 `.db-wal` 事务帧中的**数值统计字段**(小时时间桶、模型名、Token 计数、估算等值 API 美元),**绝不读取或上传任何 Prompt、回复正文、文件路径或账号凭据**;IDE 内置 **一键查看最近上报原始 JSON** 供随时审计。
23
- 3. **遵循 Google 家庭组规则的透明看板 + 约定上限提醒 + CSV 导出**:内置 **6 人上限(1 位家庭组管理员 + 最多 5 位家庭成员)**与月度账单重置周期;按模型参考单价(含新模型保守兜底估算)归一化成 **等值 API 花费 (`$`)** 公平对比;支持点击成员行展开三档进度、7 天走势与模型明细、一键导出 UTF-8 CSV 报表;IDE 右下角实时显示个人进度与掉线状态,日/周/周期上限达 **80% / 100%** 温和弹窗并推送飞书 / 钉钉 / 企微 / Telegram / Discord 群通知。
23
+ 3. **百分比优先的 Google 家庭组透明看板 + `/family` 零 Token 指令 + CSV 导出**:内置 **6 人上限(1 位家庭组管理员 + 最多 5 位家庭成员)**与月度账单重置周期;以**组内使用占比(`%`)与分配配额比例(`%`,留空自动均分,也支持自定义比例或 AI Pro `1,000` / AI Ultra `25,000` 共享总池比例追踪)**为核心,折算参考金额(`$`)与可选月费分摊仅作次要展示;支持在 IDE 与 `agy` CLI 对话框直接输入 `/family`(0 Token)、展开多窗口占比与缓存命中效率、一键导出 UTF-8 CSV 报表,以及飞书 / 钉钉 / 企微 / Telegram / Discord 群通知。
24
24
  4. **共享 AI Credits 总池对账(防篡改与离线巡检)**:家庭组管理员可在后台登记共享 AI Credits 余额并查看历史水位/审计流水,系统自动比对「共享池实际减少」与「家庭组同窗口上报消耗」,出现大额**未归因消耗(Unattributed)**立刻标红并列出期间离线或假在线 0 上报成员。
25
25
  5. **超省配额的双部署支持(零成本或自建)**:客户端默认**增量脏桶同步(Delta Sync)** + 服务端 **D1 `batch()` / SQLite 事务批量写入** + Worker isolate 建表缓存,将 Cloudflare D1 写入量压缩 **98%+**,轻松长驻 **Cloudflare Workers + D1 永久免费层** 或 **Docker 一键自部署**。
26
26
 
@@ -130,6 +130,7 @@ curl -fsSL https://raw.githubusercontent.com/xy-tuoren/agy-family/main/scripts/i
130
130
  | 会读取我的代码、聊天记录或文件路径吗? | **绝不**。仅以 `readOnly` 读取 `steps` 表中 `step_type = 15` 的数值元数据(时间、模型枚举、Token 计数),按小时桶聚合后丢弃全部会话 ID。 |
131
131
  | 会碰我的 Google 账号或 OAuth Token 吗? | **绝不**。客户端全程零 Google 登录、零钥匙串读取、零代理劫持。 |
132
132
  | 怎么确认没有偷偷上传别的东西? | 100% MIT 开源,且 IDE 扩展与 CLI 均内置 `Inspect Last Sync Payload` / `audit` 功能,发出前也可用 `--dry-run` 逐字节审查。 |
133
+ | 成员如果切到自己的非家庭组账号,会被算进家庭组吗? | **支持 SHA-256 邮箱指纹绑定 + 切其他号自动免计**。管理员添加/编辑成员时可选填其家庭组 Google 邮箱(服务端仅存 `SHA-256` 指纹与管理员自用脱敏提示,公开看板绝不暴露邮箱);客户端只读比对当前活跃账号 `SHA-256`,切其他号期间产生的增量自动写入本地排除偏移量并跳过上报(显示 `非家庭组号 · 免计`),切回家庭组号后精准续算。 |
133
134
  | 客户端数据能防止恶意篡改或关插件偷跑吗? | **四重防线**:① 服务端强制用可信单价重算 `$`;② **高水位单调锁(`MAX()`)**确保已上报用量永不允许被改小/回退,尝试回退立刻记入防篡改审计并群告警;③ **零隐私本地里程表**监测本机对话库异常删库;④ **定时离线巡检(6h Cron)+ 共享 AI Credits 总池对账**,出现未归因掉血时同时列出「期间离线」与「假在线 0 上报」成员。 |
134
135
 
135
136
  ---
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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",
7
7
  "bin": {
8
- "agy-family": "./packages/cli/bin/agy-family.mjs"
8
+ "agy-family": "packages/cli/bin/agy-family.mjs"
9
9
  },
10
10
  "files": [
11
11
  "packages/core/src/",
@@ -20,7 +20,7 @@
20
20
  "author": "xy-tuoren",
21
21
  "repository": {
22
22
  "type": "git",
23
- "url": "https://github.com/xy-tuoren/agy-family.git"
23
+ "url": "git+https://github.com/xy-tuoren/agy-family.git"
24
24
  },
25
25
  "bugs": {
26
26
  "url": "https://github.com/xy-tuoren/agy-family/issues"
@@ -8,9 +8,12 @@ import { fileURLToPath } from 'node:url';
8
8
  import {
9
9
  buildSyncPayload,
10
10
  decodeInviteInput,
11
+ extractEmailFromHookPayload,
11
12
  fetchBoardSummary,
12
13
  getOrCreateSharedDeviceId,
14
+ hashEmailSha256,
13
15
  pushSyncPayload,
16
+ writeActiveAccountCache,
14
17
  } from '../../core/src/index.mjs';
15
18
  import { startNodeServer } from '../../server-node/src/server.mjs';
16
19
  import {
@@ -24,7 +27,7 @@ import {
24
27
  uninstallBackgroundDaemon,
25
28
  } from '../src/hook.mjs';
26
29
 
27
- const CLI_VERSION = '0.2.1';
30
+ const CLI_VERSION = '0.2.3';
28
31
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
29
32
 
30
33
  function configBaseDir(home = homedir()) {
@@ -51,6 +54,10 @@ function syncedHashesPath(home = homedir()) {
51
54
  return join(configBaseDir(home), 'synced-hashes.json');
52
55
  }
53
56
 
57
+ function accountLedgerPath(home = homedir()) {
58
+ return join(configBaseDir(home), 'account-ledger.json');
59
+ }
60
+
54
61
  function writePrivateJson(filePath, obj) {
55
62
  mkdirSync(dirname(filePath), { recursive: true });
56
63
  writeFileSync(filePath, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
@@ -104,15 +111,18 @@ Privacy guarantee:
104
111
  async function runSyncOnce({ cfg, dryRun = false, fullSync = false, quiet = false, lookbackDays = 31, home = homedir() }) {
105
112
  const cache = fullSync ? null : readJsonSafe(scanCachePath(home));
106
113
  const prevHashes = dryRun || fullSync ? null : readJsonSafe(syncedHashesPath(home));
114
+ const prevLedger = readJsonSafe(accountLedgerPath(home));
107
115
  const deviceId = getOrCreateSharedDeviceId({ home, fallbackId: cfg.deviceId || '' });
108
116
 
109
- const { payload, scan, nextSyncedHashes, stats } = await buildSyncPayload({
117
+ const { payload, scan, nextSyncedHashes, nextAccountLedger, stats } = await buildSyncPayload({
110
118
  deviceId,
111
119
  clientKind: 'cli',
112
120
  clientVersion: CLI_VERSION,
113
121
  home,
114
122
  fileCache: cache,
115
123
  syncedHashes: prevHashes,
124
+ expectedEmailHash: cfg.expectedEmailHash || '',
125
+ accountLedger: prevLedger,
116
126
  fullSync: dryRun || fullSync,
117
127
  lookbackDays,
118
128
  });
@@ -126,7 +136,7 @@ async function runSyncOnce({ cfg, dryRun = false, fullSync = false, quiet = fals
126
136
  if (dryRun) {
127
137
  console.log(JSON.stringify(payload, null, 2));
128
138
  console.error(
129
- `\n[dry-run] Scanned ${scan.scannedDbs} updated + ${scan.cachedDbs} cached DBs -> ${payload.buckets.length} hourly buckets (nothing sent).`,
139
+ `\n[dry-run] Scanned ${scan.scannedDbs} updated + ${scan.cachedDbs} cached DBs -> ${payload.buckets.length} hourly buckets (account: ${stats.accountStatus}, nothing sent).`,
130
140
  );
131
141
  return null;
132
142
  }
@@ -135,35 +145,54 @@ async function runSyncOnce({ cfg, dryRun = false, fullSync = false, quiet = fals
135
145
  throw new Error('Not joined to any family group yet. Run: agy-family join <agyfam://join?...>');
136
146
  }
137
147
 
148
+ if (nextAccountLedger) {
149
+ writePrivateJson(accountLedgerPath(home), nextAccountLedger);
150
+ }
138
151
  writePrivateJson(lastPayloadPath(home), payload);
139
152
  const res = await pushSyncPayload({ url: cfg.url, token: cfg.token, payload });
140
153
  writePrivateJson(syncedHashesPath(home), nextSyncedHashes);
141
154
  writePrivateJson(lastResultPath(home), res);
142
155
 
143
- if (res?.member?.id && cfg.memberId !== res.member.id) {
144
- const updatedCfg = {
145
- ...cfg,
146
- deviceId,
147
- memberId: res.member.id,
148
- memberName: res.member.name || cfg.memberName || '',
149
- };
150
- writePrivateJson(clientConfigPath(home), updatedCfg);
156
+ if (res?.member) {
157
+ const serverExpected = res.member.expectedEmailHash || '';
158
+ if (
159
+ (res.member.id && cfg.memberId !== res.member.id) ||
160
+ (res.member.expectedEmailHash !== undefined && (cfg.expectedEmailHash || '') !== serverExpected)
161
+ ) {
162
+ const updatedCfg = {
163
+ ...cfg,
164
+ deviceId,
165
+ memberId: res.member.id || cfg.memberId,
166
+ memberName: res.member.name || cfg.memberName || '',
167
+ expectedEmailHash: serverExpected,
168
+ };
169
+ writePrivateJson(clientConfigPath(home), updatedCfg);
170
+ cfg.memberId = updatedCfg.memberId;
171
+ cfg.memberName = updatedCfg.memberName;
172
+ cfg.expectedEmailHash = updatedCfg.expectedEmailHash;
173
+ }
151
174
  }
152
175
 
153
176
  if (!quiet) {
154
177
  const m = res.member || {};
178
+ if (res.pausedByAccountMismatch || m.accountStatus === 'mismatch') {
179
+ console.log(
180
+ `⏸ Paused sync as "${m.name || cfg.memberName || 'member'}": active Google account does not match your bound family email (non-family usage excluded).`,
181
+ );
182
+ return res;
183
+ }
184
+ const acctNote = m.accountStatus === 'verified' ? ' [✓ family account]' : '';
155
185
  console.log(
156
- `✓ Synced ${res.acceptedBuckets}/${stats.totalBuckets} buckets (${payload.syncMode}) as "${m.name || cfg.memberName || 'member'}" ` +
157
- `· Today $${Number(m.dailyUsedUsd || 0).toFixed(2)} / $${Number(m.dailyCapUsd || 0).toFixed(2)} (${m.dailyPct ?? 0}%) ` +
158
- `· Family $${Number(res.pool?.todayUsd || 0).toFixed(2)}`,
186
+ `✓ Synced ${res.acceptedBuckets}/${stats.totalBuckets} buckets (${payload.syncMode}) as "${m.name || cfg.memberName || 'member'}"${acctNote} ` +
187
+ `· Today share ${m.sharePct ?? 0}% (quota ${m.quotaPct ?? 100}% · ref $${Number(m.dailyUsedUsd || 0).toFixed(2)})`,
159
188
  );
160
- if (m.capStatus === 'over') {
189
+ if (m.quotaStatus === 'over') {
161
190
  console.warn(
162
- `⚠ Agreed ${m.capReason || 'fair-use'} cap reached (daily ${m.dailyPct}% / weekly ${m.weeklyPct}% / cycle ${m.cyclePct}%).`,
191
+ `⚠ Usage share (${m.sharePct ?? 0}%) is above allocated family quota (${m.quotaPct ?? 100}%).`,
163
192
  );
164
- } else if (m.capStatus === 'warn') {
193
+ } else if (m.quotaStatus === 'warn') {
165
194
  console.warn(
166
- `! Approaching agreed ${m.capReason || 'fair-use'} cap (daily ${m.dailyPct}% / weekly ${m.weeklyPct}% / cycle ${m.cyclePct}%).`,
195
+ `! Usage share (${m.sharePct ?? 0}%) is approaching/exceeding allocated family quota (${m.quotaPct ?? 100}%).`,
167
196
  );
168
197
  }
169
198
  }
@@ -185,6 +214,11 @@ async function runHookCommand(eventArg) {
185
214
  return;
186
215
  }
187
216
  if (eventArg === 'stop') {
217
+ const hookEmail = extractEmailFromHookPayload(payload);
218
+ if (hookEmail) {
219
+ const h = hashEmailSha256(hookEmail);
220
+ if (h) writeActiveAccountCache(h, { home: homedir(), slot: 'cli', source: 'hook' });
221
+ }
188
222
  const response = handleStop({
189
223
  home: homedir(),
190
224
  executable: process.execPath,
@@ -237,10 +271,12 @@ async function main() {
237
271
  memberName: parsed.memberName || prev.memberName || '',
238
272
  boardTitle: parsed.boardTitle || prev.boardTitle || '',
239
273
  ...(parsed.viewKey ? { viewKey: parsed.viewKey } : {}),
274
+ ...(parsed.expectedEmailHash ? { expectedEmailHash: parsed.expectedEmailHash } : {}),
240
275
  joinedAt: Date.now(),
241
276
  };
242
277
  writePrivateJson(clientConfigPath(), next);
243
278
  rmSync(syncedHashesPath(), { force: true });
279
+ rmSync(accountLedgerPath(), { force: true });
244
280
  console.log(`✓ Saved invite for "${next.memberName || 'member'}" -> ${next.url}`);
245
281
 
246
282
  if (!noHook) {
@@ -360,14 +396,28 @@ async function main() {
360
396
  const kIdx = args.indexOf('--view-key');
361
397
  const viewKey = kIdx >= 0 ? args[kIdx + 1] || '' : cfg.viewKey || '';
362
398
  const board = await fetchBoardSummary({ url: cfg.url, viewKey, period });
399
+ const s = board.summary || {};
400
+ const headerExtra =
401
+ s.quotaMode === 'pool'
402
+ ? `Pool Used ${s.poolUsedPct ?? 0}% (${Number(s.poolTotalCredits || 0).toLocaleString()} Credits · ref $${Number(s.totalUsd || 0).toFixed(2)})`
403
+ : `Ref $${Number(s.totalUsd || 0).toFixed(2)}`;
363
404
  console.log(
364
- `${board.boardTitle} (${board.period}) — Total $${board.summary.totalUsd.toFixed(2)} · Online ${board.summary.onlineCount}/${board.summary.memberCount} (limit ${board.summary.maxMembers || 6})`,
405
+ `${board.boardTitle} (${board.period}) — Online ${s.onlineCount}/${s.memberCount} (limit ${s.maxMembers || 6}) · ${headerExtra}`,
365
406
  );
366
407
  for (const m of board.members || []) {
367
408
  const role = m.role === 'manager' ? ' [Mgr]' : '';
368
- const flag = m.capStatus === 'over' ? ' [OVER]' : m.capStatus === 'warn' ? ' [WARN]' : '';
409
+ const qStatus = m.quotaStatus || 'ok';
410
+ const flag = qStatus === 'over' ? ' [OVER SHARE]' : qStatus === 'warn' ? ' [ABOVE SHARE]' : '';
411
+ const acctFlag =
412
+ m.accountStatus === 'mismatch'
413
+ ? ' [non-family paused]'
414
+ : m.accountStatus === 'verified'
415
+ ? ' [✓ family acct]'
416
+ : '';
417
+ const shareStr = `${Number(m.sharePct || 0).toFixed(1)}%`.padStart(6);
418
+ const quotaStr = `quota ${Number(m.quotaPct ?? 100).toFixed(1)}%`.padEnd(13);
369
419
  console.log(
370
- ` ${(m.name + role).padEnd(18)} $${m.usedUsd.toFixed(2).padStart(7)} / $${m.capUsd.toFixed(2).padEnd(7)} (${String(m.capPct).padStart(5)}%) ${m.online ? 'online' : 'offline'}${flag}`,
420
+ ` ${(m.name + role).padEnd(18)} ${shareStr} (${quotaStr} · ref $${Number(m.usedUsd || 0).toFixed(2)}) ${m.online ? 'online' : 'offline'}${acctFlag}${flag}`,
371
421
  );
372
422
  }
373
423
  return;
@@ -376,6 +426,7 @@ async function main() {
376
426
  if (cmd === 'leave') {
377
427
  rmSync(clientConfigPath(), { force: true });
378
428
  rmSync(syncedHashesPath(), { force: true });
429
+ rmSync(accountLedgerPath(), { force: true });
379
430
  rmSync(lastResultPath(), { force: true });
380
431
  console.log('✓ Disconnected from family group and removed local invite token.');
381
432
  return;
@@ -386,6 +437,7 @@ async function main() {
386
437
  uninstallBackgroundDaemon();
387
438
  rmSync(clientConfigPath(), { force: true });
388
439
  rmSync(syncedHashesPath(), { force: true });
440
+ rmSync(accountLedgerPath(), { force: true });
389
441
  rmSync(lastResultPath(), { force: true });
390
442
  rmSync(scanCachePath(), { force: true });
391
443
  console.log('✓ Removed agy-family hook, /family skill, background daemon, and local credentials.');
@@ -13,9 +13,12 @@ import { pathToFileURL } from 'node:url';
13
13
  import {
14
14
  buildSyncPayload,
15
15
  decodeInviteInput,
16
+ extractEmailFromHookPayload,
16
17
  fetchBoardSummary,
17
18
  getOrCreateSharedDeviceId,
19
+ hashEmailSha256,
18
20
  pushSyncPayload,
21
+ writeActiveAccountCache,
19
22
  } from '../../core/src/index.mjs';
20
23
 
21
24
  export const FAMILY_HOOK_NAME = 'agy-family';
@@ -475,12 +478,17 @@ function boardLinkFromConfig(cfg) {
475
478
  function formatStatusMarkdown(board, cfg) {
476
479
  const periodLabel = { today: '今日', '7d': '近 7 天', cycle: '本周期', '30d': '近 30 天' }[board.period] || board.period;
477
480
  const s = board.summary || {};
481
+ const isPoolMode = s.quotaMode === 'pool';
482
+ const summaryLine = isPoolMode
483
+ ? `**家庭组总池进度**:已用 \`${s.poolUsedPct ?? 0}%\`(总池 \`${Number(s.poolTotalCredits || 0).toLocaleString()} Credits\` · 折算参考 \`${fmtUsd(s.totalUsd)}\`) · 在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人)`
484
+ : `**家庭组总览**:在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人) · 按百分比份额核算(折算参考 \`${fmtUsd(s.totalUsd)}\`)`;
485
+
478
486
  const lines = [
479
487
  `### ${board.boardTitle || 'Google 家庭组透明看板'} · ${periodLabel} *(0 tokens)*`,
480
488
  '',
481
- `**家庭组总计**:\`${fmtUsd(s.totalUsd)}\` / 合计上限 \`${fmtUsd(s.totalCapUsd)}\` · 在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人)`,
489
+ summaryLine,
482
490
  '',
483
- '| 家庭成员 | 状态 | 进度 | 等值消耗 | 占比 |',
491
+ '| 家庭成员 | 状态 | 分配份额与进度 | 使用占比 | 参考金额 |',
484
492
  '| :--- | :--- | :--- | ---: | ---: |',
485
493
  ];
486
494
 
@@ -489,9 +497,19 @@ function formatStatusMarkdown(board, cfg) {
489
497
  if (m.role === 'manager') badges.push('管理员');
490
498
  if (cfg?.memberId && m.id === cfg.memberId) badges.push('我');
491
499
  const nameStr = badges.length ? `**${m.name}** (${badges.join('·')})` : m.name;
492
- const statusStr = m.capStatus === 'over' ? '🔴 超限' : m.capStatus === 'warn' ? '🟡 预警' : m.online ? '🟢 在线' : '⚪ 离线';
493
- const progress = m.capUsd > 0 ? `\`${makeBar(m.capPct)}\` ${m.capPct}%` : '未设上限';
494
- lines.push(`| ${nameStr} | ${statusStr} | ${progress} | **${fmtUsd(m.usedUsd)}** / ${fmtUsd(m.capUsd)} | ${m.sharePct}% |`);
500
+ const qPct = m.quotaPct ?? (s.memberCount > 0 ? Math.round((100 / s.memberCount) * 10) / 10 : 100);
501
+ const qUsed = m.quotaUsedPct ?? (qPct > 0 ? Math.round(((m.sharePct || 0) / qPct) * 1000) / 10 : 0);
502
+ const qStatus = m.quotaStatus || 'ok';
503
+ const acctBadge =
504
+ m.accountStatus === 'mismatch'
505
+ ? ' · ⏸非家庭号免计'
506
+ : m.accountStatus === 'verified'
507
+ ? ' · ✓家庭组号'
508
+ : '';
509
+ const statusStr =
510
+ (qStatus === 'over' ? '🔴 超份额' : qStatus === 'warn' ? '🟡 偏高' : m.online ? '🟢 在线' : '⚪ 离线') + acctBadge;
511
+ const progress = `\`${makeBar(Math.min(100, qUsed))}\` 份额 ${qPct}%`;
512
+ lines.push(`| ${nameStr} | ${statusStr} | ${progress} | **${m.sharePct ?? 0}%** | ${fmtUsd(m.usedUsd)} |`);
495
513
  }
496
514
 
497
515
  const link = boardLinkFromConfig(cfg);
@@ -516,6 +534,12 @@ export async function handlePreInvocation(
516
534
  return {};
517
535
  }
518
536
 
537
+ const hookEmail = extractEmailFromHookPayload(payload);
538
+ if (hookEmail) {
539
+ const h = hashEmailSha256(hookEmail);
540
+ if (h) writeActiveAccountCache(h, { home, slot: 'cli', source: 'hook', now });
541
+ }
542
+
519
543
  const cfgPath = join(clientConfigDir(home), 'client.json');
520
544
  const lastResPath = join(clientConfigDir(home), 'last-result.json');
521
545
  const lastPayloadPath = join(clientConfigDir(home), 'last-payload.json');
@@ -523,17 +547,29 @@ export async function handlePreInvocation(
523
547
 
524
548
  const cmd = parseFamilySlashCommand(payload.lastUserInput);
525
549
 
526
- // Normal prompt (not a bare /family slash command): optionally inject a non-blocking gentle cap reminder.
550
+ // Normal prompt (not a bare /family slash command): optionally inject a non-blocking gentle quota/cap reminder.
527
551
  if (!cmd) {
528
552
  const cfg = readJsonSafe(cfgPath);
529
553
  const lastRes = readJsonSafe(lastResPath);
530
554
  const member = lastRes?.member;
531
- if (!cfg?.url || !member || member.capStatus !== 'over') return {};
555
+ const isQuotaOver = member?.quotaStatus === 'over';
556
+ const isLegacyCapOver = !member?.quotaStatus && member?.capStatus === 'over';
557
+ if (!cfg?.url || !member || (!isQuotaOver && !isLegacyCapOver)) return {};
532
558
  const prevRem = readJsonSafe(reminderPath);
533
559
  if (prevRem && now - Number(prevRem.sentAt || 0) < OVER_CAP_REMINDER_COOLDOWN_MS) {
534
560
  return {};
535
561
  }
536
562
  writeJsonAtomic(reminderPath, { sentAt: now }, 0o600);
563
+ const link = boardLinkFromConfig(cfg);
564
+ if (isQuotaOver) {
565
+ const detail =
566
+ member.quotaMode === 'pool'
567
+ ? `个人池份额已用 \`${member.quotaUsedPct}%\`(分配份额 \`${member.quotaPct}%\`)`
568
+ : `今日组内占比 \`${member.sharePct}%\`(分配份额 \`${member.quotaPct}%\`)`;
569
+ return buildGentleReminderResponse(
570
+ `> **agy-family 提醒**:你的家庭组配额已超出约定比例(${detail}),建议错峰或节流以照顾家庭组共享额度。输入 \`/family\` 查看详情${link ? ` · ${link}` : ''}。`,
571
+ );
572
+ }
537
573
  const reasonMap = { daily: '今日', weekly: '近 7 天', cycle: '本周期' };
538
574
  const scope = reasonMap[member.capReason] || '当前窗口';
539
575
  const used =
@@ -554,7 +590,6 @@ export async function handlePreInvocation(
554
590
  : member.capReason === 'cycle'
555
591
  ? member.cyclePct
556
592
  : member.dailyPct;
557
- const link = boardLinkFromConfig(cfg);
558
593
  return buildGentleReminderResponse(
559
594
  `> **agy-family 提醒**:你已达到${scope}约定上限(\`${fmtUsd(used)} / ${fmtUsd(cap)}\`,\`${pct}%\`),建议错峰或节流以照顾家庭组共享额度。输入 \`/family\` 查看详情${link ? ` · ${link}` : ''}。`,
560
595
  );
@@ -583,17 +618,22 @@ export async function handlePreInvocation(
583
618
  url: parsed.url,
584
619
  token: parsed.token,
585
620
  viewKey: parsed.viewKey || '',
621
+ expectedEmailHash: parsed.expectedEmailHash || '',
586
622
  memberName: parsed.memberName || '',
587
623
  boardTitle: parsed.boardTitle || '',
588
624
  joinedAt: now,
589
625
  };
590
626
  writeJsonAtomic(cfgPath, nextCfg, 0o600);
627
+ rmSync(join(clientConfigDir(home), 'account-ledger.json'), { force: true });
591
628
  const syncOut = syncRunner
592
629
  ? await syncRunner({ cfg: nextCfg, fullSync: true, home })
593
630
  : await runHeadlessSync({ cfg: nextCfg, fullSync: true, home, fetchFn });
594
631
  if (syncOut?.member?.id) {
595
632
  nextCfg.memberId = syncOut.member.id;
596
633
  nextCfg.memberName = syncOut.member.name || nextCfg.memberName;
634
+ if (syncOut.member.expectedEmailHash !== undefined) {
635
+ nextCfg.expectedEmailHash = syncOut.member.expectedEmailHash || '';
636
+ }
597
637
  writeJsonAtomic(cfgPath, nextCfg, 0o600);
598
638
  }
599
639
  return buildZeroTokenMarkdownResponse(
@@ -607,6 +647,7 @@ export async function handlePreInvocation(
607
647
  if (cmd.kind === 'leave') {
608
648
  if (existsSync(cfgPath)) rmSync(cfgPath, { force: true });
609
649
  if (existsSync(lastResPath)) rmSync(lastResPath, { force: true });
650
+ rmSync(join(clientConfigDir(home), 'account-ledger.json'), { force: true });
610
651
  return buildZeroTokenMarkdownResponse('✅ 已退出家庭组并清除本地邀请 Token(~/.config/agy-family/client.json)。');
611
652
  }
612
653
 
@@ -635,8 +676,14 @@ export async function handlePreInvocation(
635
676
  ? await syncRunner({ cfg, fullSync: cmd.fullSync, home })
636
677
  : await runHeadlessSync({ cfg, fullSync: cmd.fullSync, home, fetchFn });
637
678
  const m = res?.member || {};
679
+ if (res?.pausedByAccountMismatch || m.accountStatus === 'mismatch') {
680
+ return buildZeroTokenMarkdownResponse(
681
+ `⏸ **已切换至非家庭组 Google 账号**:本轮对话增量已自动排除免计,不会计入家庭组看板(切回家庭组绑定账号后自动恢复同步)。`,
682
+ );
683
+ }
684
+ const acctSuffix = m.accountStatus === 'verified' ? ' · `✓ 家庭组号`' : '';
638
685
  return buildZeroTokenMarkdownResponse(
639
- `✅ 同步完成(${cmd.fullSync ? '全量' : '增量'} \`${res?.acceptedBuckets ?? 0}\` 桶)· **${m.name || cfg.memberName || '本人'}** 今日 \`${fmtUsd(m.dailyUsedUsd)} / ${fmtUsd(m.dailyCapUsd)}\`(${m.dailyPct ?? 0}%)· 家庭组今日 \`${fmtUsd(res?.pool?.todayUsd)}\``,
686
+ `✅ 同步完成(${cmd.fullSync ? '全量' : '增量'} \`${res?.acceptedBuckets ?? 0}\` 桶)· **${m.name || cfg.memberName || '本人'}**${acctSuffix} 今日占比 \`${m.sharePct ?? 0}%\`(分配份额 \`${m.quotaPct ?? 100}%\` · 参考 \`${fmtUsd(m.dailyUsedUsd)}\`)`,
640
687
  );
641
688
  } catch (err) {
642
689
  return buildZeroTokenMarkdownResponse(`❌ 同步失败:${err?.message || err}`);
@@ -654,22 +701,27 @@ export async function handlePreInvocation(
654
701
 
655
702
  export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(), fetchFn = globalThis.fetch, lookbackDays = 31 } = {}) {
656
703
  const dir = clientConfigDir(home);
704
+ const cfgPath = join(dir, 'client.json');
657
705
  const scanCachePath = join(dir, 'scan-cache.json');
658
706
  const syncedHashesPath = join(dir, 'synced-hashes.json');
707
+ const accountLedgerPath = join(dir, 'account-ledger.json');
659
708
  const lastPayloadPath = join(dir, 'last-payload.json');
660
709
  const lastResPath = join(dir, 'last-result.json');
661
710
 
662
711
  const cache = fullSync ? null : readJsonSafe(scanCachePath);
663
712
  const prevHashes = fullSync ? null : readJsonSafe(syncedHashesPath);
713
+ const prevLedger = readJsonSafe(accountLedgerPath);
664
714
  const deviceId = getOrCreateSharedDeviceId({ home, fallbackId: cfg.deviceId });
665
715
 
666
- const { payload, scan, nextSyncedHashes } = await buildSyncPayload({
716
+ const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
667
717
  deviceId,
668
718
  clientKind: 'cli',
669
- clientVersion: '0.2.1',
719
+ clientVersion: '0.2.3',
670
720
  home,
671
721
  fileCache: cache,
672
722
  syncedHashes: prevHashes,
723
+ expectedEmailHash: cfg.expectedEmailHash || '',
724
+ accountLedger: prevLedger,
673
725
  fullSync,
674
726
  lookbackDays,
675
727
  });
@@ -677,11 +729,35 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
677
729
  throw new Error('Local SQLite reader unavailable (requires Node.js >= 22.13).');
678
730
  }
679
731
  writeJsonAtomic(scanCachePath, scan.nextCache, 0o600);
732
+ if (nextAccountLedger) {
733
+ writeJsonAtomic(accountLedgerPath, nextAccountLedger, 0o600);
734
+ }
680
735
  writeJsonAtomic(lastPayloadPath, payload, 0o600);
681
736
 
682
737
  const res = await pushSyncPayload({ url: cfg.url, token: cfg.token, payload, fetchFn });
683
738
  writeJsonAtomic(syncedHashesPath, nextSyncedHashes, 0o600);
684
739
  writeJsonAtomic(lastResPath, res, 0o600);
740
+
741
+ if (res?.member) {
742
+ const serverExpected = res.member.expectedEmailHash || '';
743
+ if (
744
+ (res.member.id && cfg.memberId !== res.member.id) ||
745
+ (res.member.expectedEmailHash !== undefined && (cfg.expectedEmailHash || '') !== serverExpected)
746
+ ) {
747
+ const existing = readJsonSafe(cfgPath) || cfg;
748
+ writeJsonAtomic(
749
+ cfgPath,
750
+ {
751
+ ...existing,
752
+ deviceId,
753
+ memberId: res.member.id || existing.memberId,
754
+ memberName: res.member.name || existing.memberName || '',
755
+ expectedEmailHash: serverExpected,
756
+ },
757
+ 0o600,
758
+ );
759
+ }
760
+ }
685
761
  return res;
686
762
  }
687
763