agy-family 0.2.1 → 0.2.2

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,7 +20,7 @@ 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).
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
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.
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
 
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
 
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
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"
@@ -24,7 +24,7 @@ import {
24
24
  uninstallBackgroundDaemon,
25
25
  } from '../src/hook.mjs';
26
26
 
27
- const CLI_VERSION = '0.2.1';
27
+ const CLI_VERSION = '0.2.2';
28
28
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
29
29
 
30
30
  function configBaseDir(home = homedir()) {
@@ -154,16 +154,15 @@ async function runSyncOnce({ cfg, dryRun = false, fullSync = false, quiet = fals
154
154
  const m = res.member || {};
155
155
  console.log(
156
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)}`,
157
+ `· Today share ${m.sharePct ?? 0}% (quota ${m.quotaPct ?? 100}% · ref $${Number(m.dailyUsedUsd || 0).toFixed(2)})`,
159
158
  );
160
- if (m.capStatus === 'over') {
159
+ if (m.quotaStatus === 'over') {
161
160
  console.warn(
162
- `⚠ Agreed ${m.capReason || 'fair-use'} cap reached (daily ${m.dailyPct}% / weekly ${m.weeklyPct}% / cycle ${m.cyclePct}%).`,
161
+ `⚠ Usage share (${m.sharePct ?? 0}%) is above allocated family quota (${m.quotaPct ?? 100}%).`,
163
162
  );
164
- } else if (m.capStatus === 'warn') {
163
+ } else if (m.quotaStatus === 'warn') {
165
164
  console.warn(
166
- `! Approaching agreed ${m.capReason || 'fair-use'} cap (daily ${m.dailyPct}% / weekly ${m.weeklyPct}% / cycle ${m.cyclePct}%).`,
165
+ `! Usage share (${m.sharePct ?? 0}%) is approaching/exceeding allocated family quota (${m.quotaPct ?? 100}%).`,
167
166
  );
168
167
  }
169
168
  }
@@ -360,14 +359,22 @@ async function main() {
360
359
  const kIdx = args.indexOf('--view-key');
361
360
  const viewKey = kIdx >= 0 ? args[kIdx + 1] || '' : cfg.viewKey || '';
362
361
  const board = await fetchBoardSummary({ url: cfg.url, viewKey, period });
362
+ const s = board.summary || {};
363
+ const headerExtra =
364
+ s.quotaMode === 'pool'
365
+ ? `Pool Used ${s.poolUsedPct ?? 0}% (${Number(s.poolTotalCredits || 0).toLocaleString()} Credits · ref $${Number(s.totalUsd || 0).toFixed(2)})`
366
+ : `Ref $${Number(s.totalUsd || 0).toFixed(2)}`;
363
367
  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})`,
368
+ `${board.boardTitle} (${board.period}) — Online ${s.onlineCount}/${s.memberCount} (limit ${s.maxMembers || 6}) · ${headerExtra}`,
365
369
  );
366
370
  for (const m of board.members || []) {
367
371
  const role = m.role === 'manager' ? ' [Mgr]' : '';
368
- const flag = m.capStatus === 'over' ? ' [OVER]' : m.capStatus === 'warn' ? ' [WARN]' : '';
372
+ const qStatus = m.quotaStatus || 'ok';
373
+ const flag = qStatus === 'over' ? ' [OVER SHARE]' : qStatus === 'warn' ? ' [ABOVE SHARE]' : '';
374
+ const shareStr = `${Number(m.sharePct || 0).toFixed(1)}%`.padStart(6);
375
+ const quotaStr = `quota ${Number(m.quotaPct ?? 100).toFixed(1)}%`.padEnd(13);
369
376
  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}`,
377
+ ` ${(m.name + role).padEnd(18)} ${shareStr} (${quotaStr} · ref $${Number(m.usedUsd || 0).toFixed(2)}) ${m.online ? 'online' : 'offline'}${flag}`,
371
378
  );
372
379
  }
373
380
  return;
@@ -475,12 +475,17 @@ function boardLinkFromConfig(cfg) {
475
475
  function formatStatusMarkdown(board, cfg) {
476
476
  const periodLabel = { today: '今日', '7d': '近 7 天', cycle: '本周期', '30d': '近 30 天' }[board.period] || board.period;
477
477
  const s = board.summary || {};
478
+ const isPoolMode = s.quotaMode === 'pool';
479
+ const summaryLine = isPoolMode
480
+ ? `**家庭组总池进度**:已用 \`${s.poolUsedPct ?? 0}%\`(总池 \`${Number(s.poolTotalCredits || 0).toLocaleString()} Credits\` · 折算参考 \`${fmtUsd(s.totalUsd)}\`) · 在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人)`
481
+ : `**家庭组总览**:在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人) · 按百分比份额核算(折算参考 \`${fmtUsd(s.totalUsd)}\`)`;
482
+
478
483
  const lines = [
479
484
  `### ${board.boardTitle || 'Google 家庭组透明看板'} · ${periodLabel} *(0 tokens)*`,
480
485
  '',
481
- `**家庭组总计**:\`${fmtUsd(s.totalUsd)}\` / 合计上限 \`${fmtUsd(s.totalCapUsd)}\` · 在线 \`${s.onlineCount}/${s.memberCount}\`(上限 ${s.maxMembers || 6} 人)`,
486
+ summaryLine,
482
487
  '',
483
- '| 家庭成员 | 状态 | 进度 | 等值消耗 | 占比 |',
488
+ '| 家庭成员 | 状态 | 分配份额与进度 | 使用占比 | 参考金额 |',
484
489
  '| :--- | :--- | :--- | ---: | ---: |',
485
490
  ];
486
491
 
@@ -489,9 +494,12 @@ function formatStatusMarkdown(board, cfg) {
489
494
  if (m.role === 'manager') badges.push('管理员');
490
495
  if (cfg?.memberId && m.id === cfg.memberId) badges.push('我');
491
496
  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}% |`);
497
+ const qPct = m.quotaPct ?? (s.memberCount > 0 ? Math.round((100 / s.memberCount) * 10) / 10 : 100);
498
+ const qUsed = m.quotaUsedPct ?? (qPct > 0 ? Math.round(((m.sharePct || 0) / qPct) * 1000) / 10 : 0);
499
+ const qStatus = m.quotaStatus || 'ok';
500
+ const statusStr = qStatus === 'over' ? '🔴 超份额' : qStatus === 'warn' ? '🟡 偏高' : m.online ? '🟢 在线' : '⚪ 离线';
501
+ const progress = `\`${makeBar(Math.min(100, qUsed))}\` 份额 ${qPct}%`;
502
+ lines.push(`| ${nameStr} | ${statusStr} | ${progress} | **${m.sharePct ?? 0}%** | ${fmtUsd(m.usedUsd)} |`);
495
503
  }
