agy-family 0.2.7 → 0.2.8

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
@@ -40,21 +40,44 @@ packages/
40
40
 
41
41
  ---
42
42
 
43
- ## 1. One-Click Manager Deployment (Choose Either)
43
+ ## 1. One CLI for Both Joining & Hosting
44
44
 
45
- ### Option A: 1-Click Deploy to Cloudflare Workers + D1 (Recommended · Free Tier · Zero CLI)
45
+ Install `agy-family` once — the same CLI handles **joining a family board** and **deploying/managing your own board** (zero `git clone` needed):
46
+
47
+ ```sh
48
+ npm i -g agy-family
49
+ ```
50
+
51
+ - **Join someone's family board** (works for both Antigravity Desktop IDE & `agy` CLI):
52
+ ```sh
53
+ agy-family join "agyfam://join?d=..." --daemon
54
+ ```
55
+ - **Host your own board on Cloudflare Workers + D1 (free tier, 1 command)** — auto-provisions D1, applies migrations, generates `AGY_FAMILY_ADMIN_KEY`, syncs live `models.dev` 3-tier pricing, and with `--self` joins you automatically:
56
+ ```sh
57
+ agy-family deploy --self --member "Owner" --email "you@gmail.com" --daemon
58
+ ```
59
+ - **Invite members, inspect keys, or upgrade anytime**:
60
+ ```sh
61
+ agy-family invite "Alice" --email "alice@gmail.com" --quota 20 # Prints ready-to-paste join command
62
+ agy-family host # Show board URL, Admin Key & member list
63
+ npm i -g agy-family@latest && agy-family deploy # Idempotent zero-downtime upgrade
64
+ ```
65
+ - **Self-host locally or on any VPS (built-in Node SQLite)**:
66
+ ```sh
67
+ agy-family serve --port 8787
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 2. Alternative Manager Deployment Options
73
+
74
+ ### Option A: 1-Click Browser Deploy to Cloudflare Workers + D1 (Zero CLI)
46
75
 
47
76
  Click the button below — Cloudflare automatically forks the template, provisions a brand-new free D1 database, prompts you for `AGY_FAMILY_ADMIN_KEY`, and deploys (tables auto-initialize on first request):
48
77
 
49
78
  [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/xy-tuoren/agy-family)
50
79
 
51
- Or deploy in one CLI command:
52
-
53
- ```sh
54
- git clone https://github.com/xy-tuoren/agy-family.git
55
- cd agy-family
56
- npm run deploy:cf # Auto-creates D1, runs migrations, sets Admin Key, and deploys
57
- ```
80
+ Already deployed via the button? Link it to your local CLI with `agy-family host link --url https://your-board.workers.dev --admin-key adm_...` so you can run `agy-family invite` and `agy-family deploy` upgrades from your terminal.
58
81
 
59
82
  ### Option B: One-Line Docker Deploy (Prebuilt Multi-Arch GHCR Image · No `git clone`)
60
83
 
package/README.zh-CN.md CHANGED
@@ -40,21 +40,44 @@ packages/
40
40
 
41
41
  ---
42
42
 
43
- ## 一、家庭组管理员一键部署(3 分钟上线,任选一种)
43
+ ## 一、一个 CLI:既能「上车」也能「自己开车」
44
44
 
45
- ### 方式 A:Cloudflare Workers + D1 一键网页部署(推荐 · 永久免费层 · 零命令行)
45
+ 只需全局安装一次 `agy-family`,**成员上车**和**车主部署/发邀请/自托管**全用同一个命令行完成(免 `git clone`):
46
+
47
+ ```sh
48
+ npm i -g agy-family
49
+ ```
50
+
51
+ - **🚌 成员上车**(收到管理员发来的邀请码,桌面 IDE 和 `agy` CLI 通用):
52
+ ```sh
53
+ agy-family join "agyfam://join?d=..." --daemon
54
+ ```
55
+ - **🚗 车主免费云端开车**(Cloudflare Workers + D1 永久免费层,自动创建 D1、跑迁移、生成 Admin Key、同步 `models.dev` 三级定价,加 `--self` 顺便把自己也接上车):
56
+ ```sh
57
+ agy-family deploy --self --member "你的名字" --email "你的家庭组@gmail.com" --daemon
58
+ ```
59
+ - **🎟️ 车主发车票 / 查密钥 / 后续升级**:
60
+ ```sh
61
+ agy-family invite "成员名" --email "member@gmail.com" --quota 20 # 生成一行上车命令
62
+ agy-family host # 随时查看看板地址与 Admin Key
63
+ npm i -g agy-family@latest && agy-family deploy # 一键平滑升级云端看板(保留数据与密钥)
64
+ ```
65
+ - **🏠 本地 / VPS 自托管开车**(零依赖内置 SQLite):
66
+ ```sh
67
+ agy-family serve --port 8787
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 二、家庭组管理员其他部署方式
73
+
74
+ ### 方式 A:Cloudflare Workers + D1 一键网页部署(免命令行)
46
75
 
47
76
  直接点击下方按钮,Cloudflare 会自动在你的账号里创建免费 D1 数据库、弹窗让你填写管理员密码 `AGY_FAMILY_ADMIN_KEY` 并完成上线(首次访问自动建表):
48
77
 
49
78
  [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/xy-tuoren/agy-family)
50
79
 
51
- 喜欢在本地终端一键部署也可以跑:
52
-
53
- ```sh
54
- git clone https://github.com/xy-tuoren/agy-family.git
55
- cd agy-family
56
- npm run deploy:cf # 自动创建 D1、执行迁移、生成/写入 Admin Key 并部署
57
- ```
80
+ 如果已通过网页按钮部署,也可以用 `agy-family host link --url https://你的看板.workers.dev --admin-key adm_...` 绑定到本地 CLI,之后就能直接 `agy-family invite` 和 `agy-family deploy` 一键升级。
58
81
 
59
82
  ### 方式 B:Docker 一行脚本部署(自动拉取 GHCR 多架构镜像,免 `git clone`)
60
83
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-family",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
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",
@@ -13,6 +13,9 @@
13
13
  "packages/cli/src/",
14
14
  "packages/server-core/src/",
15
15
  "packages/server-node/src/",
16
+ "packages/worker/src/",
17
+ "packages/worker/migrations/",
18
+ "wrangler.jsonc",
16
19
  "README.md",
17
20
  "README.zh-CN.md",
18
21
  "LICENSE"
@@ -10,8 +10,8 @@ process.emitWarning = function (warning, ...args) {
10
10
  };
11
11
 
12
12
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
13
- import { homedir } from 'node:os';
14
- import { dirname, join } from 'node:path';
13
+ import { homedir, userInfo } from 'node:os';
14
+ import { dirname, join, resolve } from 'node:path';
15
15
  import { fileURLToPath } from 'node:url';
