agy-family 0.2.2 → 0.2.4
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 +1 -1
- package/README.zh-CN.md +1 -0
- package/package.json +1 -1
- package/packages/cli/bin/agy-family.mjs +58 -13
- package/packages/cli/src/hook.mjs +61 -4
- package/packages/core/src/account.mjs +534 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/core/src/invite.mjs +20 -1
- package/packages/core/src/sync.mjs +70 -5
- package/packages/server-core/src/index.mjs +145 -17
- package/packages/server-core/src/schema.mjs +17 -1
- package/packages/server-core/src/stats.mjs +25 -3
- package/packages/server-core/src/ui.mjs +1209 -1156
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ Google One (AI Pro / AI Ultra) family groups (1 family manager + up to 5 family
|
|
|
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
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 & Shared AI Credits Reconciliation**:
|
|
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
|
@@ -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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-family",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
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",
|
|
@@ -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.
|
|
30
|
+
const CLI_VERSION = '0.2.4';
|
|
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,25 +145,45 @@ 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
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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'}" ` +
|
|
186
|
+
`✓ Synced ${res.acceptedBuckets}/${stats.totalBuckets} buckets (${payload.syncMode}) as "${m.name || cfg.memberName || 'member'}"${acctNote} ` +
|
|
157
187
|
`· Today share ${m.sharePct ?? 0}% (quota ${m.quotaPct ?? 100}% · ref $${Number(m.dailyUsedUsd || 0).toFixed(2)})`,
|
|
158
188
|
);
|
|
159
189
|
if (m.quotaStatus === 'over') {
|
|
@@ -184,6 +214,11 @@ async function runHookCommand(eventArg) {
|
|
|
184
214
|
return;
|
|
185
215
|
}
|
|
186
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
|
+
}
|
|
187
222
|
const response = handleStop({
|
|
188
223
|
home: homedir(),
|
|
189
224
|
executable: process.execPath,
|
|
@@ -236,10 +271,12 @@ async function main() {
|
|
|
236
271
|
memberName: parsed.memberName || prev.memberName || '',
|
|
237
272
|
boardTitle: parsed.boardTitle || prev.boardTitle || '',
|
|
238
273
|
...(parsed.viewKey ? { viewKey: parsed.viewKey } : {}),
|
|
274
|
+
...(parsed.expectedEmailHash ? { expectedEmailHash: parsed.expectedEmailHash } : {}),
|
|
239
275
|
joinedAt: Date.now(),
|
|
240
276
|
};
|
|
241
277
|
writePrivateJson(clientConfigPath(), next);
|
|
242
278
|
rmSync(syncedHashesPath(), { force: true });
|
|
279
|
+
rmSync(accountLedgerPath(), { force: true });
|
|
243
280
|
console.log(`✓ Saved invite for "${next.memberName || 'member'}" -> ${next.url}`);
|
|
244
281
|
|
|
245
282
|
if (!noHook) {
|
|
@@ -371,10 +408,16 @@ async function main() {
|
|
|
371
408
|
const role = m.role === 'manager' ? ' [Mgr]' : '';
|
|
372
409
|
const qStatus = m.quotaStatus || 'ok';
|
|
373
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
|
+
: '';
|
|
374
417
|
const shareStr = `${Number(m.sharePct || 0).toFixed(1)}%`.padStart(6);
|
|
375
418
|
const quotaStr = `quota ${Number(m.quotaPct ?? 100).toFixed(1)}%`.padEnd(13);
|
|
376
419
|
console.log(
|
|
377
|
-
` ${(m.name + role).padEnd(18)} ${shareStr} (${quotaStr} · ref $${Number(m.usedUsd || 0).toFixed(2)}) ${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}`,
|
|
378
421
|
);
|
|
379
422
|
}
|
|
380
423
|
return;
|
|
@@ -383,6 +426,7 @@ async function main() {
|
|
|
383
426
|
if (cmd === 'leave') {
|
|
384
427
|
rmSync(clientConfigPath(), { force: true });
|
|
385
428
|
rmSync(syncedHashesPath(), { force: true });
|
|
429
|
+
rmSync(accountLedgerPath(), { force: true });
|
|
386
430
|
rmSync(lastResultPath(), { force: true });
|
|
387
431
|
console.log('✓ Disconnected from family group and removed local invite token.');
|
|
388
432
|
return;
|
|
@@ -393,6 +437,7 @@ async function main() {
|
|
|
393
437
|
uninstallBackgroundDaemon();
|
|
394
438
|
rmSync(clientConfigPath(), { force: true });
|
|
395
439
|
rmSync(syncedHashesPath(), { force: true });
|
|
440
|
+
rmSync(accountLedgerPath(), { force: true });
|
|
396
441
|
rmSync(lastResultPath(), { force: true });
|
|
397
442
|
rmSync(scanCachePath(), { force: true });
|
|
398
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';
|
|
@@ -497,7 +500,14 @@ function formatStatusMarkdown(board, cfg) {
|
|
|
497
500
|
const qPct = m.quotaPct ?? (s.memberCount > 0 ? Math.round((100 / s.memberCount) * 10) / 10 : 100);
|
|
498
501
|
const qUsed = m.quotaUsedPct ?? (qPct > 0 ? Math.round(((m.sharePct || 0) / qPct) * 1000) / 10 : 0);
|
|
499
502
|
const qStatus = m.quotaStatus || 'ok';
|
|
500
|
-
const
|
|
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;
|
|
501
511
|
const progress = `\`${makeBar(Math.min(100, qUsed))}\` 份额 ${qPct}%`;
|
|
502
512
|
lines.push(`| ${nameStr} | ${statusStr} | ${progress} | **${m.sharePct ?? 0}%** | ${fmtUsd(m.usedUsd)} |`);
|
|
503
513
|
}
|
|
@@ -524,6 +534,12 @@ export async function handlePreInvocation(
|
|
|
524
534
|
return {};
|
|
525
535
|
}
|
|
526
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
|
+
|
|
527
543
|
const cfgPath = join(clientConfigDir(home), 'client.json');
|
|
528
544
|
const lastResPath = join(clientConfigDir(home), 'last-result.json');
|
|
529
545
|
const lastPayloadPath = join(clientConfigDir(home), 'last-payload.json');
|
|
@@ -602,17 +618,22 @@ export async function handlePreInvocation(
|
|
|
602
618
|
url: parsed.url,
|
|
603
619
|
token: parsed.token,
|
|
604
620
|
viewKey: parsed.viewKey || '',
|
|
621
|
+
expectedEmailHash: parsed.expectedEmailHash || '',
|
|
605
622
|
memberName: parsed.memberName || '',
|
|
606
623
|
boardTitle: parsed.boardTitle || '',
|
|
607
624
|
joinedAt: now,
|
|
608
625
|
};
|
|
609
626
|
writeJsonAtomic(cfgPath, nextCfg, 0o600);
|
|
627
|
+
rmSync(join(clientConfigDir(home), 'account-ledger.json'), { force: true });
|
|
610
628
|
const syncOut = syncRunner
|
|
611
629
|
? await syncRunner({ cfg: nextCfg, fullSync: true, home })
|
|
612
630
|
: await runHeadlessSync({ cfg: nextCfg, fullSync: true, home, fetchFn });
|
|
613
631
|
if (syncOut?.member?.id) {
|
|
614
632
|
nextCfg.memberId = syncOut.member.id;
|
|
615
633
|
nextCfg.memberName = syncOut.member.name || nextCfg.memberName;
|
|
634
|
+
if (syncOut.member.expectedEmailHash !== undefined) {
|
|
635
|
+
nextCfg.expectedEmailHash = syncOut.member.expectedEmailHash || '';
|
|
636
|
+
}
|
|
616
637
|
writeJsonAtomic(cfgPath, nextCfg, 0o600);
|
|
617
638
|
}
|
|
618
639
|
return buildZeroTokenMarkdownResponse(
|
|
@@ -626,6 +647,7 @@ export async function handlePreInvocation(
|
|
|
626
647
|
if (cmd.kind === 'leave') {
|
|
627
648
|
if (existsSync(cfgPath)) rmSync(cfgPath, { force: true });
|
|
628
649
|
if (existsSync(lastResPath)) rmSync(lastResPath, { force: true });
|
|
650
|
+
rmSync(join(clientConfigDir(home), 'account-ledger.json'), { force: true });
|
|
629
651
|
return buildZeroTokenMarkdownResponse('✅ 已退出家庭组并清除本地邀请 Token(~/.config/agy-family/client.json)。');
|
|
630
652
|
}
|
|
631
653
|
|
|
@@ -654,8 +676,14 @@ export async function handlePreInvocation(
|
|
|
654
676
|
? await syncRunner({ cfg, fullSync: cmd.fullSync, home })
|
|
655
677
|
: await runHeadlessSync({ cfg, fullSync: cmd.fullSync, home, fetchFn });
|
|
656
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' ? ' · `✓ 家庭组号`' : '';
|
|
657
685
|
return buildZeroTokenMarkdownResponse(
|
|
658
|
-
`✅ 同步完成(${cmd.fullSync ? '全量' : '增量'} \`${res?.acceptedBuckets ?? 0}\` 桶)· **${m.name || cfg.memberName || '本人'}
|
|
686
|
+
`✅ 同步完成(${cmd.fullSync ? '全量' : '增量'} \`${res?.acceptedBuckets ?? 0}\` 桶)· **${m.name || cfg.memberName || '本人'}**${acctSuffix} 今日占比 \`${m.sharePct ?? 0}%\`(分配份额 \`${m.quotaPct ?? 100}%\` · 参考 \`${fmtUsd(m.dailyUsedUsd)}\`)`,
|
|
659
687
|
);
|
|
660
688
|
} catch (err) {
|
|
661
689
|
return buildZeroTokenMarkdownResponse(`❌ 同步失败:${err?.message || err}`);
|
|
@@ -673,22 +701,27 @@ export async function handlePreInvocation(
|
|
|
673
701
|
|
|
674
702
|
export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(), fetchFn = globalThis.fetch, lookbackDays = 31 } = {}) {
|
|
675
703
|
const dir = clientConfigDir(home);
|
|
704
|
+
const cfgPath = join(dir, 'client.json');
|
|
676
705
|
const scanCachePath = join(dir, 'scan-cache.json');
|
|
677
706
|
const syncedHashesPath = join(dir, 'synced-hashes.json');
|
|
707
|
+
const accountLedgerPath = join(dir, 'account-ledger.json');
|
|
678
708
|
const lastPayloadPath = join(dir, 'last-payload.json');
|
|
679
709
|
const lastResPath = join(dir, 'last-result.json');
|
|
680
710
|
|
|
681
711
|
const cache = fullSync ? null : readJsonSafe(scanCachePath);
|
|
682
712
|
const prevHashes = fullSync ? null : readJsonSafe(syncedHashesPath);
|
|
713
|
+
const prevLedger = readJsonSafe(accountLedgerPath);
|
|
683
714
|
const deviceId = getOrCreateSharedDeviceId({ home, fallbackId: cfg.deviceId });
|
|
684
715
|
|
|
685
|
-
const { payload, scan, nextSyncedHashes } = await buildSyncPayload({
|
|
716
|
+
const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
|
|
686
717
|
deviceId,
|
|
687
718
|
clientKind: 'cli',
|
|
688
|
-
clientVersion: '0.2.
|
|
719
|
+
clientVersion: '0.2.4',
|
|
689
720
|
home,
|
|
690
721
|
fileCache: cache,
|
|
691
722
|
syncedHashes: prevHashes,
|
|
723
|
+
expectedEmailHash: cfg.expectedEmailHash || '',
|
|
724
|
+
accountLedger: prevLedger,
|
|
692
725
|
fullSync,
|
|
693
726
|
lookbackDays,
|
|
694
727
|
});
|
|
@@ -696,11 +729,35 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
|
|
|
696
729
|
throw new Error('Local SQLite reader unavailable (requires Node.js >= 22.13).');
|
|
697
730
|
}
|
|
698
731
|
writeJsonAtomic(scanCachePath, scan.nextCache, 0o600);
|
|
732
|
+
if (nextAccountLedger) {
|
|
733
|
+
writeJsonAtomic(accountLedgerPath, nextAccountLedger, 0o600);
|
|
734
|
+
}
|
|
699
735
|
writeJsonAtomic(lastPayloadPath, payload, 0o600);
|
|
700
736
|
|
|
701
737
|
const res = await pushSyncPayload({ url: cfg.url, token: cfg.token, payload, fetchFn });
|
|
702
738
|
writeJsonAtomic(syncedHashesPath, nextSyncedHashes, 0o600);
|
|
703
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
|
+
}
|
|
704
761
|
return res;
|
|
705
762
|
}
|
|
706
763
|
|