496
504
 
497
505
  const link = boardLinkFromConfig(cfg);
@@ -523,17 +531,29 @@ export async function handlePreInvocation(
523
531
 
524
532
  const cmd = parseFamilySlashCommand(payload.lastUserInput);
525
533
 
526
- // Normal prompt (not a bare /family slash command): optionally inject a non-blocking gentle cap reminder.
534
+ // Normal prompt (not a bare /family slash command): optionally inject a non-blocking gentle quota/cap reminder.
527
535
  if (!cmd) {
528
536
  const cfg = readJsonSafe(cfgPath);
529
537
  const lastRes = readJsonSafe(lastResPath);
530
538
  const member = lastRes?.member;
531
- if (!cfg?.url || !member || member.capStatus !== 'over') return {};
539
+ const isQuotaOver = member?.quotaStatus === 'over';
540
+ const isLegacyCapOver = !member?.quotaStatus && member?.capStatus === 'over';
541
+ if (!cfg?.url || !member || (!isQuotaOver && !isLegacyCapOver)) return {};
532
542
  const prevRem = readJsonSafe(reminderPath);
533
543
  if (prevRem && now - Number(prevRem.sentAt || 0) < OVER_CAP_REMINDER_COOLDOWN_MS) {
534
544
  return {};
535
545
  }
536
546
  writeJsonAtomic(reminderPath, { sentAt: now }, 0o600);
547
+ const link = boardLinkFromConfig(cfg);
548
+ if (isQuotaOver) {
549
+ const detail =
550
+ member.quotaMode === 'pool'
551
+ ? `个人池份额已用 \`${member.quotaUsedPct}%\`(分配份额 \`${member.quotaPct}%\`)`
552
+ : `今日组内占比 \`${member.sharePct}%\`(分配份额 \`${member.quotaPct}%\`)`;
553
+ return buildGentleReminderResponse(
554
+ `> **agy-family 提醒**:你的家庭组配额已超出约定比例(${detail}),建议错峰或节流以照顾家庭组共享额度。输入 \`/family\` 查看详情${link ? ` · ${link}` : ''}。`,
555
+ );
556
+ }
537
557
  const reasonMap = { daily: '今日', weekly: '近 7 天', cycle: '本周期' };
538
558
  const scope = reasonMap[member.capReason] || '当前窗口';
539
559
  const used =
@@ -554,7 +574,6 @@ export async function handlePreInvocation(
554
574
  : member.capReason === 'cycle'
555
575
  ? member.cyclePct
556
576
  : member.dailyPct;
557
- const link = boardLinkFromConfig(cfg);
558
577
  return buildGentleReminderResponse(
559
578
  `> **agy-family 提醒**:你已达到${scope}约定上限(\`${fmtUsd(used)} / ${fmtUsd(cap)}\`,\`${pct}%\`),建议错峰或节流以照顾家庭组共享额度。输入 \`/family\` 查看详情${link ? ` · ${link}` : ''}。`,
560
579
  );
@@ -636,7 +655,7 @@ export async function handlePreInvocation(
636
655
  : await runHeadlessSync({ cfg, fullSync: cmd.fullSync, home, fetchFn });
637
656
  const m = res?.member || {};
638
657
  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)}\``,
658
+ `✅ 同步完成(${cmd.fullSync ? '全量' : '增量'} \`${res?.acceptedBuckets ?? 0}\` 桶)· **${m.name || cfg.memberName || '本人'}** 今日占比 \`${m.sharePct ?? 0}%\`(分配份额 \`${m.quotaPct ?? 100}%\` · 参考 \`${fmtUsd(m.dailyUsedUsd)}\`)`,
640
659
  );
641
660
  } catch (err) {
642
661
  return buildZeroTokenMarkdownResponse(`❌ 同步失败:${err?.message || err}`);
@@ -666,7 +685,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
666
685
  const { payload, scan, nextSyncedHashes } = await buildSyncPayload({
667
686
  deviceId,
668
687
  clientKind: 'cli',
669
- clientVersion: '0.2.1',
688
+ clientVersion: '0.2.2',
670
689
  home,
671
690
  fileCache: cache,
672
691
  syncedHashes: prevHashes,
@@ -77,7 +77,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
77
77
  export async function buildSyncPayload({
78
78
  deviceId,
79
79
  clientKind = 'cli',
80
- clientVersion = '0.2.1',
80
+ clientVersion = '0.2.2',
81
81
  home,
82
82
  roots = null,
83
83
  sourceFilter = 'all',
@@ -101,7 +101,7 @@ export async function buildSyncPayload({
101
101
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
102
102
  client: {
103
103
  kind: clientKind === 'extension' ? 'extension' : 'cli',
104
- version: String(clientVersion || '0.2.1').slice(0, 24),
104
+ version: String(clientVersion || '0.2.2').slice(0, 24),
105
105
  },
106
106
  syncedAt: now,
107
107
  lookbackDays: Math.max(1, Number(lookbackDays) || DEFAULT_LOOKBACK_DAYS),
@@ -12,14 +12,16 @@ import {
12
12
  checkOfflineMembersAndAlert,
13
13
  computeCreditsReconciliation,
14
14
  computeMemberCapsSnapshot,
15
+ evaluateQuotaProgress,
15
16
  getPeriodWindow,
16
17
  loadSettings,
18
+ resolveFamilyQuotas,
17
19
  roundUsd,
18
20
  } from './stats.mjs';
19
21
  import { renderDashboardHtml } from './ui.mjs';
20
22
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
21
23
 
22
- export const SERVER_VERSION = '0.2.1';
24
+ export const SERVER_VERSION = '0.2.2';
23
25
  const MAX_BUCKETS_PER_SYNC = 1000;
24
26
  const MAX_DEVICES_PER_MEMBER = 8;
25
27
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -35,6 +37,7 @@ const ALLOWED_SETTINGS_KEYS = new Set([
35
37
  'offlineAlertHours',
36
38
  'timezoneOffsetMin',
37
39
  'creditsPerUsd',
40
+ 'poolTotalCredits',
38
41
  'monthlyPlanCost',
39
42
  'monthlyPlanCurrency',
40
43
  'webhookUrl',
@@ -42,6 +45,13 @@ const ALLOWED_SETTINGS_KEYS = new Set([
42
45
  'boardViewKey',
43
46
  ]);
44
47
 
48
+ function parseQuotaPctInput(val) {
49
+ if (val === null || val === undefined || val === '') return null;
50
+ const n = Number(val);
51
+ if (!Number.isFinite(n) || n <= 0) return null;
52
+ return Math.min(100, Math.round(n * 10) / 10);
53
+ }
54
+
45
55
  class HttpError extends Error {
46
56
  constructor(status, message) {
47
57
  super(message);
@@ -645,6 +655,31 @@ export function createApp({
645
655
  }
646
656
 
647
657
  const todayBoard = await buildBoardPayload(db, { period: 'today', envDefaults, now });
658
+ const todayMember = (todayBoard.members || []).find((m) => m.id === member.id) || null;
659
+
660
+ // Fire deduped percentage-quota alert when percentage pool / custom quota is configured
661
+ if (
662
+ todayMember &&
663
+ (todayMember.quotaStatus === 'over' || todayMember.quotaStatus === 'warn') &&
664
+ (Number(settings.poolTotalCredits) > 0 || (member.quota_pct !== null && member.quota_pct !== undefined))
665
+ ) {
666
+ const isOver = todayMember.quotaStatus === 'over';
667
+ const modeLabel =
668
+ todayBoard.summary.quotaMode === 'pool'
669
+ ? `已用个人池份额 ${todayMember.quotaUsedPct}%(占总池 ${todayMember.poolUsedPct}% / 分配份额 ${todayMember.quotaPct}%)`
670
+ : `组内实际占比 ${todayMember.sharePct}%(分配份额 ${todayMember.quotaPct}%,相对进度 ${todayMember.quotaUsedPct}%)`;
671
+ await sendDedupedAlert({
672
+ db,
673
+ alertKey: `quota:today:${member.id}:${capSnap.dateKey}:${todayMember.quotaStatus}`,
674
+ kind: `quota.today.${todayMember.quotaStatus}`,
675
+ title: `[${settings.boardTitle}] 家庭成员配额比例${isOver ? '超出' : '预警'}`,
676
+ message: `${member.name} 今日${modeLabel}`,
677
+ settings,
678
+ payload: { memberName: member.name, quotaMode: todayBoard.summary.quotaMode, ...todayMember },
679
+ now,
680
+ fetchFn,
681
+ });
682
+ }
648
683
 
649
684
  return jsonRes({
650
685
  ok: true,
@@ -656,9 +691,19 @@ export function createApp({
656
691
  member: {
657
692
  id: member.id,
658
693
  name: member.name,
694
+ quotaMode: todayBoard.summary.quotaMode,
695
+ quotaPct: todayMember ? todayMember.quotaPct : null,
696
+ isAutoQuota: todayMember ? todayMember.isAutoQuota : true,
697
+ sharePct: todayMember ? todayMember.sharePct : 0,
698
+ poolUsedPct: todayMember ? todayMember.poolUsedPct : 0,
699
+ quotaUsedPct: todayMember ? todayMember.quotaUsedPct : 0,
700
+ quotaStatus: todayMember ? todayMember.quotaStatus : 'ok',
659
701
  ...capSnap,
660
702
  },
661
703
  pool: {
704
+ quotaMode: todayBoard.summary.quotaMode,
705
+ poolTotalCredits: todayBoard.summary.poolTotalCredits,
706
+ poolUsedPct: todayBoard.summary.poolUsedPct,
662
707
  todayUsd: todayBoard.summary.totalUsd,
663
708
  todayCapUsd: todayBoard.summary.totalCapUsd,
664
709
  onlineCount: todayBoard.summary.onlineCount,
@@ -674,9 +719,18 @@ export function createApp({
674
719
 
675
720
  if (request.method === 'GET' && path === '/api/admin/overview') {
676
721
  const settings = await loadSettings(db, envDefaults);
677
- const members = await db.all(
678
- 'SELECT id, name, role, color, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at, last_seen_at, last_client_kind, last_client_version FROM members ORDER BY CASE WHEN role = \'manager\' THEN 0 ELSE 1 END, created_at ASC',
722
+ const membersRows = await db.all(
723
+ "SELECT id, name, role, color, quota_pct, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at, last_seen_at, last_client_kind, last_client_version FROM members ORDER BY CASE WHEN role = 'manager' THEN 0 ELSE 1 END, created_at ASC",
679
724
  );
725
+ const resolvedQuotas = resolveFamilyQuotas((membersRows || []).filter((m) => m.active));
726
+ const members = (membersRows || []).map((m) => {
727
+ const q = resolvedQuotas.get(m.id);
728
+ return {
729
+ ...m,
730
+ effective_quota_pct: q ? q.quotaPct : 0,
731
+ is_auto_quota: q ? q.isAutoQuota : m.quota_pct === null || m.quota_pct === undefined,
732
+ };
733
+ });
680
734
  const snapshots = await db.all(
681
735
  'SELECT id, balance, note, recorded_at FROM credit_snapshots ORDER BY recorded_at DESC LIMIT 20',
682
736
  );
@@ -711,6 +765,7 @@ export function createApp({
711
765
  if (!name) return adminJsonRes({ error: 'Member name is required.' }, 400);
712
766
  const role = body.role === 'manager' ? 'manager' : 'member';
713
767
  const color = /^#[0-9a-fA-F]{6}$/.test(String(body.color || '')) ? body.color : '#2383e2';
768
+ const quotaPct = parseQuotaPctInput(body.quotaPct);
714
769
  const dailyCap = body.dailyCapUsd === null || body.dailyCapUsd === undefined ? null : Math.max(0, Number(body.dailyCapUsd));
715
770
  const weeklyCap = body.weeklyCapUsd === null || body.weeklyCapUsd === undefined ? null : Math.max(0, Number(body.weeklyCapUsd));
716
771
  const cycleCap = body.cycleCapUsd === null || body.cycleCapUsd === undefined ? null : Math.max(0, Number(body.cycleCapUsd));
@@ -728,9 +783,9 @@ export function createApp({
728
783
  });
729
784
  }
730
785
  stmts.push({
731
- sql: `INSERT INTO members (id, name, role, color, token_hash, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at)
732
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
733
- params: [id, name, role, color, tokenHash, dailyCap, weeklyCap, cycleCap, now],
786
+ sql: `INSERT INTO members (id, name, role, color, token_hash, quota_pct, daily_cap_usd, weekly_cap_usd, cycle_cap_usd, active, created_at)
787
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
788
+ params: [id, name, role, color, tokenHash, quotaPct, dailyCap, weeklyCap, cycleCap, now],
734
789
  });
735
790
  await runBatchedWrites(db, stmts);
736
791
 
@@ -747,7 +802,7 @@ export function createApp({
747
802
  return adminJsonRes(
748
803
  {
749
804
  ok: true,
750
- member: { id, name, role, color, dailyCapUsd: dailyCap, weeklyCapUsd: weeklyCap, cycleCapUsd: cycleCap },
805
+ member: { id, name, role, color, quotaPct, dailyCapUsd: dailyCap, weeklyCapUsd: weeklyCap, cycleCapUsd: cycleCap },
751
806
  token,
752
807
  inviteUri,
753
808
  },
@@ -795,6 +850,7 @@ export function createApp({
795
850
  : 'member';
796
851
  const nextColor =
797
852
  body.color !== undefined && /^#[0-9a-fA-F]{6}$/.test(String(body.color)) ? body.color : existing.color;
853
+ const nextQuotaPct = body.quotaPct === undefined ? existing.quota_pct : parseQuotaPctInput(body.quotaPct);
798
854
  const nextDaily = body.dailyCapUsd === undefined ? existing.daily_cap_usd : body.dailyCapUsd === null ? null : Math.max(0, Number(body.dailyCapUsd));
799
855
  const nextWeekly = body.weeklyCapUsd === undefined ? existing.weekly_cap_usd : body.weeklyCapUsd === null ? null : Math.max(0, Number(body.weeklyCapUsd));
800
856
  const nextCycle = body.cycleCapUsd === undefined ? existing.cycle_cap_usd : body.cycleCapUsd === null ? null : Math.max(0, Number(body.cycleCapUsd));
@@ -808,11 +864,11 @@ export function createApp({
808
864
  });
809
865
  }
810
866
  stmts.push({
811
- sql: 'UPDATE members SET name = ?, role = ?, color = ?, daily_cap_usd = ?, weekly_cap_usd = ?, cycle_cap_usd = ?, active = ? WHERE id = ?',
812
- params: [nextName, nextRole, nextColor, nextDaily, nextWeekly, nextCycle, nextActive, id],
867
+ sql: 'UPDATE members SET name = ?, role = ?, color = ?, quota_pct = ?, daily_cap_usd = ?, weekly_cap_usd = ?, cycle_cap_usd = ?, active = ? WHERE id = ?',
868
+ params: [nextName, nextRole, nextColor, nextQuotaPct, nextDaily, nextWeekly, nextCycle, nextActive, id],
813
869
  });
814
870
  await runBatchedWrites(db, stmts);
815
- return adminJsonRes({ ok: true, id, name: nextName, role: nextRole, active: Boolean(nextActive) });
871
+ return adminJsonRes({ ok: true, id, name: nextName, role: nextRole, quotaPct: nextQuotaPct, active: Boolean(nextActive) });
816
872
  }
817
873
 
818
874
  if (request.method === 'DELETE') {
@@ -833,6 +889,10 @@ export function createApp({
833
889
  if (!check.ok) return adminJsonRes({ error: check.error }, 400);
834
890
  body.webhookUrl = check.url;
835
891
  }
892
+ if (body && body.poolTotalCredits !== undefined) {
893
+ const n = Number(body.poolTotalCredits);
894
+ body.poolTotalCredits = Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
895
+ }
836
896
  if (body && body.monthlyPlanCost !== undefined) {
837
897
  const n = Number(body.monthlyPlanCost);
838
898
  body.monthlyPlanCost = Number.isFinite(n) && n > 0 ? Math.round(n * 100) / 100 : 0;
@@ -939,4 +999,4 @@ export function createApp({
939
999
  };
940
1000
  }
941
1001
 
942
- export { checkOfflineMembersAndAlert, getPeriodWindow };
1002
+ export { checkOfflineMembersAndAlert, evaluateQuotaProgress, getPeriodWindow, resolveFamilyQuotas };
@@ -16,6 +16,7 @@ export const SCHEMA_STATEMENTS = Object.freeze([
16
16
  role TEXT NOT NULL DEFAULT 'member',
17
17
  color TEXT NOT NULL DEFAULT '#2383e2',
18
18
  token_hash TEXT NOT NULL UNIQUE,
19
+ quota_pct REAL,
19
20
  daily_cap_usd REAL,
20
21
  weekly_cap_usd REAL,
21
22
  cycle_cap_usd REAL,
@@ -92,6 +93,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
92
93
  offlineAlertHours: 48,
93
94
  timezoneOffsetMin: 480,
94
95
  creditsPerUsd: 100,
96
+ poolTotalCredits: 0,
95
97
  monthlyPlanCost: 0,
96
98
  monthlyPlanCurrency: 'USD',
97
99
  webhookUrl: '',
@@ -103,10 +105,15 @@ export async function ensureSchema(db) {
103
105
  for (const sql of SCHEMA_STATEMENTS) {
104
106
  await db.run(sql);
105
107
  }
106
- // Idempotent column migration for existing SQLite / D1 databases created prior to family role support.
108
+ // Idempotent column migrations for existing SQLite / D1 databases.
107
109
  try {
108
110
  await db.run("ALTER TABLE members ADD COLUMN role TEXT NOT NULL DEFAULT 'member'");
109
111
  } catch {
110
112
  // Column already exists.
111
113
  }
114
+ try {
115
+ await db.run('ALTER TABLE members ADD COLUMN quota_pct REAL');
116
+ } catch {
117
+ // Column already exists.
118
+ }
112
119
  }