16
16
  import {
17
17
  buildSyncPayload,
@@ -36,9 +36,20 @@ import {
36
36
  uninstallAntigravityIntegration,
37
37
  uninstallBackgroundDaemon,
38
38
  } from '../src/hook.mjs';
39
-
40
- const CLI_VERSION = '0.2.7';
39
+ import {
40
+ adminApiRequest,
41
+ createMemberInvite,
42
+ deployToCloudflare,
43
+ hostConfigPath,
44
+ readHostConfig,
45
+ removeHostConfig,
46
+ sanitizeWorkerName,
47
+ writeHostConfig,
48
+ } from '../src/host.mjs';
49
+
50
+ const CLI_VERSION = '0.2.8';
41
51
  const THIS_CLI_PATH = fileURLToPath(import.meta.url);
52
+ const PACKAGE_ROOT = resolve(dirname(THIS_CLI_PATH), '..', '..', '..');
42
53
 
43
54
  function configBaseDir(home = homedir()) {
44
55
  return join(home, '.config', 'agy-family');
@@ -96,23 +107,46 @@ function getOrCreateClientConfig(home = homedir()) {
96
107
  return { deviceId: sharedDeviceId };
97
108
  }
98
109
 
110
+ function readFlag(args, name) {
111
+ for (let i = 0; i < args.length; i++) {
112
+ const a = args[i];
113
+ if (a === name) {
114
+ const next = args[i + 1];
115
+ return next !== undefined && !next.startsWith('--') ? next : '';
116
+ }
117
+ if (a.startsWith(`${name}=`)) {
118
+ return a.slice(name.length + 1);
119
+ }
120
+ }
121
+ return '';
122
+ }
123
+
99
124
  function printHelp() {
100
125
  console.log(`agy-family v${CLI_VERSION} — Google Family Group Transparent Usage Board & /family Hook CLI
126
+ One CLI for both joining a family group ("上车") and hosting your own board ("自己开车").
101
127
 
102
- Usage:
128
+ Join a Family Group (Member):
103
129
  agy-family join <agyfam://join?...> [--no-hook] [--daemon]
104
130
  Join a Google Family Group board & enable /family in IDE + CLI
105
131
  agy-family sync [--dry-run] [--watch] [--full] [--quiet]
106
132
  Sync local Desktop IDE + CLI numeric usage (delta by default)
107
133
  agy-family status [--period today|7d|cycle|30d]
108
- View your cap progress and family leaderboard
134
+ View your quota progress and family leaderboard
109
135
  agy-family audit Inspect the exact last transmitted JSON payload
110
136
  agy-family pricing [sync] View or sync 3-tier model pricing cache (models.dev / litellm)
111
137
  agy-family hook [on|off|status] Manage Antigravity IDE + CLI /family command & Stop auto-sync hook
112
138
  agy-family daemon [install|uninstall|status] Manage background 5-minute OS heartbeat (macOS launchd / Linux cron)
113
139
  agy-family leave Disconnect this device and delete local invite token
114
140
  agy-family uninstall Remove hook, /family skill, OS daemon, and local credentials
115
- agy-family serve [--port 8787] [--db path] Start the self-hosted Node + SQLite server locally
141
+
142
+ Host Your Own Board (Family Manager):
143
+ agy-family deploy [--name agy-family] [--title "..."] [--admin-key <key>] [--self] [--member <name>] [--email <gmail>] [--daemon]
144
+ One-command deploy/upgrade on Cloudflare Workers + D1 (free tier, no git clone)
145
+ agy-family invite <name> [--email <gmail>] [--quota <pct>] [--role member|manager]
146
+ Create a member and print their ready-to-paste one-line join command
147
+ agy-family host [show|link|unlink] View or link your hosted board URL, Admin Key, and D1 metadata
148
+ agy-family serve [--port 8787] [--db path] [--admin-key <key>] [--title "..."]
149
+ Start a self-hosted Node.js + SQLite board server locally or on a VPS
116
150
 
117
151
  Privacy guarantee:
118
152
  Only read-only numeric SQLite metadata (hour bucket, model, token counts, est. USD) is scanned.
@@ -246,6 +280,48 @@ async function runHookCommand(eventArg) {
246
280
  }
247
281
  }
248
282
 
283
+ async function performJoin({ rawInvite, noHook = false, withDaemon = false }) {
284
+ const parsed = decodeInviteInput(rawInvite);
285
+ const prev = getOrCreateClientConfig();
286
+ const next = {
287
+ deviceId: getOrCreateSharedDeviceId({ fallbackId: prev.deviceId }),
288
+ url: parsed.url,
289
+ token: parsed.token,
290
+ memberName: parsed.memberName || prev.memberName || '',
291
+ boardTitle: parsed.boardTitle || prev.boardTitle || '',
292
+ ...(parsed.viewKey ? { viewKey: parsed.viewKey } : {}),
293
+ ...(parsed.expectedEmailHash ? { expectedEmailHash: parsed.expectedEmailHash } : {}),
294
+ joinedAt: Date.now(),
295
+ };
296
+ writePrivateJson(clientConfigPath(), next);
297
+ rmSync(syncedHashesPath(), { force: true });
298
+ rmSync(accountLedgerPath(), { force: true });
299
+ console.log(`✓ Saved invite for "${next.memberName || 'member'}" -> ${next.url}`);
300
+
301
+ if (!noHook) {
302
+ const info = installAntigravityIntegration({
303
+ executable: process.execPath,
304
+ cliPath: THIS_CLI_PATH,
305
+ });
306
+ console.log(`✓ Installed /family zero-token command & auto-sync hook (${info.hooksFile})`);
307
+ }
308
+ if (withDaemon) {
309
+ const d = installBackgroundDaemon({
310
+ executable: process.execPath,
311
+ cliPath: THIS_CLI_PATH,
312
+ });
313
+ if (d.kind === 'launchd' || d.kind === 'cron') {
314
+ console.log(`✓ Installed background heartbeat (${d.kind}, every ${d.intervalSeconds}s)`);
315
+ }
316
+ }
317
+
318
+ await runSyncOnce({ cfg: next, dryRun: false, fullSync: true });
319
+ if (!noHook) {
320
+ console.log('Tip: Type "/family" inside Antigravity IDE or agy CLI anytime (0 tokens).');
321
+ }
322
+ return next;
323
+ }
324
+
249
325
  async function main() {
250
326
  const args = process.argv.slice(2);
251
327
  const cmd = args[0] || 'help';
@@ -274,44 +350,7 @@ async function main() {
274
350
  console.error('Usage: agy-family join <agyfam://join?...> [--no-hook] [--daemon]');
275
351
  process.exit(1);
276
352
  }
277
- const parsed = decodeInviteInput(raw);
278
- const prev = getOrCreateClientConfig();
279
- const next = {
280
- deviceId: getOrCreateSharedDeviceId({ fallbackId: prev.deviceId }),
281
- url: parsed.url,
282
- token: parsed.token,
283
- memberName: parsed.memberName || prev.memberName || '',
284
- boardTitle: parsed.boardTitle || prev.boardTitle || '',
285
- ...(parsed.viewKey ? { viewKey: parsed.viewKey } : {}),
286
- ...(parsed.expectedEmailHash ? { expectedEmailHash: parsed.expectedEmailHash } : {}),
287
- joinedAt: Date.now(),
288
- };
289
- writePrivateJson(clientConfigPath(), next);
290
- rmSync(syncedHashesPath(), { force: true });
291
- rmSync(accountLedgerPath(), { force: true });
292
- console.log(`✓ Saved invite for "${next.memberName || 'member'}" -> ${next.url}`);
293
-
294
- if (!noHook) {
295
- const info = installAntigravityIntegration({
296
- executable: process.execPath,
297
- cliPath: THIS_CLI_PATH,
298
- });
299
- console.log(`✓ Installed /family zero-token command & auto-sync hook (${info.hooksFile})`);
300
- }
301
- if (withDaemon) {
302
- const d = installBackgroundDaemon({
303
- executable: process.execPath,
304
- cliPath: THIS_CLI_PATH,
305
- });
306
- if (d.kind === 'launchd' || d.kind === 'cron') {
307
- console.log(`✓ Installed background heartbeat (${d.kind}, every ${d.intervalSeconds}s)`);
308
- }
309
- }
310
-
311
- await runSyncOnce({ cfg: next, dryRun: false, fullSync: true });
312
- if (!noHook) {
313
- console.log('Tip: Type "/family" inside Antigravity IDE or agy CLI anytime (0 tokens).');
314
- }
353
+ await performJoin({ rawInvite: raw, noHook, withDaemon });
315
354
  return;
316
355
  }
317
356
 
@@ -481,19 +520,240 @@ async function main() {
481
520
  return;
482
521
  }
483
522
 
523
+ if (cmd === 'deploy' || cmd === 'up') {
524
+ const workerName = readFlag(args, '--name');
525
+ const databaseName = readFlag(args, '--db-name');
526
+ const databaseId = readFlag(args, '--db-id');
527
+ const boardTitle = readFlag(args, '--title');
528
+ const adminKey = readFlag(args, '--admin-key');
529
+ const rotateKey = args.includes('--rotate-key');
530
+ const dryRun = args.includes('--dry-run');
531
+ const joinSelf = args.includes('--self') || args.includes('--join-self');
532
+ const noHook = args.includes('--no-hook');
533
+ const withDaemon = args.includes('--daemon');
534
+ const selfName = readFlag(args, '--member') || (() => {
535
+ try {
536
+ return userInfo().username || 'Owner';
537
+ } catch {
538
+ return 'Owner';
539
+ }
540
+ })();
541
+ const selfEmail = readFlag(args, '--email');
542
+ const selfQuota = readFlag(args, '--quota');
543
+
544
+ const res = await deployToCloudflare({
545
+ packageRoot: PACKAGE_ROOT,
546
+ workerName,
547
+ databaseName,
548
+ databaseId,
549
+ boardTitle,
550
+ adminKey,
551
+ rotateKey,
552
+ dryRun,
553
+ version: CLI_VERSION,
554
+ });
555
+
556
+ if (dryRun) {
557
+ console.log(JSON.stringify(res, null, 2));
558
+ return;
559
+ }
560
+
561
+ console.log(`\n✓ Deployed agy-family v${CLI_VERSION} to Cloudflare Workers + D1!`);
562
+ console.log(` Board URL : ${res.url}`);
563
+ console.log(` Admin Key : ${res.adminKey}`);
564
+ console.log(` D1 DB : ${res.databaseName} (${res.databaseId})`);
565
+ console.log(` Host Saved : ${res.hostConfigPath}`);
566
+ if (res.pricingSync?.ok) {
567
+ console.log(` Pricing : synced ${res.pricingSync.count} model rates from ${res.pricingSync.source}`);
568
+ }
569
+
570
+ if (joinSelf) {
571
+ const existingClient = getOrCreateClientConfig();
572
+ const normExistingUrl = String(existingClient?.url || '').replace(/\/+$/, '');
573
+ if (existingClient?.token && normExistingUrl === res.url) {
574
+ console.log(`\n✓ This device is already joined to ${res.url} as "${existingClient.memberName || 'member'}".`);
575
+ await runSyncOnce({ cfg: existingClient, dryRun: false, fullSync: false });
576
+ } else {
577
+ const overview = await adminApiRequest({
578
+ url: res.url,
579
+ adminKey: res.adminKey,
580
+ path: '/api/admin/overview',
581
+ });
582
+ const existingMgr = (overview.members || []).find((m) => m.role === 'manager' && m.active);
583
+ if (existingMgr) {
584
+ console.log(
585
+ `\nℹ Family Manager "${existingMgr.name}" already exists on this board (skipped creating duplicate manager).`,
586
+ );
587
+ console.log(
588
+ ` To invite another member, run: agy-family invite "<name>" --email "<gmail>"`,
589
+ );
590
+ } else {
591
+ const created = await createMemberInvite({
592
+ url: res.url,
593
+ adminKey: res.adminKey,
594
+ name: selfName,
595
+ role: 'manager',
596
+ email: selfEmail,
597
+ quotaPct: selfQuota ? Number(selfQuota) : null,
598
+ });
599
+ console.log(`\n✓ Created Family Manager "${created.member?.name || selfName}" — joining this device now...`);
600
+ await performJoin({ rawInvite: created.inviteUri, noHook, withDaemon });
601
+ }
602
+ }
603
+ }
604
+
605
+ console.log('\nNext steps:');
606
+ console.log(` Open board : ${res.url}`);
607
+ console.log(' Invite member : agy-family invite "Alice" --email "alice@gmail.com"');
608
+ if (!joinSelf) {
609
+ console.log(' Join yourself : agy-family deploy --self --member "YourName" --daemon');
610
+ }
611
+ return;
612
+ }
613
+
614
+ if (cmd === 'invite') {
615
+ const valueFlags = new Set(['--email', '--quota', '--role', '--color', '--url', '--admin-key']);
616
+ const pos = [];
617
+ for (let i = 1; i < args.length; i++) {
618
+ const a = args[i];
619
+ if (valueFlags.has(a)) {
620
+ i += 1;
621
+ continue;
622
+ }
623
+ if (a.startsWith('--')) continue;
624
+ pos.push(a);
625
+ }
626
+ const memberName = pos.join(' ').trim();
627
+ if (!memberName) {
628
+ console.error('Usage: agy-family invite <name> [--email <gmail>] [--quota <pct>] [--role member|manager]');
629
+ process.exit(1);
630
+ }
631
+ const hostCfg = readHostConfig();
632
+ const url = readFlag(args, '--url') || hostCfg?.url || '';
633
+ const adminKey = readFlag(args, '--admin-key') || hostCfg?.adminKey || process.env.AGY_FAMILY_ADMIN_KEY || '';
634
+ if (!url || !adminKey) {
635
+ console.error(
636
+ 'No hosted board configured locally. Run "agy-family deploy" first, or link an existing board with:\n agy-family host link --url <https://...> --admin-key <adm_...>',
637
+ );
638
+ process.exit(1);
639
+ }
640
+ const email = readFlag(args, '--email');
641
+ const quotaRaw = readFlag(args, '--quota');
642
+ const role = readFlag(args, '--role') || 'member';
643
+ const color = readFlag(args, '--color');
644
+ const asJson = args.includes('--json');
645
+
646
+ const res = await createMemberInvite({
647
+ url,
648
+ adminKey,
649
+ name: memberName,
650
+ role,
651
+ email,
652
+ quotaPct: quotaRaw ? Number(quotaRaw) : null,
653
+ color,
654
+ });
655
+ if (asJson) {
656
+ console.log(JSON.stringify(res, null, 2));
657
+ return;
658
+ }
659
+ const m = res.member || {};
660
+ console.log(`✓ Created ${m.role === 'manager' ? 'Family Manager' : 'member'} "${m.name || memberName}" on ${url}`);
661
+ if (m.emailHint) console.log(` Bound Google Email : ${m.emailHint} (SHA-256 only; non-family auto-excluded)`);
662
+ if (m.quotaPct != null) console.log(` Quota Share : ${m.quotaPct}%`);
663
+ console.log('\nSend this one-line join command (works for both Antigravity Desktop IDE & agy CLI):');
664
+ console.log(` ${res.joinCommand}`);
665
+ console.log('\nRaw invite code:');
666
+ console.log(` ${res.inviteUri}`);
667
+ return;
668
+ }
669
+
670
+ if (cmd === 'host') {
671
+ const action = (args[1] || 'show').toLowerCase();
672
+ if (action === 'link') {
673
+ const url = readFlag(args, '--url').replace(/\/+$/, '');
674
+ const adminKey = readFlag(args, '--admin-key');
675
+ if (!url || !adminKey) {
676
+ console.error(
677
+ 'Usage: agy-family host link --url <https://...> --admin-key <adm_...> [--name <worker>] [--db-name <db>] [--db-id <uuid>] [--title <title>]',
678
+ );
679
+ process.exit(1);
680
+ }
681
+ const existing = readHostConfig() || {};
682
+ const workerName = sanitizeWorkerName(readFlag(args, '--name') || existing.workerName || 'agy-family');
683
+ const databaseName = readFlag(args, '--db-name') || existing.databaseName || `${workerName}-db`;
684
+ const databaseId = readFlag(args, '--db-id') || existing.databaseId || '';
685
+ const boardTitle = readFlag(args, '--title') || existing.boardTitle || 'Antigravity Family Board';
686
+ const saved = writeHostConfig({
687
+ provider: url.includes('.workers.dev') || databaseId ? 'cloudflare' : 'self-hosted',
688
+ workerName,
689
+ databaseName,
690
+ databaseId,
691
+ url,
692
+ adminKey,
693
+ boardTitle,
694
+ version: CLI_VERSION,
695
+ linkedAt: Date.now(),
696
+ });
697
+ console.log(`✓ Linked hosted board -> ${url}`);
698
+ console.log(` Saved to : ${saved} (chmod 600)`);
699
+ console.log(' You can now run "agy-family invite <name>" or "agy-family deploy" (to upgrade).');
700
+ return;
701
+ }
702
+ if (action === 'unlink' || action === 'remove') {
703
+ const removed = removeHostConfig();
704
+ console.log(`✓ Local host config: ${removed ? 'removed' : 'not configured'}.`);
705
+ return;
706
+ }
707
+ const cfg = readHostConfig();
708
+ if (!cfg) {
709
+ console.log('No hosted board configured on this machine yet.');
710
+ console.log(' Deploy a free Cloudflare board : agy-family deploy --self --daemon');
711
+ console.log(' Or link an existing board : agy-family host link --url <https://...> --admin-key <adm_...>');
712
+ return;
713
+ }
714
+ if (args.includes('--json')) {
715
+ console.log(JSON.stringify(cfg, null, 2));
716
+ return;
717
+ }
718
+ console.log('Hosted Family Board:');
719
+ console.log(` Provider : ${cfg.provider || 'cloudflare'}`);
720
+ console.log(` Board URL : ${cfg.url || '(unknown)'}`);
721
+ console.log(` Admin Key : ${cfg.adminKey || '(not saved)'}`);
722
+ if (cfg.workerName) console.log(` Worker : ${cfg.workerName}`);
723
+ if (cfg.databaseName) console.log(` D1 DB : ${cfg.databaseName}${cfg.databaseId ? ` (${cfg.databaseId})` : ''}`);
724
+ console.log(` Config : ${hostConfigPath()}`);
725
+ if (cfg.url && cfg.adminKey) {
726
+ try {
727
+ const ov = await adminApiRequest({ url: cfg.url, adminKey: cfg.adminKey, path: '/api/admin/overview', timeoutMs: 8_000 });
728
+ const activeMembers = (ov.members || []).filter((m) => m.active);
729
+ console.log(` Members : ${activeMembers.length}/6 (${activeMembers.map((m) => m.name).join(', ') || 'none'})`);
730
+ } catch {
731
+ // Offline or unreachable — skip live count quietly.
732
+ }
733
+ }
734
+ return;
735
+ }
736
+
484
737
  if (cmd === 'serve') {
485
- const portIdx = args.indexOf('--port');
486
- const dbIdx = args.indexOf('--db');
487
- const keyIdx = args.indexOf('--admin-key');
738
+ const portStr = readFlag(args, '--port');
739
+ const hostStr = readFlag(args, '--host');
740
+ const dbStr = readFlag(args, '--db');
741
+ const keyStr = readFlag(args, '--admin-key');
742
+ const titleStr = readFlag(args, '--title');
743
+ const publicUrlStr = readFlag(args, '--public-url');
488
744
  const inst = await startNodeServer({
489
- ...(portIdx >= 0 ? { port: Number(args[portIdx + 1]) } : {}),
490
- ...(dbIdx >= 0 ? { dbPath: args[dbIdx + 1] } : {}),
491
- ...(keyIdx >= 0 ? { adminKey: args[keyIdx + 1] } : {}),
745
+ ...(portStr ? { port: Number(portStr) } : {}),
746
+ ...(hostStr ? { host: hostStr } : {}),
747
+ ...(dbStr ? { dbPath: dbStr } : {}),
748
+ ...(keyStr ? { adminKey: keyStr } : {}),
749
+ ...(publicUrlStr ? { publicBaseUrl: publicUrlStr } : {}),
750
+ ...(titleStr ? { envDefaults: { boardTitle: titleStr } } : {}),
492
751
  });
752
+ const displayUrl = publicUrlStr || `http://${inst.host === '0.0.0.0' ? '127.0.0.1' : inst.host}:${inst.port}`;
493
753
  console.log(`agy-family server listening on http://${inst.host}:${inst.port}`);
494
- if (inst.generatedAdminKey) {
495
- console.log(`Admin Key: ${inst.adminKey}`);
496
- }
754
+ console.log(`Board URL : ${displayUrl}`);
755
+ console.log(`Admin Key : ${inst.adminKey}${inst.generatedAdminKey ? ' (auto-generated)' : ''}`);
756
+ console.log(`Invite : agy-family invite "Alice" --url ${displayUrl} --admin-key ${inst.adminKey}`);
497
757
  return;
498
758
  }
499
759
 
@@ -716,7 +716,7 @@ export async function runHeadlessSync({ cfg, fullSync = false, home = homedir(),
716
716
  const { payload, scan, nextSyncedHashes, nextAccountLedger } = await buildSyncPayload({
717
717
  deviceId,
718
718
  clientKind: 'cli',
719
- clientVersion: '0.2.7',
719
+ clientVersion: '0.2.8',
720
720
  home,
721
721
  fileCache: cache,
722
722
  syncedHashes: prevHashes,
@@ -0,0 +1,442 @@
1
+ // Self-hosting & Cloudflare Workers + D1 deployment engine for the unified `agy-family` CLI.
2
+ // Lets any user run BOTH "上车" (`agy-family join`) AND "自己开车" (`agy-family deploy` / `invite` / `host` / `serve`)
3
+ // from a single global `npm i -g agy-family` installation — zero `git clone` required.
4
+
5
+ import { spawnSync } from 'node:child_process';
6
+ import { randomBytes } from 'node:crypto';
7
+ import {
8
+ chmodSync,
9
+ cpSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ readFileSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from 'node:fs';
16
+ import { homedir, tmpdir } from 'node:os';
17
+ import { dirname, join, resolve } from 'node:path';
18
+
19
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
20
+ const WORKERS_DEV_URL_RE = /https:\/\/[a-z0-9][a-z0-9.-]*\.workers\.dev\b/i;
21
+
22
+ export function hostConfigPath(home = homedir()) {
23
+ return join(home, '.config', 'agy-family', 'host.json');
24
+ }
25
+
26
+ export function readHostConfig({ home = homedir() } = {}) {
27
+ const p = hostConfigPath(home);
28
+ try {
29
+ if (!existsSync(p)) return null;
30
+ const parsed = JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''));
31
+ return parsed && typeof parsed === 'object' ? parsed : null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ 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;
47
+ }
48
+
49
+ export function removeHostConfig({ home = homedir() } = {}) {
50
+ const p = hostConfigPath(home);
51
+ const existed = existsSync(p);
52
+ rmSync(p, { force: true });
53
+ return existed;
54
+ }
55
+
56
+ export function generateAdminKey() {
57
+ return `adm_${randomBytes(16).toString('hex')}`;
58
+ }
59
+
60
+ export function sanitizeWorkerName(rawName, fallback = 'agy-family') {
61
+ const clean = String(rawName || '')
62
+ .trim()
63
+ .toLowerCase()
64
+ .replace(/[^a-z0-9-]+/g, '-')
65
+ .replace(/^-+|-+$/g, '')
66
+ .slice(0, 63);
67
+ return clean || fallback;
68
+ }
69
+
70
+ export function extractJsonFromCliOutput(text) {
71
+ const s = String(text || '').trim();
72
+ if (!s) return null;
73
+ try {
74
+ return JSON.parse(s);
75
+ } catch {
76
+ // Wrangler often prints banners like `▲ [WARNING] Proxy...` before JSON output.
77
+ }
78
+ for (const [open, close] of [
79
+ ['[', ']'],
80
+ ['{', '}'],
81
+ ]) {
82
+ const lastClose = s.lastIndexOf(close);
83
+ if (lastClose < 0) continue;
84
+ let idx = s.indexOf(open);
85
+ while (idx >= 0 && idx < lastClose) {
86
+ try {
87
+ return JSON.parse(s.slice(idx, lastClose + 1));
88
+ } catch {
89
+ idx = s.indexOf(open, idx + 1);
90
+ }
91
+ }
92
+ }
93
+ return null;
94
+ }
95
+
96
+ export function parseUuidFromText(text) {
97
+ const m = String(text || '').match(UUID_RE);
98
+ return m ? m[0].toLowerCase() : '';
99
+ }
100
+
101
+ export function parseDeployedWorkerUrl(text) {
102
+ const m = String(text || '').match(WORKERS_DEV_URL_RE);
103
+ return m ? m[0].replace(/\/+$/, '') : '';
104
+ }
105
+
106
+ export function buildWranglerConfig({
107
+ workerName = 'agy-family',
108
+ databaseName = 'agy-family-db',
109
+ databaseId = '',
110
+ boardTitle = 'Antigravity Family Board',
111
+ defaultDailyCapUsd = 10,
112
+ defaultWeeklyCapUsd = 50,
113
+ defaultCycleCapUsd = 150,
114
+ } = {}) {
115
+ return {
116
+ name: sanitizeWorkerName(workerName),
117
+ main: 'packages/worker/src/index.mjs',
118
+ compatibility_date: '2025-05-01',
119
+ observability: { enabled: true },
120
+ triggers: { crons: ['0 */6 * * *'] },
121
+ d1_databases: [
122
+ {
123
+ binding: 'DB',
124
+ database_name: String(databaseName || 'agy-family-db').trim(),
125
+ database_id: String(databaseId || '').trim(),
126
+ migrations_dir: 'packages/worker/migrations',
127
+ },
128
+ ],
129
+ vars: {
130
+ BOARD_TITLE: String(boardTitle || 'Antigravity Family Board').trim(),
131
+ DEFAULT_DAILY_CAP_USD: String(defaultDailyCapUsd),
132
+ DEFAULT_WEEKLY_CAP_USD: String(defaultWeeklyCapUsd),
133
+ DEFAULT_CYCLE_CAP_USD: String(defaultCycleCapUsd),
134
+ },
135
+ };
136
+ }
137
+
138
+ export function stageWorkerWorkspace({ packageRoot, stageDir, wranglerConfig }) {
139
+ const root = resolve(packageRoot);
140
+ const requiredDirs = [
141
+ 'packages/worker/src',
142
+ 'packages/worker/migrations',
143
+ 'packages/server-core/src',
144
+ 'packages/core/src',
145
+ ];
146
+ for (const rel of requiredDirs) {
147
+ const src = join(root, rel);
148
+ if (!existsSync(src)) {
149
+ throw new Error(
150
+ `Worker bundle files not found at ${src}. Please upgrade agy-family ("npm i -g agy-family@latest").`,
151
+ );
152
+ }
153
+ const dst = join(stageDir, rel);
154
+ mkdirSync(dirname(dst), { recursive: true });
155
+ cpSync(src, dst, { recursive: true });
156
+ }
157
+ const configPath = join(stageDir, 'wrangler.json');
158
+ writeFileSync(configPath, `${JSON.stringify(wranglerConfig, null, 2)}\n`, 'utf8');
159
+ return configPath;
160
+ }
161
+
162
+ function resolveNpxCliScript() {
163
+ const execDir = dirname(process.execPath);
164
+ const candidates = [
165
+ join(execDir, 'node_modules', 'npm', 'bin', 'npx-cli.js'),
166
+ join(execDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npx-cli.js'),
167
+ ];
168
+ for (const c of candidates) {
169
+ if (existsSync(c)) return c;
170
+ }
171
+ return null;
172
+ }
173
+
174
+ export function createDefaultWranglerRunner() {
175
+ const npxCli = resolveNpxCliScript();
176
+ return function runWrangler(wranglerArgs, { cwd, input, inheritStdio = false } = {}) {
177
+ const fullArgs = ['--yes', 'wrangler', ...wranglerArgs];
178
+ const spawnOpts = {
179
+ cwd,
180
+ encoding: 'utf8',
181
+ stdio: inheritStdio ? 'inherit' : 'pipe',
182
+ ...(input !== undefined ? { input } : {}),
183
+ };
184
+ let res;
185
+ if (npxCli) {
186
+ res = spawnSync(process.execPath, [npxCli, ...fullArgs], spawnOpts);
187
+ } else {
188
+ res = spawnSync(process.platform === 'win32' ? 'npx.cmd' : 'npx', fullArgs, {
189
+ ...spawnOpts,
190
+ shell: process.platform === 'win32',
191
+ });
192
+ }
193
+ return {
194
+ status: res.status ?? (res.error ? 1 : 0),
195
+ stdout: typeof res.stdout === 'string' ? res.stdout : '',
196
+ stderr: typeof res.stderr === 'string' ? res.stderr : '',
197
+ error: res.error || null,
198
+ };
199
+ };
200
+ }
201
+
202
+ export async function adminApiRequest({
203
+ url,
204
+ adminKey,
205
+ path,
206
+ method = 'GET',
207
+ body = undefined,
208
+ fetchFn = globalThis.fetch,
209
+ timeoutMs = 15_000,
210
+ }) {
211
+ const base = String(url || '').trim().replace(/\/+$/, '');
212
+ if (!base) throw new Error('Board URL is required.');
213
+ if (!adminKey) throw new Error('Admin key is required.');
214
+
215
+ const controller = new AbortController();
216
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
217
+ try {
218
+ const res = await fetchFn(`${base}${path}`, {
219
+ method,
220
+ headers: {
221
+ 'X-Admin-Key': String(adminKey).trim(),
222
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
223
+ },
224
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
225
+ signal: controller.signal,
226
+ });
227
+ const text = await res.text();
228
+ let parsed = null;
229
+ try {
230
+ parsed = JSON.parse(text);
231
+ } catch {
232
+ parsed = null;
233
+ }
234
+ if (!res.ok) {
235
+ throw new Error(parsed?.error || `Admin API ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
236
+ }
237
+ return parsed ?? { ok: true };
238
+ } finally {
239
+ clearTimeout(timer);
240
+ }
241
+ }
242
+
243
+ export async function createMemberInvite({
244
+ url,
245
+ adminKey,
246
+ name,
247
+ role = 'member',
248
+ email = '',
249
+ quotaPct = null,
250
+ color = '',
251
+ fetchFn = globalThis.fetch,
252
+ }) {
253
+ const payload = {
254
+ name: String(name || '').trim(),
255
+ role: role === 'manager' ? 'manager' : 'member',
256
+ ...(email ? { email: String(email).trim() } : {}),
257
+ ...(quotaPct !== null && quotaPct !== undefined && quotaPct !== '' ? { quotaPct: Number(quotaPct) } : {}),
258
+ ...(color ? { color: String(color).trim() } : {}),
259
+ };
260
+ if (!payload.name) throw new Error('Member name is required.');
261
+ const res = await adminApiRequest({
262
+ url,
263
+ adminKey,
264
+ path: '/api/admin/members',
265
+ method: 'POST',
266
+ body: payload,
267
+ fetchFn,
268
+ });
269
+ const inviteUri = res.inviteUri || '';
270
+ const joinCommand = inviteUri ? `npm i -g agy-family && agy-family join "${inviteUri}" --daemon` : '';
271
+ return { ...res, joinCommand };
272
+ }
273
+
274
+ export async function deployToCloudflare({
275
+ packageRoot,
276
+ home = homedir(),
277
+ workerName = '',
278
+ databaseName = '',
279
+ databaseId = '',
280
+ boardTitle = '',
281
+ adminKey = '',
282
+ rotateKey = false,
283
+ dryRun = false,
284
+ version = '0.2.8',
285
+ execFn = createDefaultWranglerRunner(),
286
+ fetchFn = globalThis.fetch,
287
+ log = console.log,
288
+ } = {}) {
289
+ const existing = readHostConfig({ home }) || {};
290
+ const finalWorkerName = sanitizeWorkerName(workerName || existing.workerName || 'agy-family');
291
+ const finalDbName = String(
292
+ databaseName || (existing.workerName === finalWorkerName ? existing.databaseName : '') || `${finalWorkerName}-db`,
293
+ ).trim();
294
+ const finalTitle = String(boardTitle || existing.boardTitle || 'Antigravity Family Board').trim();
295
+
296
+ const explicitAdminKey = String(adminKey || '').trim();
297
+ const reusedKey = !rotateKey && !explicitAdminKey && existing.adminKey && (!existing.workerName || existing.workerName === finalWorkerName);
298
+ const finalAdminKey = explicitAdminKey || (reusedKey ? existing.adminKey : generateAdminKey());
299
+ const needSecretPut = Boolean(explicitAdminKey || rotateKey || !reusedKey);
300
+
301
+ const initialDbId = String(
302
+ databaseId || (existing.databaseName === finalDbName && existing.databaseId ? existing.databaseId : ''),
303
+ ).trim();
304
+
305
+ if (dryRun) {
306
+ return {
307
+ ok: true,
308
+ dryRun: true,
309
+ workerName: finalWorkerName,
310
+ databaseName: finalDbName,
311
+ databaseId: initialDbId || '<will resolve or create>',
312
+ boardTitle: finalTitle,
313
+ willSetSecret: needSecretPut,
314
+ reusedExistingHost: Boolean(existing.url),
315
+ url: existing.url || `https://${finalWorkerName}.<your-subdomain>.workers.dev`,
316
+ };
317
+ }
318
+
319
+ // Step 1/5: Cloudflare login check
320
+ log('1/5 Checking Cloudflare Wrangler login...');
321
+ const whoami = execFn(['whoami'], { cwd: process.cwd() });
322
+ if (whoami.status !== 0) {
323
+ log(' Not logged in yet — opening Cloudflare OAuth in your browser...');
324
+ const loginRes = execFn(['login'], { cwd: process.cwd(), inheritStdio: true });
325
+ if (loginRes.status !== 0) {
326
+ throw new Error('Cloudflare login failed or was cancelled.');
327
+ }
328
+ }
329
+
330
+ // Step 2/5: Provision or reuse D1 database
331
+ let resolvedDbId = initialDbId;
332
+ if (resolvedDbId) {
333
+ log(`2/5 Reusing D1 database "${finalDbName}" (${resolvedDbId})...`);
334
+ } else {
335
+ log(`2/5 Provisioning D1 database "${finalDbName}"...`);
336
+ const listRes = execFn(['d1', 'list', '--json'], { cwd: process.cwd() });
337
+ if (listRes.status === 0) {
338
+ const list = extractJsonFromCliOutput(listRes.stdout);
339
+ if (Array.isArray(list)) {
340
+ const hit = list.find((d) => d && d.name === finalDbName && d.uuid);
341
+ if (hit) resolvedDbId = String(hit.uuid).trim();
342
+ }
343
+ }
344
+ if (!resolvedDbId) {
345
+ const createRes = execFn(['d1', 'create', finalDbName], { cwd: process.cwd() });
346
+ const combined = `${createRes.stdout}\n${createRes.stderr}`;
347
+ if (createRes.status !== 0) {
348
+ throw new Error(`Failed to create D1 database "${finalDbName}": ${combined.trim().slice(0, 400)}`);
349
+ }
350
+ resolvedDbId = parseUuidFromText(combined);
351
+ }
352
+ if (!resolvedDbId) {
353
+ throw new Error(`Could not resolve D1 database_id for "${finalDbName}".`);
354
+ }
355
+ log(` D1 database_id: ${resolvedDbId}`);
356
+ }
357
+
358
+ // Step 3/5: Stage Worker workspace in temp directory & apply D1 migrations
359
+ const stageDir = join(tmpdir(), `agy-family-deploy-${randomBytes(6).toString('hex')}`);
360
+ mkdirSync(stageDir, { recursive: true });
361
+ try {
362
+ const wranglerConfig = buildWranglerConfig({
363
+ workerName: finalWorkerName,
364
+ databaseName: finalDbName,
365
+ databaseId: resolvedDbId,
366
+ boardTitle: finalTitle,
367
+ });
368
+ stageWorkerWorkspace({ packageRoot, stageDir, wranglerConfig });
369
+
370
+ log('3/5 Applying D1 database migrations...');
371
+ const migRes = execFn(['d1', 'migrations', 'apply', 'DB', '--remote', '--force'], { cwd: stageDir });
372
+ if (migRes.status !== 0) {
373
+ const detail = `${migRes.stdout}\n${migRes.stderr}`.trim().slice(0, 500);
374
+ throw new Error(`D1 migration failed: ${detail}`);
375
+ }
376
+
377
+ // Step 4/5: Deploy Worker first (so brand-new Workers exist before `secret put`)
378
+ log(`4/5 Deploying Cloudflare Worker "${finalWorkerName}"...`);
379
+ const deployRes = execFn(['deploy'], { cwd: stageDir });
380
+ const deployOut = `${deployRes.stdout}\n${deployRes.stderr}`;
381
+ if (deployRes.status !== 0) {
382
+ throw new Error(`Wrangler deploy failed: ${deployOut.trim().slice(0, 500)}`);
383
+ }
384
+ const deployedUrl = parseDeployedWorkerUrl(deployOut) || String(existing.url || '').replace(/\/+$/, '');
385
+ if (!deployedUrl) {
386
+ throw new Error('Worker deployed, but could not parse the deployed *.workers.dev URL from Wrangler output.');
387
+ }
388
+
389
+ // Step 5/5: Set AGY_FAMILY_ADMIN_KEY secret (on first deploy / explicit key / rotate) + warm up models.dev 3-tier pricing
390
+ if (needSecretPut) {
391
+ log('5/5 Configuring AGY_FAMILY_ADMIN_KEY secret & syncing live models.dev pricing...');
392
+ const secRes = execFn(['secret', 'put', 'AGY_FAMILY_ADMIN_KEY'], {
393
+ cwd: stageDir,
394
+ input: finalAdminKey,
395
+ });
396
+ if (secRes.status !== 0) {
397
+ const detail = `${secRes.stdout}\n${secRes.stderr}`.trim().slice(0, 400);
398
+ throw new Error(`Failed to set AGY_FAMILY_ADMIN_KEY secret: ${detail}`);
399
+ }
400
+ } else {
401
+ log('5/5 Preserving existing AGY_FAMILY_ADMIN_KEY & syncing live models.dev pricing...');
402
+ }
403
+
404
+ let pricingSync = null;
405
+ try {
406
+ pricingSync = await adminApiRequest({
407
+ url: deployedUrl,
408
+ adminKey: finalAdminKey,
409
+ path: '/api/admin/pricing-sync',
410
+ method: 'POST',
411
+ body: { source: 'auto' },
412
+ fetchFn,
413
+ timeoutMs: 12_000,
414
+ });
415
+ } catch {
416
+ // Non-fatal: Worker falls back to calibrated built-in table and 6h Cron retries automatically.
417
+ }
418
+
419
+ const hostRecord = {
420
+ provider: 'cloudflare',
421
+ workerName: finalWorkerName,
422
+ databaseName: finalDbName,
423
+ databaseId: resolvedDbId,
424
+ url: deployedUrl,
425
+ adminKey: finalAdminKey,
426
+ boardTitle: finalTitle,
427
+ version,
428
+ deployedAt: Date.now(),
429
+ };
430
+ const savedPath = writeHostConfig(hostRecord, { home });
431
+
432
+ return {
433
+ ok: true,
434
+ ...hostRecord,
435
+ secretUpdated: needSecretPut,
436
+ pricingSync,
437
+ hostConfigPath: savedPath,
438
+ };
439
+ } finally {
440
+ rmSync(stageDir, { recursive: true, force: true });
441
+ }
442
+ }
@@ -82,7 +82,7 @@ export function diffSyncBuckets(buckets, syncedHashes = null, { fullSync = false
82
82
  export async function buildSyncPayload({
83
83
  deviceId,
84
84
  clientKind = 'cli',
85
- clientVersion = '0.2.7',
85
+ clientVersion = '0.2.8',
86
86
  home,
87
87
  roots = null,
88
88
  sourceFilter = 'all',
@@ -155,7 +155,7 @@ export async function buildSyncPayload({
155
155
  deviceId: String(deviceId || deriveAnonymousDeviceId()).slice(0, 32),
156
156
  client: {
157
157
  kind: clientKind === 'extension' ? 'extension' : 'cli',
158
- version: String(clientVersion || '0.2.7').slice(0, 24),
158
+ version: String(clientVersion || '0.2.8').slice(0, 24),
159
159
  },
160
160
  account: {
161
161
  emailHash: effectiveReportedHash,
@@ -23,7 +23,7 @@ import {
23
23
  import { renderDashboardHtml } from './ui.mjs';
24
24
  import { dispatchWebhook, sendDedupedAlert, validateWebhookUrl } from './webhooks.mjs';
25
25
 
26
- export const SERVER_VERSION = '0.2.7';
26
+ export const SERVER_VERSION = '0.2.8';
27
27
  const MAX_BUCKETS_PER_SYNC = 1000;
28
28
  const MAX_DEVICES_PER_MEMBER = 8;
29
29
  const MAX_TOKENS_PER_BUCKET = 500_000_000;
@@ -1238,7 +1238,7 @@ export function renderDashboardHtml({ boardTitle = 'Antigravity Family Board' }
1238
1238
 
1239
1239
  <footer class="foot">
1240
1240
  <span data-i18n="privacyNote">隐私承诺:客户端仅只读扫描本地 SQLite 数值元数据,绝不上传 Prompt、代码、文件路径或 Google 凭据。</span>
1241
- <span class="mono">agy-family v0.2.7 · MIT</span>
1241
+ <span class="mono">agy-family v0.2.8 · MIT</span>
1242
1242
  </footer>
1243
1243
  </main>
1244
1244
 
@@ -0,0 +1,57 @@
1
+ -- Cloudflare D1 initial migration (identical to packages/server-core/src/schema.mjs)
2
+
3
+ CREATE TABLE IF NOT EXISTS settings (
4
+ key TEXT PRIMARY KEY,
5
+ value TEXT NOT NULL,
6
+ updated_at INTEGER NOT NULL
7
+ );
8
+
9
+ CREATE TABLE IF NOT EXISTS members (
10
+ id TEXT PRIMARY KEY,
11
+ name TEXT NOT NULL,
12
+ color TEXT NOT NULL DEFAULT '#38bdf8',
13
+ token_hash TEXT NOT NULL UNIQUE,
14
+ daily_cap_usd REAL,
15
+ weekly_cap_usd REAL,
16
+ cycle_cap_usd REAL,
17
+ active INTEGER NOT NULL DEFAULT 1,
18
+ created_at INTEGER NOT NULL,
19
+ last_seen_at INTEGER,
20
+ last_client_kind TEXT,
21
+ last_client_version TEXT
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS usage_buckets (
25
+ member_id TEXT NOT NULL,
26
+ device_id TEXT NOT NULL,
27
+ bucket_hour_ms INTEGER NOT NULL,
28
+ source TEXT NOT NULL,
29
+ model TEXT NOT NULL,
30
+ input_tokens INTEGER NOT NULL DEFAULT 0,
31
+ output_tokens INTEGER NOT NULL DEFAULT 0,
32
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
33
+ thinking_tokens INTEGER NOT NULL DEFAULT 0,
34
+ steps INTEGER NOT NULL DEFAULT 0,
35
+ est_usd REAL NOT NULL DEFAULT 0,
36
+ updated_at INTEGER NOT NULL,
37
+ PRIMARY KEY (member_id, device_id, bucket_hour_ms, source, model)
38
+ );
39
+
40
+ CREATE INDEX IF NOT EXISTS idx_usage_buckets_hour ON usage_buckets (bucket_hour_ms);
41
+ CREATE INDEX IF NOT EXISTS idx_usage_buckets_member_hour ON usage_buckets (member_id, bucket_hour_ms);
42
+
43
+ CREATE TABLE IF NOT EXISTS credit_snapshots (
44
+ id TEXT PRIMARY KEY,
45
+ balance REAL NOT NULL,
46
+ note TEXT NOT NULL DEFAULT '',
47
+ recorded_at INTEGER NOT NULL
48
+ );
49
+
50
+ CREATE INDEX IF NOT EXISTS idx_credit_snapshots_time ON credit_snapshots (recorded_at DESC);
51
+
52
+ CREATE TABLE IF NOT EXISTS alert_log (
53
+ alert_key TEXT PRIMARY KEY,
54
+ kind TEXT NOT NULL,
55
+ summary TEXT NOT NULL,
56
+ sent_at INTEGER NOT NULL
57
+ );
@@ -0,0 +1,29 @@
1
+ -- Anti-tamper odometers & integrity audit log (v0.2.1)
2
+
3
+ CREATE TABLE IF NOT EXISTS device_odometers (
4
+ member_id TEXT NOT NULL,
5
+ device_id TEXT NOT NULL,
6
+ max_db_files INTEGER NOT NULL DEFAULT 0,
7
+ max_all_time_steps INTEGER NOT NULL DEFAULT 0,
8
+ max_all_time_tokens INTEGER NOT NULL DEFAULT 0,
9
+ last_db_files INTEGER NOT NULL DEFAULT 0,
10
+ last_all_time_steps INTEGER NOT NULL DEFAULT 0,
11
+ last_all_time_tokens INTEGER NOT NULL DEFAULT 0,
12
+ last_nonzero_at INTEGER,
13
+ updated_at INTEGER NOT NULL,
14
+ PRIMARY KEY (member_id, device_id)
15
+ );
16
+
17
+ CREATE TABLE IF NOT EXISTS integrity_events (
18
+ id TEXT PRIMARY KEY,
19
+ member_id TEXT NOT NULL,
20
+ member_name TEXT NOT NULL,
21
+ device_id TEXT NOT NULL,
22
+ kind TEXT NOT NULL,
23
+ severity TEXT NOT NULL DEFAULT 'warn',
24
+ summary TEXT NOT NULL,
25
+ detected_at INTEGER NOT NULL
26
+ );
27
+
28
+ CREATE INDEX IF NOT EXISTS idx_integrity_events_time ON integrity_events (detected_at DESC);
29
+ CREATE INDEX IF NOT EXISTS idx_integrity_events_member ON integrity_events (member_id, detected_at DESC);
@@ -0,0 +1,2 @@
1
+ -- Google Family Group member role ('manager' | 'member')
2
+ ALTER TABLE members ADD COLUMN role TEXT NOT NULL DEFAULT 'member';
@@ -0,0 +1,2 @@
1
+ -- Percentage-based family quota share (NULL = auto-split remaining pool equally)
2
+ ALTER TABLE members ADD COLUMN quota_pct REAL;
@@ -0,0 +1,5 @@
1
+ -- Privacy-preserving Google Family email SHA-256 binding & active account attribution status
2
+ ALTER TABLE members ADD COLUMN expected_email_hash TEXT;
3
+ ALTER TABLE members ADD COLUMN email_hint TEXT;
4
+ ALTER TABLE members ADD COLUMN last_email_hash TEXT;
5
+ ALTER TABLE members ADD COLUMN last_account_status TEXT;
@@ -0,0 +1,103 @@
1
+ // Cloudflare Workers + D1 entrypoint for agy-family.
2
+ // Zero npm runtime dependencies — runs cleanly on Cloudflare's free tier,
3
+ // including scheduled() Cron Triggers for proactive offline member alerts.
4
+
5
+ import { checkOfflineMembersAndAlert, createApp, syncServerPricingCache } from '../../server-core/src/index.mjs';
6
+ import { ensureSchema } from '../../server-core/src/schema.mjs';
7
+
8
+ // Cache schema initialization per D1 binding instance within a Worker isolate so we do NOT
9
+ // burn DDL round-trips against D1 on every single HTTP request.
10
+ const migratedBindings = new WeakSet();
11
+ const migrationInFlight = new WeakMap();
12
+
13
+ export function createD1Adapter(d1) {
14
+ if (!d1 || typeof d1.prepare !== 'function') {
15
+ throw new Error('Cloudflare D1 binding "DB" is missing. Check wrangler.jsonc.');
16
+ }
17
+ const bindStmt = (sql, params = []) => (params.length > 0 ? d1.prepare(sql).bind(...params) : d1.prepare(sql));
18
+
19
+ return {
20
+ async all(sql, params = []) {
21
+ const res = await bindStmt(sql, params).all();
22
+ return Array.isArray(res?.results) ? res.results : [];
23
+ },
24
+ async get(sql, params = []) {
25
+ const row = await bindStmt(sql, params).first();
26
+ return row ?? null;
27
+ },
28
+ async run(sql, params = []) {
29
+ return bindStmt(sql, params).run();
30
+ },
31
+ async batch(statements = []) {
32
+ if (!Array.isArray(statements) || statements.length === 0) return [];
33
+ if (typeof d1.batch === 'function') {
34
+ const prepared = statements.map((s) => bindStmt(s.sql, s.params || []));
35
+ return d1.batch(prepared);
36
+ }
37
+ const results = [];
38
+ for (const s of statements) {
39
+ results.push(await bindStmt(s.sql, s.params || []).run());
40
+ }
41
+ return results;
42
+ },
43
+ };
44
+ }
45
+
46
+ async function ensureMigratedOnce(rawD1, db) {
47
+ if (migratedBindings.has(rawD1)) return;
48
+ let promise = migrationInFlight.get(rawD1);
49
+ if (!promise) {
50
+ promise = ensureSchema(db)
51
+ .then(() => {
52
+ migratedBindings.add(rawD1);
53
+ })
54
+ .finally(() => {
55
+ migrationInFlight.delete(rawD1);
56
+ });
57
+ migrationInFlight.set(rawD1, promise);
58
+ }
59
+ await promise;
60
+ }
61
+
62
+ function extractEnvDefaults(env = {}) {
63
+ const envDefaults = {};
64
+ if (env.BOARD_TITLE) envDefaults.boardTitle = env.BOARD_TITLE;
65
+ if (env.BOARD_VIEW_KEY) envDefaults.boardViewKey = env.BOARD_VIEW_KEY;
66
+ if (env.DEFAULT_DAILY_CAP_USD) envDefaults.defaultDailyCapUsd = Number(env.DEFAULT_DAILY_CAP_USD);
67
+ if (env.DEFAULT_WEEKLY_CAP_USD) envDefaults.defaultWeeklyCapUsd = Number(env.DEFAULT_WEEKLY_CAP_USD);
68
+ if (env.DEFAULT_CYCLE_CAP_USD) envDefaults.defaultCycleCapUsd = Number(env.DEFAULT_CYCLE_CAP_USD);
69
+ if (env.TIMEZONE_OFFSET_MIN) envDefaults.timezoneOffsetMin = Number(env.TIMEZONE_OFFSET_MIN);
70
+ if (env.CREDITS_PER_USD) envDefaults.creditsPerUsd = Number(env.CREDITS_PER_USD);
71
+ return envDefaults;
72
+ }
73
+
74
+ export default {
75
+ async fetch(request, env) {
76
+ const db = createD1Adapter(env.DB);
77
+ await ensureMigratedOnce(env.DB, db);
78
+
79
+ const app = createApp({
80
+ db,
81
+ adminKey: String(env.AGY_FAMILY_ADMIN_KEY || '').trim(),
82
+ publicBaseUrl: String(env.PUBLIC_BASE_URL || '').trim(),
83
+ envDefaults: extractEnvDefaults(env),
84
+ runtime: 'cloudflare-workers',
85
+ autoMigrate: false,
86
+ });
87
+ return app(request);
88
+ },
89
+
90
+ async scheduled(_event, env, ctx) {
91
+ const db = createD1Adapter(env.DB);
92
+ await ensureMigratedOnce(env.DB, db);
93
+ const work = Promise.allSettled([
94
+ checkOfflineMembersAndAlert(db, { envDefaults: extractEnvDefaults(env) }),
95
+ syncServerPricingCache(db, { force: false }),
96
+ ]);
97
+ if (ctx && typeof ctx.waitUntil === 'function') {
98
+ ctx.waitUntil(work);
99
+ } else {
100
+ await work;
101
+ }
102
+ },
103
+ };
package/wrangler.jsonc ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "agy-family",
3
+ "main": "packages/worker/src/index.mjs",
4
+ "compatibility_date": "2025-05-01",
5
+ "observability": {
6
+ "enabled": true
7
+ },
8
+ // Periodic proactive offline-member check (every 6 hours, included in Cloudflare Workers free tier)
9
+ "triggers": {
10
+ "crons": ["0 */6 * * *"]
11
+ },
12
+ // Leaving database_id empty lets the "Deploy to Cloudflare" button
13
+ // automatically provision a brand-new D1 database in your Cloudflare account.
14
+ "d1_databases": [
15
+ {
16
+ "binding": "DB",
17
+ "database_name": "agy-family-db",
18
+ "database_id": "",
19
+ "migrations_dir": "packages/worker/migrations"
20
+ }
21
+ ],
22
+ "vars": {
23
+ "BOARD_TITLE": "Antigravity Family Board",
24
+ "DEFAULT_DAILY_CAP_USD": "10",
25
+ "DEFAULT_WEEKLY_CAP_USD": "50",
26
+ "DEFAULT_CYCLE_CAP_USD": "150"
27
+ }
28
+ }