gipity 1.1.40 → 1.1.42

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/dist/index.js CHANGED
@@ -6993,7 +6993,7 @@ Prefer the cheapest option that works - CLI and sandbox are instant and free, ap
6993
6993
 
6994
6994
  1. CLI commands (fast, no agent overhead). The \`gipity\` CLI covers add, deploy, db, fn, logs, page, sync, memory, skill, email, and more. All commands support \`--json\` (except \`gipity build\`, which hands the terminal to your coding agent).
6995
6995
  2. Cloud sandbox via \`gipity sandbox run\` - Docker container with pre-installed tools for media (ffmpeg, ImageMagick, sox), documents (pandoc, LibreOffice), and data (pandas, matplotlib, sqlite3). Run \`gipity skill read sandbox-tools\` for the full toolkit. No network from inside the sandbox - fetch what you need before sending it in.
6996
- 3. App services - runtime HTTP endpoints your deployed app calls directly at \`https://a.gipity.ai/api/<PROJECT_GUID>/services/*\`. Available: LLM, TTS, image, sound, music, transcribe, video, file upload, realtime (a function can push into a room with the injected \`realtime.publish()\`, so a page listens instead of polling; see \`app-realtime\`), location, push notifications (Gipity Notify - \`gipity add notify\`, send from a function with the injected \`notify()\`; see \`app-notify\`), embeddings for semantic search / RAG (the injected \`embed()\` in a function plus the pre-installed pgvector in the app DB; see \`app-vector-search\`). Load the matching skill (\`app-llm\`, \`app-tts\`, etc.) before writing service code - they have the schemas, auth pattern, and common-mistake guards. For one-off generation during development, prefer \`gipity generate <image|video|speech|sound|music>\` - direct generation always bills you (the owner), regardless of any service \`billing_mode\` (that setting only governs the deployed app's runtime calls; never flip it just to create assets). Image models named \`gipity-*\` run on Gipity's own GPU at half price but wait in a queue (paid accounts first): \`gipity generate image --model gipity-<model>\` waits and saves, \`--no-wait\` returns at once, and \`gipity generate models\` shows them with prices and the current wait. \`gipity generate\` saves to a generic file in the current directory by default (e.g. \`./generated.png\`) - pass \`-o <path>\` to write it straight into your source tree so it deploys (e.g. \`gipity generate image "hero banner" -o src/assets/images/hero.png\`) instead of generating at cwd and moving it. For a quick model answer while you work - summarize a log, extract fields, describe a screenshot, a second opinion from a different model - use \`gipity ask "<question>"\`: one call, no history or tools, any model (\`--model sonnet\`, \`--model openai\`), text files with \`--file <path>\` (\`--file -\` for stdin), images with \`--image <path>\`, and a JSON answer with \`--schema '<json schema>'\`.
6996
+ 3. App services - runtime HTTP endpoints your deployed app calls directly at \`https://a.gipity.ai/api/<PROJECT_GUID>/services/*\`. Available: LLM, TTS, image, sound, music, transcribe, video, file upload, realtime (a function can push into a room with the injected \`realtime.publish()\`, so a page listens instead of polling; see \`app-realtime\`), location, push notifications (Gipity Notify - \`gipity add notify\`, send from a function with the injected \`notify()\`; see \`app-notify\`), embeddings for semantic search / RAG (the injected \`embed()\` in a function plus the pre-installed pgvector in the app DB; see \`app-vector-search\`), passkey approvals (one person signs off on one exact action with Face ID or a passkey, and a device verifies the signed proof offline: the injected \`approval\` in a function; see \`app-approvals\`). Load the matching skill (\`app-llm\`, \`app-tts\`, etc.) before writing service code - they have the schemas, auth pattern, and common-mistake guards. For one-off generation during development, prefer \`gipity generate <image|video|speech|sound|music>\` - direct generation always bills you (the owner), regardless of any service \`billing_mode\` (that setting only governs the deployed app's runtime calls; never flip it just to create assets). Image models named \`gipity-*\` run on Gipity's own GPU at half price but wait in a queue (paid accounts first): \`gipity generate image --model gipity-<model>\` waits and saves, \`--no-wait\` returns at once, and \`gipity generate models\` shows them with prices and the current wait. \`gipity generate\` saves to a generic file in the current directory by default (e.g. \`./generated.png\`) - pass \`-o <path>\` to write it straight into your source tree so it deploys (e.g. \`gipity generate image "hero banner" -o src/assets/images/hero.png\`) instead of generating at cwd and moving it. For a quick model answer while you work - summarize a log, extract fields, describe a screenshot, a second opinion from a different model - use \`gipity ask "<question>"\`: one call, no history or tools, any model (\`--model sonnet\`, \`--model openai\`), text files with \`--file <path>\` (\`--file -\` for stdin), images with \`--image <path>\`, and a JSON answer with \`--schema '<json schema>'\`.
6997
6997
 
6998
6998
  You are the developer. Write files in this directory - Gipity's editor hooks (installed by \`gipity init\` into Claude Code, Codex, Grok, Antigravity, and opencode) auto-sync them to Gipity. Don't run \`npm install\`, \`npm start\`, \`node\`, or \`python\` locally; there is no local runtime. Code runs in the Gipity sandbox.
6999
6999
 
@@ -7118,13 +7118,14 @@ Run \`gipity skill list\` to see every skill. Run \`gipity skill read <name>\` t
7118
7118
 
7119
7119
  App services skills (load before calling \`/services/*\` endpoints):
7120
7120
  - \`app-api-keys\` - project API keys for scripts/devices: gipity key create, scopes (functions, tables, files, ip)
7121
+ - \`app-approvals\` - passkey approvals - one person signs off on one exact action with Face ID / a passkey; signed proof a device verifies offline, single-use consume
7121
7122
  - \`app-audio\` - sound effects, music, transcription
7122
7123
  - \`app-auth\` - sign in: Gipity accounts or app-owned users (Google, email code), popup vs redirect
7123
7124
  - \`app-files\` - uploads, then displaying files and the storage helper (ownership check, delete)
7124
7125
  - \`app-image\` - text-to-image AND instruction editing (pass \`images\` to edit an uploaded photo); providers, sizes, aspect ratios
7125
7126
  - \`app-llm\` - chat completions, streaming, image input
7126
7127
  - \`app-location\` - user location & reverse geocoding for deployed apps (first-party - no third-party geocoder)
7127
- - \`app-notify\` - web push notifications for deployed apps (incl. iOS home-screen web apps) - notify kit + injected notify() service, platform owns the keys
7128
+ - \`app-notify\` - push notifications for deployed apps (web, iOS home-screen web apps, and native iOS apps via APNs) - notify kit + injected notify() service, platform owns delivery
7128
7129
  - \`app-payments\` - charge end-users real money - Stripe one-time purchases & subscriptions, via the stripe kit (gipity add stripe)
7129
7130
  - \`app-realtime\` - Gipity Realtime rooms, relay vs state
7130
7131
  - \`app-tts\` - voices, models, dialogue, languages, word timestamps
@@ -34369,7 +34370,7 @@ var {
34369
34370
  init_config();
34370
34371
  init_setup();
34371
34372
  init_utils();
34372
- import { readFileSync as readFileSync32 } from "fs";
34373
+ import { readFileSync as readFileSync34 } from "fs";
34373
34374
  import { fileURLToPath as fileURLToPath5 } from "url";
34374
34375
  import { dirname as dirname17, resolve as resolve20 } from "path";
34375
34376
 
@@ -34850,9 +34851,9 @@ var UploadConflictError = class extends Error {
34850
34851
  path;
34851
34852
  };
34852
34853
  async function uploadOneFile(projectGuid2, localPath, virtualPath, opts = {}) {
34853
- const { sha256, size } = await hashFile(localPath);
34854
+ const { sha256: sha2562, size } = await hashFile(localPath);
34854
34855
  const mime = opts.mime ?? guessMime(virtualPath);
34855
- const initBody = { path: virtualPath, size, sha256, mime };
34856
+ const initBody = { path: virtualPath, size, sha256: sha2562, mime };
34856
34857
  if (opts.expectedServerVersion !== void 0) {
34857
34858
  initBody.expected_server_version = opts.expectedServerVersion;
34858
34859
  }
@@ -35119,8 +35120,8 @@ function walkLocal(root, ignorePatterns, baseline) {
35119
35120
  const size = stat2.size;
35120
35121
  const mtime = stat2.mtime.toISOString();
35121
35122
  const prior = baseline[rel2];
35122
- const sha256 = prior && prior.size === size && prior.mtime === mtime ? prior.sha256 : void 0;
35123
- result.set(rel2, { size, mtime, sha256 });
35123
+ const sha2562 = prior && prior.size === size && prior.mtime === mtime ? prior.sha256 : void 0;
35124
+ result.set(rel2, { size, mtime, sha256: sha2562 });
35124
35125
  } catch {
35125
35126
  }
35126
35127
  }
@@ -35162,8 +35163,8 @@ async function ensureLocalHashes(root, local, paths) {
35162
35163
  const info2 = local.get(path5);
35163
35164
  if (!info2 || info2.sha256) continue;
35164
35165
  try {
35165
- const { sha256 } = await hashFile(join10(root, path5));
35166
- info2.sha256 = sha256;
35166
+ const { sha256: sha2562 } = await hashFile(join10(root, path5));
35167
+ info2.sha256 = sha2562;
35167
35168
  } catch {
35168
35169
  }
35169
35170
  }
@@ -35729,11 +35730,11 @@ async function syncInner(projectGuid2, root, ignore2, opts, interactive) {
35729
35730
  { expectedServerVersion: null }
35730
35731
  );
35731
35732
  const stat2 = statSync2(renamedFull);
35732
- const { sha256 } = await hashFile(renamedFull);
35733
+ const { sha256: sha2562 } = await hashFile(renamedFull);
35733
35734
  baseline.files[renamedRel] = {
35734
35735
  size: stat2.size,
35735
35736
  mtime: stat2.mtime.toISOString(),
35736
- sha256,
35737
+ sha256: sha2562,
35737
35738
  serverVersion: result.serverVersion
35738
35739
  };
35739
35740
  } catch (e) {
@@ -35815,11 +35816,11 @@ async function syncInner(projectGuid2, root, ignore2, opts, interactive) {
35815
35816
  expectedServerVersion: null
35816
35817
  });
35817
35818
  const stat2 = statSync2(renamed);
35818
- const { sha256 } = await hashFile(renamed);
35819
+ const { sha256: sha2562 } = await hashFile(renamed);
35819
35820
  baseline.files[a.renamedLocalTo] = {
35820
35821
  size: stat2.size,
35821
35822
  mtime: stat2.mtime.toISOString(),
35822
- sha256,
35823
+ sha256: sha2562,
35823
35824
  serverVersion: result.serverVersion
35824
35825
  };
35825
35826
  } catch (err) {
@@ -35859,8 +35860,8 @@ async function syncInner(projectGuid2, root, ignore2, opts, interactive) {
35859
35860
  onBytes?.(a.localSize ?? 0);
35860
35861
  continue;
35861
35862
  }
35862
- const sha256 = local.get(a.path)?.sha256 ?? (await hashFile(full)).sha256;
35863
- prepared.push({ a, full, size: stat2.size, mtime: stat2.mtime.toISOString(), sha256 });
35863
+ const sha2562 = local.get(a.path)?.sha256 ?? (await hashFile(full)).sha256;
35864
+ prepared.push({ a, full, size: stat2.size, mtime: stat2.mtime.toISOString(), sha256: sha2562 });
35864
35865
  } catch (e) {
35865
35866
  errors.push(`Upload failed for ${a.path}: ${e.message}`);
35866
35867
  onBytes?.(a.localSize ?? 0);
@@ -36008,12 +36009,12 @@ async function syncInner(projectGuid2, root, ignore2, opts, interactive) {
36008
36009
  mkdirSync5(dirname6(full), { recursive: true });
36009
36010
  writeFileSync6(full, buf);
36010
36011
  const stat2 = statSync2(full);
36011
- const { sha256 } = await hashFile(full);
36012
+ const { sha256: sha2562 } = await hashFile(full);
36012
36013
  const current = typeof err.data?.current_server_version === "number" ? err.data.current_server_version : null;
36013
36014
  baseline.files[a.path] = {
36014
36015
  size: stat2.size,
36015
36016
  mtime: stat2.mtime.toISOString(),
36016
- sha256,
36017
+ sha256: sha2562,
36017
36018
  serverVersion: current ?? a.expectedServerVersion ?? 0
36018
36019
  };
36019
36020
  errors.push(`Could not delete ${a.path}: server has a newer version - restored the server copy locally (delete it again and re-sync to confirm)`);
@@ -36096,11 +36097,11 @@ async function pushFile(filePath) {
36096
36097
  expectedServerVersion: baseEntry ? baseEntry.serverVersion : null
36097
36098
  });
36098
36099
  const stat2 = statSync2(filePath);
36099
- const { sha256 } = await hashFile(filePath);
36100
+ const { sha256: sha2562 } = await hashFile(filePath);
36100
36101
  baseline.files[rel2] = {
36101
36102
  size: stat2.size,
36102
36103
  mtime: stat2.mtime.toISOString(),
36103
- sha256,
36104
+ sha256: sha2562,
36104
36105
  serverVersion: result.serverVersion
36105
36106
  };
36106
36107
  writeBaseline(baseline);
@@ -36523,6 +36524,7 @@ function scopesFromFlags(opts) {
36523
36524
  }
36524
36525
  }
36525
36526
  if (opts.files !== void 0) scopes.files = opts.files;
36527
+ if (opts.approvals !== void 0) scopes.approvals = opts.approvals;
36526
36528
  if (opts.ip !== void 0) {
36527
36529
  const ips = splitList(opts.ip);
36528
36530
  if (!ips.length) throw new Error("--ip needs at least one address or CIDR range");
@@ -36536,6 +36538,7 @@ function describeScopes(scopes) {
36536
36538
  if (scopes.functions) parts.push(`fn: ${scopes.functions.join(",")}`);
36537
36539
  if (scopes.tables) parts.push(`tables: ${Object.entries(scopes.tables).map(([t, a]) => `${t}:${a}`).join(",")}`);
36538
36540
  if (scopes.files) parts.push(`files: ${scopes.files}`);
36541
+ if (scopes.approvals) parts.push(`approvals: ${scopes.approvals}`);
36539
36542
  if (scopes.ip) parts.push(`ip: ${scopes.ip.join(",")}`);
36540
36543
  return parts.join(" ");
36541
36544
  }
@@ -36544,7 +36547,7 @@ async function projectGuid(opts) {
36544
36547
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
36545
36548
  return config.projectGuid;
36546
36549
  }
36547
- keyCommand.command("create <name>").description("Mint a project API key (shown once). Give it a name you will recognize later").addOption(new Option("--role <role>", "Access role for the key").choices(["viewer", "editor", "owner"]).default("viewer")).option("--expires-days <n>", "Days until the key expires (default: never)").option("--functions <names>", "Scope: only these functions (comma-separated)").option("--tables <list>", "Scope: only these Records tables, e.g. commands:write,logs:read").addOption(new Option("--files <access>", "Scope: app files access").choices(["read", "write"])).option("--ip <list>", "Scope: only from these IPs / CIDR ranges (comma-separated)").option(...projectOpt).option("--json", "Output as JSON").action((name, opts) => run("Create", async () => {
36550
+ keyCommand.command("create <name>").description("Mint a project API key (shown once). Give it a name you will recognize later").addOption(new Option("--role <role>", "Access role for the key").choices(["viewer", "editor", "owner"]).default("viewer")).option("--expires-days <n>", "Days until the key expires (default: never)").option("--functions <names>", "Scope: only these functions (comma-separated)").option("--tables <list>", "Scope: only these Records tables, e.g. commands:write,logs:read").addOption(new Option("--files <access>", "Scope: app files access").choices(["read", "write"])).addOption(new Option("--approvals <access>", "Scope: read and consume passkey approvals").choices(["read"])).option("--ip <list>", "Scope: only from these IPs / CIDR ranges (comma-separated)").option(...projectOpt).option("--json", "Output as JSON").action((name, opts) => run("Create", async () => {
36548
36551
  const body = { name, role: opts.role };
36549
36552
  const scopes = scopesFromFlags(opts);
36550
36553
  if (scopes) body.scopes = scopes;
@@ -37750,258 +37753,9 @@ init_api();
37750
37753
  init_config();
37751
37754
  init_colors();
37752
37755
  init_setup();
37753
- import { existsSync as existsSync12, readFileSync as readFileSync14 } from "fs";
37754
- import { join as join16, resolve as resolve9 } from "path";
37756
+ import { existsSync as existsSync13, readFileSync as readFileSync16 } from "fs";
37757
+ import { join as join18, resolve as resolve10 } from "path";
37755
37758
  import { homedir as homedir12 } from "os";
37756
- function checkGipityPlugin() {
37757
- const path5 = join16(homedir12(), ".claude", "settings.json");
37758
- let settings = {};
37759
- if (existsSync12(path5)) {
37760
- try {
37761
- settings = JSON.parse(readFileSync14(path5, "utf-8"));
37762
- } catch {
37763
- }
37764
- }
37765
- const missing = [];
37766
- if (!settings?.extraKnownMarketplaces?.[GIPITY_MARKETPLACE_NAME]) missing.push("marketplace");
37767
- if (settings?.enabledPlugins?.[GIPITY_PLUGIN_ID] !== true) missing.push("plugin");
37768
- const install = userScopeInstallState();
37769
- if (!install.current) missing.push("install");
37770
- const stale = missing.length === 1 && missing[0] === "install" && install.exists;
37771
- return { missing, ok: missing.length === 0, stale };
37772
- }
37773
- async function probeAuth(loggedIn) {
37774
- if (!loggedIn && !usingEnvToken()) return { state: "none", account: null };
37775
- if (!usingEnvToken() && sessionExpired()) return { state: "expired", account: null };
37776
- const timeout = new Promise(
37777
- (res) => setTimeout(() => res({ state: "unreachable", account: null }), 5e3).unref?.()
37778
- );
37779
- const call = get("/users/me").then(
37780
- (res) => ({ state: "ok", account: res.data?.accountSlug ?? null }),
37781
- (err) => ({ state: err instanceof ApiError && err.statusCode === 401 ? "rejected" : "unreachable", account: null })
37782
- );
37783
- return Promise.race([call, timeout]);
37784
- }
37785
- var statusCommand = new Command("status").alias("whoami").description("Show project and login status").option("--json", "Output as JSON").option("--repair-hooks", "Re-enable the Gipity Claude Code plugin (hooks) if missing or disabled").action(async (opts) => {
37786
- const config = getConfig();
37787
- const auth = getAuth();
37788
- const cwd = resolve9(process.cwd());
37789
- void cwd;
37790
- const hookCheck = config ? checkGipityPlugin() : null;
37791
- const queueDelivered = auth && !sessionExpired() ? await flushBugQueue().catch(() => 0) : 0;
37792
- const probe = await probeAuth(!!auth);
37793
- const accountMismatch = probe.state === "ok" && !!config && !!probe.account && probe.account !== config.accountSlug;
37794
- const apiBaseInUse = resolveApiBase();
37795
- if (opts.json) {
37796
- console.log(JSON.stringify({
37797
- project: config ? {
37798
- guid: config.projectGuid,
37799
- slug: config.projectSlug,
37800
- account: config.accountSlug,
37801
- apiBase: config.apiBase,
37802
- apiBaseInUse,
37803
- url: liveUrl(config),
37804
- ...config.env ? { env: config.env.name } : {}
37805
- } : null,
37806
- // `valid` reflects the refresh token (the real session) - access
37807
- // tokens auto-renew, so their expiry must not read as "invalid".
37808
- // `probe` is what one live call just proved: 'rejected' means every
37809
- // authenticated command will fail even though `valid` reads true.
37810
- // 'mismatch' overrides 'ok' when the live account isn't the one that
37811
- // owns this project - `valid` still reads true (the token IS valid).
37812
- auth: auth || usingEnvToken() ? {
37813
- email: auth?.email,
37814
- account: probe.account,
37815
- source: usingEnvToken() ? "agent-token" : "session",
37816
- valid: usingEnvToken() ? probe.state !== "rejected" : !sessionExpired(),
37817
- probe: accountMismatch ? "mismatch" : probe.state
37818
- } : null,
37819
- plugin: hookCheck
37820
- }, null, 2));
37821
- return;
37822
- }
37823
- if (!config) {
37824
- console.log(warning("Not a Gipity project. Run: gipity init"));
37825
- } else {
37826
- console.log(`${muted("Project:")} ${brand(config.projectSlug)} ${muted(`(${config.projectGuid})`)}`);
37827
- console.log(`${muted("Account:")} ${config.accountSlug}`);
37828
- if (config.env) console.log(`${muted("Env:")} ${config.env.name}`);
37829
- console.log(`${muted("Live:")} ${liveUrl(config)}`);
37830
- console.log(`${muted("API:")} ${config.apiBase}`);
37831
- if (apiBaseInUse !== config.apiBase) {
37832
- console.log(`${muted("API (in use):")} ${warning(apiBaseInUse)} ${muted("(overrides .gipity.json: GIPITY_API_BASE / --api-base / allowlist)")}`);
37833
- }
37834
- }
37835
- if (usingEnvToken()) {
37836
- console.log(`${muted("Auth:")} ${probe.state === "rejected" ? warning("agent API token (GIPITY_TOKEN) rejected by the server. Mint a new one: gipity skill read agent-deploy") : success("agent API token (GIPITY_TOKEN)")}${probe.state === "unreachable" ? ` ${muted("(unverified: API unreachable)")}` : ""}`);
37837
- } else if (!auth) {
37838
- console.log(`${muted("Auth:")} ${warning("not logged in. Run: gipity login")}`);
37839
- } else if (probe.state === "expired") {
37840
- console.log(`${muted("Auth:")} ${warning(`session expired for ${auth.email}. Run: gipity login (headless/CI: set GIPITY_TOKEN, see gipity skill read agent-deploy)`)}`);
37841
- } else if (probe.state === "rejected") {
37842
- console.log(`${muted("Auth:")} ${warning(`session for ${auth.email} was rejected by the server. Run: gipity login (headless/CI: set GIPITY_TOKEN, see gipity skill read agent-deploy)`)}`);
37843
- } else {
37844
- console.log(`${muted("Auth:")} ${success(auth.email)}${probe.state === "unreachable" ? ` ${muted("(unverified: API unreachable)")}` : ""}`);
37845
- }
37846
- if (accountMismatch) {
37847
- console.log(`${muted("Account:")} ${warning(`logged-in account (${probe.account}) differs from this project's account (${config.accountSlug}). If you didn't expect this you may be logged into the wrong account. Run: gipity login`)}`);
37848
- console.log(muted("(If this project was shared with you via gipity rbac, this is expected.)"));
37849
- }
37850
- if (queueDelivered > 0) {
37851
- console.log(`${muted("Bug queue:")} ${success(`delivered ${queueDelivered} queued bug report${queueDelivered === 1 ? "" : "s"}`)}`);
37852
- }
37853
- if (hookCheck) {
37854
- if (hookCheck.ok) {
37855
- console.log(`${muted("Hooks:")} ${success(`Gipity plugin enabled (${GIPITY_PLUGIN_ID})`)}`);
37856
- } else if (opts.repairHooks) {
37857
- ensureGipityPlugin(true);
37858
- setupClaudeHooks();
37859
- ensureGipityPluginInstalled();
37860
- const after = checkGipityPlugin();
37861
- if (after.ok) {
37862
- console.log(`${muted("Hooks:")} ${success("repaired - Gipity plugin enabled")}`);
37863
- } else {
37864
- console.log(`${muted("Hooks:")} ${warning(`repair incomplete (still missing: ${after.missing.join(", ")})`)}`);
37865
- console.log(muted("Ensure `claude` is on PATH, then re-run. Restart Claude Code to load the update."));
37866
- }
37867
- } else if (hookCheck.stale) {
37868
- console.log(`${muted("Hooks:")} ${warning("Gipity plugin out of date (an update is available)")}`);
37869
- console.log(muted("Hooks still load, but run `gipity status --repair-hooks` to update to the latest."));
37870
- } else {
37871
- console.log(`${muted("Hooks:")} ${warning(`Gipity plugin not enabled (missing: ${hookCheck.missing.join(", ")})`)}`);
37872
- console.log(muted("Run `gipity status --repair-hooks` to enable."));
37873
- console.log(muted("Without it, files don't auto-sync and web CLI dispatches can't show Claude Code output."));
37874
- }
37875
- }
37876
- });
37877
-
37878
- // src/commands/sync.ts
37879
- import { dirname as dirname9 } from "node:path";
37880
- init_colors();
37881
- init_utils();
37882
- init_config();
37883
- var syncCommand = new Command("sync").description("Sync files").addHelpText("after", "\nAdd a .gipityignore at the project root to exclude paths (gitignore-style).").option("--plan", "Print the plan without applying any changes").option("--force", "Bypass the bulk-deletion guard").option("--prune", "Remove files that exist on Gipity but not locally (applies the bulk deletes the guard defers)").option("--json", "Output as JSON").action(async (opts) => {
37884
- try {
37885
- const progress = opts.json ? void 0 : createProgressReporter();
37886
- const result = await sync({ plan: opts.plan, force: opts.force, prune: opts.prune, confirmMerge: true, progress });
37887
- if (opts.json) {
37888
- console.log(JSON.stringify(result));
37889
- } else {
37890
- console.log(result.summary);
37891
- if (!opts.plan && result.applied > 0) {
37892
- console.log(`
37893
- ${result.applied} action${result.applied > 1 ? "s" : ""} applied.`);
37894
- }
37895
- if (isWsl()) {
37896
- const configPath = getConfigPath();
37897
- const twin = configPath ? findWindowsTwinProject(dirname9(configPath)) : null;
37898
- if (twin) {
37899
- console.log(muted(
37900
- `
37901
- Note: a Windows-side copy of this project exists at ${wslPathToWindows(twin)} and is NOT synced. If you added files there, move them into this folder so they sync.`
37902
- ));
37903
- }
37904
- }
37905
- if (result.deferredDeletes > 0) {
37906
- console.log(muted(
37907
- `
37908
- ${result.deferredDeletes} file${result.deferredDeletes > 1 ? "s" : ""} on Gipity ${result.deferredDeletes > 1 ? "are" : "is"} not present locally and ${result.deferredDeletes > 1 ? "were" : "was"} left untouched. Run 'gipity sync --prune' to remove ${result.deferredDeletes > 1 ? "them" : "it"}.`
37909
- ));
37910
- }
37911
- for (const e of result.errors) console.error(error(e));
37912
- }
37913
- if (result.aborted || result.errors.length > 0) process.exit(1);
37914
- } catch (err) {
37915
- console.error(error(`Sync failed: ${err.message}`));
37916
- process.exit(1);
37917
- }
37918
- });
37919
-
37920
- // src/commands/push.ts
37921
- import { resolve as resolve10 } from "path";
37922
- init_colors();
37923
- var pushCommand = new Command("push").description("Push one or more files").argument("<files...>", "File path(s) to push").option("--quiet", "Suppress output").option("--background", "Fork and exit immediately").option("--json", "Output as JSON").action(async (files, opts) => {
37924
- try {
37925
- const fullPaths = files.map((f) => resolve10(f));
37926
- if (opts.background) {
37927
- const { spawnCommand: spawnCommand2 } = await Promise.resolve().then(() => (init_platform(), platform_exports));
37928
- const child = spawnCommand2(process.execPath, [process.argv[1], "push", ...fullPaths, "--quiet"], {
37929
- detached: true,
37930
- stdio: "ignore"
37931
- });
37932
- child.unref();
37933
- if (opts.json) console.log(JSON.stringify({ background: true, files }));
37934
- return;
37935
- }
37936
- const pushed = [];
37937
- const skipped = [];
37938
- for (let i = 0; i < fullPaths.length; i++) {
37939
- (await pushFile(fullPaths[i]) ? pushed : skipped).push(files[i]);
37940
- }
37941
- if (opts.json) {
37942
- console.log(JSON.stringify({ pushed, skipped }));
37943
- } else if (!opts.quiet) {
37944
- console.log(success(files.length === 1 ? `Pushed ${files[0]}` : `Pushed ${files.length} files`));
37945
- }
37946
- } catch (err) {
37947
- if (!opts.quiet) {
37948
- console.error(error(`Push failed: ${err.message}`));
37949
- }
37950
- process.exit(1);
37951
- }
37952
- });
37953
-
37954
- // src/commands/upload.ts
37955
- init_api();
37956
- init_config();
37957
- import { statSync as statSync5 } from "fs";
37958
- import { basename as basename4 } from "path";
37959
- init_utils();
37960
- init_colors();
37961
- var uploadCommand = new Command("upload").description("Upload a file and print a durable public URL (works immediately, no deploy)").argument("<file>", "Local file to upload").option("--private", "Store as a private token-signed serve URL instead of a public CDN url").option("--content-type <mime>", "Override the content type (default: detected from the file extension)").option("--json", "Output as JSON").addHelpText("after", `
37962
- Public by default (a media.gipity.ai CDN url any job or function can fetch);
37963
- --private mints a token-signed serve url instead. Example:
37964
-
37965
- gipity upload song.mp3
37966
- gipity job submit split-stems --data '{"audio_url":"<printed url>"}'
37967
- `).action((file, opts) => run("Upload", async () => {
37968
- const { config } = await resolveProjectContext();
37969
- let size;
37970
- try {
37971
- const st2 = statSync5(file);
37972
- if (!st2.isFile()) throw new Error("not a regular file");
37973
- size = st2.size;
37974
- } catch (err) {
37975
- throw new Error(`can't read ${file}: ${err.message}`);
37976
- }
37977
- if (size === 0) throw new Error(`${file} is empty - nothing to upload.`);
37978
- const filename = basename4(file);
37979
- const contentType = opts.contentType || guessMime(file);
37980
- const doUpload = async () => {
37981
- const init = await post(`/api/${config.projectGuid}/uploads/init`, {
37982
- filename,
37983
- content_type: contentType,
37984
- size,
37985
- public: !opts.private
37986
- });
37987
- const fields = await transferToS3(file, size, contentType, init.data);
37988
- const completeBody = {
37989
- upload_guid: init.data.upload_guid
37990
- };
37991
- if ("parts" in fields) completeBody.parts = fields.parts;
37992
- const comp = await post(`/api/${config.projectGuid}/uploads/complete`, completeBody);
37993
- return comp.data;
37994
- };
37995
- const data = opts.json ? await doUpload() : await withSpinner(`Uploading ${filename} (${formatSize(size)})...`, doUpload, { done: null });
37996
- if (opts.json) {
37997
- console.log(JSON.stringify(data));
37998
- return;
37999
- }
38000
- console.log(success(`Uploaded ${data.name} (${formatSize(data.size)})`));
38001
- console.log(` ${brand(data.url)}`);
38002
- console.log(muted(` Durable, worker-reachable URL - pass it straight to a job/function as an input URL.`));
38003
- console.log(muted(` ${data.is_public ? "public (CDN)" : "private (token-signed)"} \xB7 guid: ${data.guid}`));
38004
- }));
38005
37759
 
38006
37760
  // src/commands/deploy.ts
38007
37761
  init_api();
@@ -38016,7 +37770,7 @@ init_colors();
38016
37770
  init_auth();
38017
37771
 
38018
37772
  // src/commands/page-eval.ts
38019
- import { readFileSync as readFileSync16 } from "node:fs";
37773
+ import { readFileSync as readFileSync15 } from "node:fs";
38020
37774
  init_api();
38021
37775
  init_colors();
38022
37776
  init_auth();
@@ -38049,8 +37803,8 @@ function dropCheckpoint(projectGuid2, database) {
38049
37803
  // src/page-fixtures.ts
38050
37804
  init_api();
38051
37805
  init_config();
38052
- import { readFileSync as readFileSync15, statSync as statSync6, existsSync as existsSync13, readdirSync as readdirSync7 } from "node:fs";
38053
- import { basename as basename5, resolve as resolve11, relative as relative3, join as join17 } from "node:path";
37806
+ import { readFileSync as readFileSync14, statSync as statSync5, existsSync as existsSync12, readdirSync as readdirSync7 } from "node:fs";
37807
+ import { basename as basename4, resolve as resolve9, relative as relative3, join as join16 } from "node:path";
38054
37808
  var FIND_SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", ".gipity", "dist", "build", ".next", "coverage"]);
38055
37809
  function findByBasename(root, name, limit = 3) {
38056
37810
  const hits = [];
@@ -38067,31 +37821,31 @@ function findByBasename(root, name, limit = 3) {
38067
37821
  }
38068
37822
  for (const e of entries) {
38069
37823
  if (e.isDirectory()) {
38070
- if (!FIND_SKIP.has(e.name)) queue.push(join17(dir, e.name));
37824
+ if (!FIND_SKIP.has(e.name)) queue.push(join16(dir, e.name));
38071
37825
  } else if (e.name === name && hits.length < limit) {
38072
- hits.push(join17(dir, e.name));
37826
+ hits.push(join16(dir, e.name));
38073
37827
  }
38074
37828
  }
38075
37829
  }
38076
37830
  return hits;
38077
37831
  }
38078
37832
  function assertLocalAsset(flag, localPath) {
38079
- const abs = resolve11(localPath);
38080
- if (existsSync13(abs)) return;
37833
+ const abs = resolve9(localPath);
37834
+ if (existsSync12(abs)) return;
38081
37835
  const root = getProjectRoot() ?? process.cwd();
38082
- const elsewhere = findByBasename(root, basename5(localPath)).filter((p) => p !== abs);
37836
+ const elsewhere = findByBasename(root, basename4(localPath)).filter((p) => p !== abs);
38083
37837
  const found = elsewhere.length ? `
38084
37838
  That file DOES exist here. Pass this path instead:
38085
37839
  ${elsewhere.map((p) => ` ${flag} ${relative3(process.cwd(), p) || p}`).join("\n")}` : `
38086
- Nothing named "${basename5(localPath)}" under ${root} either. Generate a frame with \`gipity generate image "<description>" -o ${localPath}\`, or check the path.`;
37840
+ Nothing named "${basename4(localPath)}" under ${root} either. Generate a frame with \`gipity generate image "<description>" -o ${localPath}\`, or check the path.`;
38087
37841
  throw new Error(
38088
37842
  `${flag} ${localPath}: no such file. Looked for ${abs} (relative paths resolve against the current directory, ${process.cwd()}).${found}`
38089
37843
  );
38090
37844
  }
38091
37845
  async function uploadPublicFixture(projectGuid2, localPath, flag = "--fixture") {
38092
37846
  assertLocalAsset(flag, localPath);
38093
- const name = basename5(localPath);
38094
- const size = statSync6(localPath).size;
37847
+ const name = basename4(localPath);
37848
+ const size = statSync5(localPath).size;
38095
37849
  const contentType = guessMime(localPath);
38096
37850
  const init = await post(
38097
37851
  `/api/${projectGuid2}/uploads/init`,
@@ -38103,7 +37857,7 @@ async function uploadPublicFixture(projectGuid2, localPath, flag = "--fixture")
38103
37857
  const res = await fetch(init.data.url, {
38104
37858
  method: "PUT",
38105
37859
  headers: { "Content-Type": contentType },
38106
- body: readFileSync15(localPath)
37860
+ body: readFileSync14(localPath)
38107
37861
  });
38108
37862
  if (!res.ok) {
38109
37863
  throw new Error(`upload of fixture "${name}" failed: ${res.status} ${res.statusText}`);
@@ -38123,7 +37877,7 @@ function assertCameraFile(localPath) {
38123
37877
  const ext = localPath.slice(localPath.lastIndexOf(".")).toLowerCase();
38124
37878
  if (CAMERA_EXTS.includes(ext)) return;
38125
37879
  throw new Error(
38126
- `--camera ${basename5(localPath)}: unsupported file type "${ext || "(none)"}": the camera feed must be an image or video (${CAMERA_EXTS.join(", ")}).
37880
+ `--camera ${basename4(localPath)}: unsupported file type "${ext || "(none)"}": the camera feed must be an image or video (${CAMERA_EXTS.join(", ")}).
38127
37881
  A still image is played as a looping single-frame feed, which is what a gesture/pose/object model needs.
38128
37882
  No frame to hand? Generate one: gipity generate image "a hand making a closed fist, palm to camera, plain background"`
38129
37883
  );
@@ -38205,7 +37959,7 @@ function capWaitForTimeoutMs(raw) {
38205
37959
  return WAIT_FOR_MAX_MS;
38206
37960
  }
38207
37961
  function readScriptFile(pathArg) {
38208
- return readFileSync16(pathArg === "-" ? 0 : pathArg, "utf8");
37962
+ return readFileSync15(pathArg === "-" ? 0 : pathArg, "utf8");
38209
37963
  }
38210
37964
  function parsesAsExpression(s) {
38211
37965
  try {
@@ -38710,7 +38464,7 @@ init_auth();
38710
38464
  init_colors();
38711
38465
  init_utils();
38712
38466
  import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync10 } from "fs";
38713
- import { dirname as dirname10, extname as extname4, join as join18, resolve as resolvePath } from "path";
38467
+ import { dirname as dirname9, extname as extname4, join as join17, resolve as resolvePath } from "path";
38714
38468
  var DEVICE_PRESETS = {
38715
38469
  default: { width: 1280, height: 720 },
38716
38470
  desktop: { width: 1920, height: 1080 },
@@ -38774,7 +38528,7 @@ function dimSuffix(vp2) {
38774
38528
  }
38775
38529
  function defaultScreenshotDir() {
38776
38530
  const root = getProjectRoot();
38777
- return join18(root ?? ".", "tmp", "screenshots");
38531
+ return join17(root ?? ".", "tmp", "screenshots");
38778
38532
  }
38779
38533
  function timestampSlug(d = /* @__PURE__ */ new Date()) {
38780
38534
  const p = (n) => String(n).padStart(2, "0");
@@ -38993,8 +38747,8 @@ var pageScreenshotCommand = new Command("screenshot").description("Screenshot a
38993
38747
  return stemPath(outputArg, suffix);
38994
38748
  };
38995
38749
  for (let i = 0; i < pngs.length; i++) {
38996
- const target = outputArg ? outputPath(i) : join18(dir, names[i] ?? shotName(meta.screenshots[i].viewport));
38997
- mkdirSync9(dirname10(target), { recursive: true });
38750
+ const target = outputArg ? outputPath(i) : join17(dir, names[i] ?? shotName(meta.screenshots[i].viewport));
38751
+ mkdirSync9(dirname9(target), { recursive: true });
38998
38752
  writeFileSync10(target, pngs[i].buffer);
38999
38753
  savedFiles.push(resolvePath(target));
39000
38754
  }
@@ -39179,8 +38933,8 @@ async function inspectPage(url, opts = {}) {
39179
38933
  let transientErrors = [];
39180
38934
  if (opts.reprobe !== false && (b7.console || []).some(isErrorLine)) {
39181
38935
  try {
39182
- const verify2 = await post(`/tools/browser/inspect`, inspectBody);
39183
- const recurring = new Set((verify2.data.console || []).filter(isErrorLine));
38936
+ const verify3 = await post(`/tools/browser/inspect`, inspectBody);
38937
+ const recurring = new Set((verify3.data.console || []).filter(isErrorLine));
39184
38938
  transientErrors = (b7.console || []).filter((l7) => isErrorLine(l7) && !recurring.has(l7));
39185
38939
  b7.console = (b7.console || []).filter((l7) => !isErrorLine(l7) || recurring.has(l7));
39186
38940
  } catch {
@@ -39337,7 +39091,7 @@ async function printPlan(appGuid2, env, json) {
39337
39091
  console.log(warning("A prod deploy stops on the destructive statements above until you pass --yes-destructive."));
39338
39092
  }
39339
39093
  }
39340
- var deployCommand = new Command("deploy").description("Deploy the app to prod, or to an environment (created on first deploy)").argument("[env]", "prod, or an environment name (dev, staging, ...). Omitted: prod while the app has no environments; once it has any, name one").option("--yes-destructive", "Allow pending prod migrations that destroy data (DROP TABLE/COLUMN, TRUNCATE, DELETE without WHERE, column type changes)").option("--plan", "Show the pending migrations this deploy would run (and where each already ran), without deploying").option("--source-dir <dir>", "Source directory to deploy from").option("--only <phases>", "Run only specific phases, comma-separated, matched by gipity.yaml phase name or type: files/static, database/sql, functions, workflows, services, jobs, records, realtime, env, auth_branding, auth").option("--force", "Re-run all phases (ignore checksums) and bypass the sync bulk-deletion guard").option("--no-sync", "Skip sync-up before deploy").option("--optimize", 'Bundle and minify the JS/CSS with Vite (off by default: files upload as-is, so prod serves what you verified). Only bundles <script type="module"> references, and page eval import() of an app module then loads a separate copy').option("--json", "Output as JSON").option("--inspect [path]", "After a successful deploy, run `page inspect` on the deployed URL (or URL + path) in the same command - one build-loop step instead of two. With --json, emits two JSON lines: deploy, then inspect.").option("--wait <ms>", "With --inspect: sleep this many ms before capturing (max 30000)").option("--wait-for <selector>", "With --inspect: wait until this CSS selector appears before capturing (deterministic; the app's own ready signal)").option("--wait-timeout <ms>", "With --inspect: max ms to wait for --wait-for before giving up", "5000").action((envArg, opts) => run("Deploy", async () => {
39094
+ var deployCommand = new Command("deploy").description("Deploy the app to prod, or to an environment (created on first deploy)").argument("[env]", "prod, or an environment name (dev, staging, ...). Omitted: prod while the app has no environments; once it has any, name one").option("--yes-destructive", "Allow pending prod migrations that destroy data (DROP TABLE/COLUMN, TRUNCATE, DELETE without WHERE, column type changes)").option("--plan", "Show the pending migrations this deploy would run (and where each already ran), without deploying").option("--source-dir <dir>", "Source directory to deploy from").option("--only <phases>", "Run only specific phases, comma-separated, matched by gipity.yaml phase name or type: files/static, database/sql, functions, workflows, services, jobs, records, realtime, env, auth_branding, auth, access").option("--force", "Re-run all phases (ignore checksums) and bypass the sync bulk-deletion guard").option("--no-sync", "Skip sync-up before deploy").option("--optimize", 'Bundle and minify the JS/CSS with Vite (off by default: files upload as-is, so prod serves what you verified). Only bundles <script type="module"> references, and page eval import() of an app module then loads a separate copy').option("--json", "Output as JSON").option("--inspect [path]", "After a successful deploy, run `page inspect` on the deployed URL (or URL + path) in the same command - one build-loop step instead of two. With --json, emits two JSON lines: deploy, then inspect.").option("--wait <ms>", "With --inspect: sleep this many ms before capturing (max 30000)").option("--wait-for <selector>", "With --inspect: wait until this CSS selector appears before capturing (deterministic; the app's own ready signal)").option("--wait-timeout <ms>", "With --inspect: max ms to wait for --wait-for before giving up", "5000").action((envArg, opts) => run("Deploy", async () => {
39341
39095
  const env = envArg ?? getEnvOption();
39342
39096
  if (opts.plan) {
39343
39097
  await printPlan(requireConfig2().projectGuid, env ?? "prod", !!opts.json);
@@ -39358,7 +39112,6 @@ var deployCommand = new Command("deploy").description("Deploy the app to prod, o
39358
39112
  });
39359
39113
  const res = opts.json ? await doDeploy() : await withSpinner(env ? `Deploying to ${env}...` : "Deploying...", doDeploy, { done: null });
39360
39114
  const d = res.data;
39361
- const where = d.env ?? d.target;
39362
39115
  const inspectAfter = async () => {
39363
39116
  if (!opts.inspect) return;
39364
39117
  if (!d.url) {
@@ -39387,7 +39140,7 @@ var deployCommand = new Command("deploy").description("Deploy the app to prod, o
39387
39140
  return;
39388
39141
  }
39389
39142
  const batchLabel = d.batch ? muted(` (batch ${d.batch})`) : "";
39390
- console.log(brand(bold(`Deploy to ${where}`)) + batchLabel + (d.created ? muted(" (new environment)") : ""));
39143
+ console.log(brand(bold(`Deploy to ${d.env}`)) + batchLabel + (d.created ? muted(" (new environment)") : ""));
39391
39144
  console.log(muted("\u2500".repeat(40)));
39392
39145
  if (d.phases && d.phases.length > 0) {
39393
39146
  for (const phase of d.phases) {
@@ -39424,17 +39177,285 @@ var deployCommand = new Command("deploy").description("Deploy the app to prod, o
39424
39177
  console.log(error(`Deploy failed`) + muted(` (${d.elapsedMs}ms)`));
39425
39178
  process.exit(1);
39426
39179
  } else {
39427
- console.log(success(`\u2713 Deployed to ${where}`) + muted(` (${d.elapsedMs}ms)`));
39180
+ console.log(success(`\u2713 Deployed to ${d.env}`) + muted(` (${d.elapsedMs}ms)`));
39428
39181
  if (d.url) console.log(`${muted("Live:")} ${brand(d.url)}`);
39182
+ if (d.pageAccess && d.pageAccess !== "public") console.log(`${muted("Pages:")} ${pageAccessLabel(d.pageAccess)}`);
39429
39183
  if (d.phases?.some((p) => p.name === "functions")) {
39430
- console.log(`${muted("Functions:")} POST ${brand(`${resolveApiBase()}/api/${d.appGuid ?? config.projectGuid}/fn/<name>`)}`);
39431
- const envFlag = d.env && d.env !== "prod" ? ` --env ${d.env}` : "";
39184
+ console.log(`${muted("Functions:")} POST ${brand(`${resolveApiBase()}/api/${d.appGuid}/fn/<name>`)}`);
39185
+ const envFlag = d.env !== "prod" ? ` --env ${d.env}` : "";
39432
39186
  console.log(muted(` (names: gipity fn list${envFlag}; verify the public path: gipity fn call <name>${envFlag} --anon)`));
39433
39187
  }
39434
39188
  for (const hint of d.hints ?? []) console.log(muted(hint));
39435
39189
  await inspectAfter();
39436
39190
  }
39437
39191
  }));
39192
+ function pageAccessLabel(mode) {
39193
+ return mode === "members" ? "private: only you and project members (Gipity sign-in)" : "private: only the app's signed-in users";
39194
+ }
39195
+
39196
+ // src/commands/status.ts
39197
+ async function probePageAccess(projectGuid2) {
39198
+ const timeout = new Promise((res) => setTimeout(() => res(null), 5e3).unref?.());
39199
+ const call = get(`/projects/${projectGuid2}`).then(
39200
+ (res) => res.data?.page_access ?? null,
39201
+ () => null
39202
+ );
39203
+ return Promise.race([call, timeout]);
39204
+ }
39205
+ function checkGipityPlugin() {
39206
+ const path5 = join18(homedir12(), ".claude", "settings.json");
39207
+ let settings = {};
39208
+ if (existsSync13(path5)) {
39209
+ try {
39210
+ settings = JSON.parse(readFileSync16(path5, "utf-8"));
39211
+ } catch {
39212
+ }
39213
+ }
39214
+ const missing = [];
39215
+ if (!settings?.extraKnownMarketplaces?.[GIPITY_MARKETPLACE_NAME]) missing.push("marketplace");
39216
+ if (settings?.enabledPlugins?.[GIPITY_PLUGIN_ID] !== true) missing.push("plugin");
39217
+ const install = userScopeInstallState();
39218
+ if (!install.current) missing.push("install");
39219
+ const stale = missing.length === 1 && missing[0] === "install" && install.exists;
39220
+ return { missing, ok: missing.length === 0, stale };
39221
+ }
39222
+ async function probeAuth(loggedIn) {
39223
+ if (!loggedIn && !usingEnvToken()) return { state: "none", account: null };
39224
+ if (!usingEnvToken() && sessionExpired()) return { state: "expired", account: null };
39225
+ const timeout = new Promise(
39226
+ (res) => setTimeout(() => res({ state: "unreachable", account: null }), 5e3).unref?.()
39227
+ );
39228
+ const call = get("/users/me").then(
39229
+ (res) => ({ state: "ok", account: res.data?.accountSlug ?? null }),
39230
+ (err) => ({ state: err instanceof ApiError && err.statusCode === 401 ? "rejected" : "unreachable", account: null })
39231
+ );
39232
+ return Promise.race([call, timeout]);
39233
+ }
39234
+ var statusCommand = new Command("status").alias("whoami").description("Show project and login status").option("--json", "Output as JSON").option("--repair-hooks", "Re-enable the Gipity Claude Code plugin (hooks) if missing or disabled").action(async (opts) => {
39235
+ const config = getConfig();
39236
+ const auth = getAuth();
39237
+ const cwd = resolve10(process.cwd());
39238
+ void cwd;
39239
+ const hookCheck = config ? checkGipityPlugin() : null;
39240
+ const queueDelivered = auth && !sessionExpired() ? await flushBugQueue().catch(() => 0) : 0;
39241
+ const [probe, pageAccess] = await Promise.all([
39242
+ probeAuth(!!auth),
39243
+ config && (auth || usingEnvToken()) ? probePageAccess(config.projectGuid) : Promise.resolve(null)
39244
+ ]);
39245
+ const accountMismatch = probe.state === "ok" && !!config && !!probe.account && probe.account !== config.accountSlug;
39246
+ const apiBaseInUse = resolveApiBase();
39247
+ if (opts.json) {
39248
+ console.log(JSON.stringify({
39249
+ project: config ? {
39250
+ guid: config.projectGuid,
39251
+ slug: config.projectSlug,
39252
+ account: config.accountSlug,
39253
+ apiBase: config.apiBase,
39254
+ apiBaseInUse,
39255
+ url: liveUrl(config),
39256
+ ...config.env ? { env: config.env.name } : {},
39257
+ ...pageAccess ? { pageAccess } : {}
39258
+ } : null,
39259
+ // `valid` reflects the refresh token (the real session) - access
39260
+ // tokens auto-renew, so their expiry must not read as "invalid".
39261
+ // `probe` is what one live call just proved: 'rejected' means every
39262
+ // authenticated command will fail even though `valid` reads true.
39263
+ // 'mismatch' overrides 'ok' when the live account isn't the one that
39264
+ // owns this project - `valid` still reads true (the token IS valid).
39265
+ auth: auth || usingEnvToken() ? {
39266
+ email: auth?.email,
39267
+ account: probe.account,
39268
+ source: usingEnvToken() ? "agent-token" : "session",
39269
+ valid: usingEnvToken() ? probe.state !== "rejected" : !sessionExpired(),
39270
+ probe: accountMismatch ? "mismatch" : probe.state
39271
+ } : null,
39272
+ plugin: hookCheck
39273
+ }, null, 2));
39274
+ return;
39275
+ }
39276
+ if (!config) {
39277
+ console.log(warning("Not a Gipity project. Run: gipity init"));
39278
+ } else {
39279
+ console.log(`${muted("Project:")} ${brand(config.projectSlug)} ${muted(`(${config.projectGuid})`)}`);
39280
+ console.log(`${muted("Account:")} ${config.accountSlug}`);
39281
+ if (config.env) console.log(`${muted("Env:")} ${config.env.name}`);
39282
+ console.log(`${muted("Live:")} ${liveUrl(config)}`);
39283
+ if (pageAccess && pageAccess !== "public") console.log(`${muted("Pages:")} ${pageAccessLabel(pageAccess)}`);
39284
+ console.log(`${muted("API:")} ${config.apiBase}`);
39285
+ if (apiBaseInUse !== config.apiBase) {
39286
+ console.log(`${muted("API (in use):")} ${warning(apiBaseInUse)} ${muted("(overrides .gipity.json: GIPITY_API_BASE / --api-base / allowlist)")}`);
39287
+ }
39288
+ }
39289
+ if (usingEnvToken()) {
39290
+ console.log(`${muted("Auth:")} ${probe.state === "rejected" ? warning("agent API token (GIPITY_TOKEN) rejected by the server. Mint a new one: gipity skill read agent-deploy") : success("agent API token (GIPITY_TOKEN)")}${probe.state === "unreachable" ? ` ${muted("(unverified: API unreachable)")}` : ""}`);
39291
+ } else if (!auth) {
39292
+ console.log(`${muted("Auth:")} ${warning("not logged in. Run: gipity login")}`);
39293
+ } else if (probe.state === "expired") {
39294
+ console.log(`${muted("Auth:")} ${warning(`session expired for ${auth.email}. Run: gipity login (headless/CI: set GIPITY_TOKEN, see gipity skill read agent-deploy)`)}`);
39295
+ } else if (probe.state === "rejected") {
39296
+ console.log(`${muted("Auth:")} ${warning(`session for ${auth.email} was rejected by the server. Run: gipity login (headless/CI: set GIPITY_TOKEN, see gipity skill read agent-deploy)`)}`);
39297
+ } else {
39298
+ console.log(`${muted("Auth:")} ${success(auth.email)}${probe.state === "unreachable" ? ` ${muted("(unverified: API unreachable)")}` : ""}`);
39299
+ }
39300
+ if (accountMismatch) {
39301
+ console.log(`${muted("Account:")} ${warning(`logged-in account (${probe.account}) differs from this project's account (${config.accountSlug}). If you didn't expect this you may be logged into the wrong account. Run: gipity login`)}`);
39302
+ console.log(muted("(If this project was shared with you via gipity rbac, this is expected.)"));
39303
+ }
39304
+ if (queueDelivered > 0) {
39305
+ console.log(`${muted("Bug queue:")} ${success(`delivered ${queueDelivered} queued bug report${queueDelivered === 1 ? "" : "s"}`)}`);
39306
+ }
39307
+ if (hookCheck) {
39308
+ if (hookCheck.ok) {
39309
+ console.log(`${muted("Hooks:")} ${success(`Gipity plugin enabled (${GIPITY_PLUGIN_ID})`)}`);
39310
+ } else if (opts.repairHooks) {
39311
+ ensureGipityPlugin(true);
39312
+ setupClaudeHooks();
39313
+ ensureGipityPluginInstalled();
39314
+ const after = checkGipityPlugin();
39315
+ if (after.ok) {
39316
+ console.log(`${muted("Hooks:")} ${success("repaired - Gipity plugin enabled")}`);
39317
+ } else {
39318
+ console.log(`${muted("Hooks:")} ${warning(`repair incomplete (still missing: ${after.missing.join(", ")})`)}`);
39319
+ console.log(muted("Ensure `claude` is on PATH, then re-run. Restart Claude Code to load the update."));
39320
+ }
39321
+ } else if (hookCheck.stale) {
39322
+ console.log(`${muted("Hooks:")} ${warning("Gipity plugin out of date (an update is available)")}`);
39323
+ console.log(muted("Hooks still load, but run `gipity status --repair-hooks` to update to the latest."));
39324
+ } else {
39325
+ console.log(`${muted("Hooks:")} ${warning(`Gipity plugin not enabled (missing: ${hookCheck.missing.join(", ")})`)}`);
39326
+ console.log(muted("Run `gipity status --repair-hooks` to enable."));
39327
+ console.log(muted("Without it, files don't auto-sync and web CLI dispatches can't show Claude Code output."));
39328
+ }
39329
+ }
39330
+ });
39331
+
39332
+ // src/commands/sync.ts
39333
+ import { dirname as dirname10 } from "node:path";
39334
+ init_colors();
39335
+ init_utils();
39336
+ init_config();
39337
+ var syncCommand = new Command("sync").description("Sync files").addHelpText("after", "\nAdd a .gipityignore at the project root to exclude paths (gitignore-style).").option("--plan", "Print the plan without applying any changes").option("--force", "Bypass the bulk-deletion guard").option("--prune", "Remove files that exist on Gipity but not locally (applies the bulk deletes the guard defers)").option("--json", "Output as JSON").action(async (opts) => {
39338
+ try {
39339
+ const progress = opts.json ? void 0 : createProgressReporter();
39340
+ const result = await sync({ plan: opts.plan, force: opts.force, prune: opts.prune, confirmMerge: true, progress });
39341
+ if (opts.json) {
39342
+ console.log(JSON.stringify(result));
39343
+ } else {
39344
+ console.log(result.summary);
39345
+ if (!opts.plan && result.applied > 0) {
39346
+ console.log(`
39347
+ ${result.applied} action${result.applied > 1 ? "s" : ""} applied.`);
39348
+ }
39349
+ if (isWsl()) {
39350
+ const configPath = getConfigPath();
39351
+ const twin = configPath ? findWindowsTwinProject(dirname10(configPath)) : null;
39352
+ if (twin) {
39353
+ console.log(muted(
39354
+ `
39355
+ Note: a Windows-side copy of this project exists at ${wslPathToWindows(twin)} and is NOT synced. If you added files there, move them into this folder so they sync.`
39356
+ ));
39357
+ }
39358
+ }
39359
+ if (result.deferredDeletes > 0) {
39360
+ console.log(muted(
39361
+ `
39362
+ ${result.deferredDeletes} file${result.deferredDeletes > 1 ? "s" : ""} on Gipity ${result.deferredDeletes > 1 ? "are" : "is"} not present locally and ${result.deferredDeletes > 1 ? "were" : "was"} left untouched. Run 'gipity sync --prune' to remove ${result.deferredDeletes > 1 ? "them" : "it"}.`
39363
+ ));
39364
+ }
39365
+ for (const e of result.errors) console.error(error(e));
39366
+ }
39367
+ if (result.aborted || result.errors.length > 0) process.exit(1);
39368
+ } catch (err) {
39369
+ console.error(error(`Sync failed: ${err.message}`));
39370
+ process.exit(1);
39371
+ }
39372
+ });
39373
+
39374
+ // src/commands/push.ts
39375
+ import { resolve as resolve11 } from "path";
39376
+ init_colors();
39377
+ var pushCommand = new Command("push").description("Push one or more files").argument("<files...>", "File path(s) to push").option("--quiet", "Suppress output").option("--background", "Fork and exit immediately").option("--json", "Output as JSON").action(async (files, opts) => {
39378
+ try {
39379
+ const fullPaths = files.map((f) => resolve11(f));
39380
+ if (opts.background) {
39381
+ const { spawnCommand: spawnCommand2 } = await Promise.resolve().then(() => (init_platform(), platform_exports));
39382
+ const child = spawnCommand2(process.execPath, [process.argv[1], "push", ...fullPaths, "--quiet"], {
39383
+ detached: true,
39384
+ stdio: "ignore"
39385
+ });
39386
+ child.unref();
39387
+ if (opts.json) console.log(JSON.stringify({ background: true, files }));
39388
+ return;
39389
+ }
39390
+ const pushed = [];
39391
+ const skipped = [];
39392
+ for (let i = 0; i < fullPaths.length; i++) {
39393
+ (await pushFile(fullPaths[i]) ? pushed : skipped).push(files[i]);
39394
+ }
39395
+ if (opts.json) {
39396
+ console.log(JSON.stringify({ pushed, skipped }));
39397
+ } else if (!opts.quiet) {
39398
+ console.log(success(files.length === 1 ? `Pushed ${files[0]}` : `Pushed ${files.length} files`));
39399
+ }
39400
+ } catch (err) {
39401
+ if (!opts.quiet) {
39402
+ console.error(error(`Push failed: ${err.message}`));
39403
+ }
39404
+ process.exit(1);
39405
+ }
39406
+ });
39407
+
39408
+ // src/commands/upload.ts
39409
+ init_api();
39410
+ init_config();
39411
+ import { statSync as statSync6 } from "fs";
39412
+ import { basename as basename5 } from "path";
39413
+ init_utils();
39414
+ init_colors();
39415
+ var uploadCommand = new Command("upload").description("Upload a file and print a durable public URL (works immediately, no deploy)").argument("<file>", "Local file to upload").option("--private", "Store as a private token-signed serve URL instead of a public CDN url").option("--content-type <mime>", "Override the content type (default: detected from the file extension)").option("--json", "Output as JSON").addHelpText("after", `
39416
+ Public by default (a media.gipity.ai CDN url any job or function can fetch);
39417
+ --private mints a token-signed serve url instead. Example:
39418
+
39419
+ gipity upload song.mp3
39420
+ gipity job submit split-stems --data '{"audio_url":"<printed url>"}'
39421
+ `).action((file, opts) => run("Upload", async () => {
39422
+ const { config } = await resolveProjectContext();
39423
+ let size;
39424
+ try {
39425
+ const st2 = statSync6(file);
39426
+ if (!st2.isFile()) throw new Error("not a regular file");
39427
+ size = st2.size;
39428
+ } catch (err) {
39429
+ throw new Error(`can't read ${file}: ${err.message}`);
39430
+ }
39431
+ if (size === 0) throw new Error(`${file} is empty - nothing to upload.`);
39432
+ const filename = basename5(file);
39433
+ const contentType = opts.contentType || guessMime(file);
39434
+ const doUpload = async () => {
39435
+ const init = await post(`/api/${config.projectGuid}/uploads/init`, {
39436
+ filename,
39437
+ content_type: contentType,
39438
+ size,
39439
+ public: !opts.private
39440
+ });
39441
+ const fields = await transferToS3(file, size, contentType, init.data);
39442
+ const completeBody = {
39443
+ upload_guid: init.data.upload_guid
39444
+ };
39445
+ if ("parts" in fields) completeBody.parts = fields.parts;
39446
+ const comp = await post(`/api/${config.projectGuid}/uploads/complete`, completeBody);
39447
+ return comp.data;
39448
+ };
39449
+ const data = opts.json ? await doUpload() : await withSpinner(`Uploading ${filename} (${formatSize(size)})...`, doUpload, { done: null });
39450
+ if (opts.json) {
39451
+ console.log(JSON.stringify(data));
39452
+ return;
39453
+ }
39454
+ console.log(success(`Uploaded ${data.name} (${formatSize(data.size)})`));
39455
+ console.log(` ${brand(data.url)}`);
39456
+ console.log(muted(` Durable, worker-reachable URL - pass it straight to a job/function as an input URL.`));
39457
+ console.log(muted(` ${data.is_public ? "public (CDN)" : "private (token-signed)"} \xB7 guid: ${data.guid}`));
39458
+ }));
39438
39459
 
39439
39460
  // src/commands/env.ts
39440
39461
  init_api();
@@ -43232,9 +43253,10 @@ function dispositionFilename(headers) {
43232
43253
  const m = /filename="([^"]+)"/.exec(headers.get("content-disposition") ?? "");
43233
43254
  return m ? m[1] : null;
43234
43255
  }
43235
- var saveCommand = new Command("save").description("Save this app as a portable .gip bundle").argument("[output]", "Output .gip path, or a directory to write <slug>.gip into (default: ./<slug>.gip)").option("--json", "Output as JSON").addHelpText("after", "\nRestore anywhere with `gipity load <file>.gip` - it always creates a NEW project.").action((output, opts) => run("Save", async () => {
43256
+ var saveCommand = new Command("save").description("Save this app as a portable .gip bundle").argument("[output]", "Output .gip path, or a directory to write <slug>.gip into (default: ./<slug>.gip)").option("--with-data", "Also save every table's rows from the app's database (owner only)").option("--json", "Output as JSON").addHelpText("after", "\nRestore anywhere with `gipity load <file>.gip` - it always creates a NEW project.\nWith --with-data, load also builds the database from the migrations and loads the rows.").action((output, opts) => run("Save", async () => {
43236
43257
  const config = requireConfig2();
43237
- const doExport = () => downloadWithHeaders(`/projects/${config.projectGuid}/export`);
43258
+ const query = opts.withData ? "?with_data=1" : "";
43259
+ const doExport = () => downloadWithHeaders(`/projects/${config.projectGuid}/export${query}`);
43238
43260
  const { buffer, headers } = opts.json ? await doExport() : await withSpinner("Exporting...", doExport, { done: null });
43239
43261
  const filename = dispositionFilename(headers) ?? `${config.projectSlug}.gip`;
43240
43262
  let dest = path2.resolve(output ?? filename);
@@ -43243,16 +43265,18 @@ var saveCommand = new Command("save").description("Save this app as a portable .
43243
43265
  }
43244
43266
  fs3.mkdirSync(path2.dirname(dest), { recursive: true });
43245
43267
  fs3.writeFileSync(dest, buffer);
43246
- const sha256 = createHash4("sha256").update(buffer).digest("hex");
43268
+ const sha2562 = createHash4("sha256").update(buffer).digest("hex");
43247
43269
  const skipped = Number(headers.get("x-gip-skipped") ?? 0);
43248
43270
  const entries = zipEntryCount(buffer);
43271
+ const data = opts.withData ? { tables: Number(headers.get("x-gip-data-tables") ?? 0), rows: Number(headers.get("x-gip-data-rows") ?? 0) } : null;
43249
43272
  if (opts.json) {
43250
43273
  console.log(JSON.stringify({
43251
43274
  path: dest,
43252
43275
  bytes: buffer.length,
43253
- sha256,
43276
+ sha256: sha2562,
43254
43277
  ...entries !== null ? { entries } : {},
43255
- skipped
43278
+ skipped,
43279
+ ...data ? { data } : {}
43256
43280
  }));
43257
43281
  return;
43258
43282
  }
@@ -43260,12 +43284,17 @@ var saveCommand = new Command("save").description("Save this app as a portable .
43260
43284
  console.log(` Path: ${dest}`);
43261
43285
  console.log(` Size: ${formatBytes(buffer.length)}`);
43262
43286
  if (entries !== null) console.log(` Entries: ${entries} (including the bundle manifest)`);
43263
- console.log(` SHA-256: ${sha256}`);
43287
+ if (data) console.log(` Data: ${data.rows} row(s) from ${data.tables} table(s)`);
43288
+ console.log(` SHA-256: ${sha2562}`);
43264
43289
  if (skipped > 0) {
43265
43290
  console.log("");
43266
43291
  console.warn(warning(`${skipped} file(s) were skipped (unreadable or over 100 MB) - this bundle is partial.`));
43267
43292
  console.warn(warning("Large assets belong in Gipity Storage, not in a code bundle."));
43268
43293
  }
43294
+ if (data) {
43295
+ console.log("");
43296
+ console.warn(warning("This bundle holds the app's data. Share it only with people allowed to see that data."));
43297
+ }
43269
43298
  console.log("");
43270
43299
  console.log(muted("Restore anywhere with `gipity load " + path2.basename(dest) + "` (creates a new project)."));
43271
43300
  }));
@@ -43329,6 +43358,11 @@ function printManifest(m) {
43329
43358
  }
43330
43359
  }
43331
43360
  }
43361
+ function printTableCounts(databases) {
43362
+ const rows = databases.flatMap((db2) => db2.tables.map((t) => ({ name: `${db2.database}.${t.table}`, rows: t.rows })));
43363
+ const width = Math.max(0, ...rows.map((r) => r.name.length));
43364
+ for (const r of rows) console.log(` ${r.name.padEnd(width)} ${muted(`${r.rows} row(s)`)}`);
43365
+ }
43332
43366
  function printInspect(d, source) {
43333
43367
  if (d.meta) {
43334
43368
  console.log(bold(d.meta.name));
@@ -43343,9 +43377,17 @@ function printInspect(d, source) {
43343
43377
  console.log("");
43344
43378
  printManifest(d.manifest);
43345
43379
  console.log("");
43380
+ if (d.data) {
43381
+ const tables = d.data.databases.reduce((n, db2) => n + db2.tables.length, 0);
43382
+ console.log(bold(`Data: ${d.data.rows} row(s) in ${tables} table(s), ${formatBytes(d.data.bytes)}`));
43383
+ printTableCounts(d.data.databases);
43384
+ } else {
43385
+ console.log(muted("Data: none (code, migrations and seeds only)"));
43386
+ }
43387
+ console.log("");
43346
43388
  console.log(muted("Load it with `gipity load " + source + "` - always creates a NEW project."));
43347
43389
  }
43348
- var loadCommand = new Command("load").description("Create a new app from a .gip bundle or a GitHub repo").argument("<source>", "A .gip file (from `gipity save`), github:owner/repo[/sub/path][@ref], or a github.com URL").option("--name <name>", "Name for the new project (default: the source's saved name)").option("--inspect", "Peek inside the source - contents, deploy phases, function permissions - without creating anything").option("--json", "Output as JSON").addHelpText("after", "\nLoad always creates a NEW project - it never merges into an existing one.\nGitHub sources need a one-time `gipity github connect` (re-run it to grant more repos).").action((source, opts) => run("Load", async () => {
43390
+ var loadCommand = new Command("load").description("Create a new app from a .gip bundle or a GitHub repo").argument("<source>", "A .gip file (from `gipity save`), github:owner/repo[/sub/path][@ref], or a github.com URL").option("--name <name>", "Name for the new project (default: the source's saved name)").option("--inspect", "Peek inside the source - contents, deploy phases, function permissions, saved data - without creating anything").option("--json", "Output as JSON").addHelpText("after", "\nLoad always creates a NEW project - it never merges into an existing one.\nGitHub sources need a one-time `gipity github connect` (re-run it to grant more repos).").action((source, opts) => run("Load", async () => {
43349
43391
  const github = isGithubSource(source);
43350
43392
  if (!github && /^https?:\/\//i.test(source)) {
43351
43393
  throw new Error("Only GitHub URLs are supported for now - pass github:owner/repo, a github.com URL, or a local .gip file.");
@@ -43409,8 +43451,10 @@ var loadCommand = new Command("load").description("Create a new app from a .gip
43409
43451
  written: data.written,
43410
43452
  failed: data.failed,
43411
43453
  partial,
43412
- applied
43454
+ applied,
43455
+ ...data.data ? { data: data.data } : {}
43413
43456
  }));
43457
+ if (data.data && !data.data.loaded) process.exitCode = 1;
43414
43458
  return;
43415
43459
  }
43416
43460
  console.log(success(`Created "${project.name}" (${project.slug}) from ${sourceLabel}`));
@@ -43423,8 +43467,23 @@ var loadCommand = new Command("load").description("Create a new app from a .gip
43423
43467
  for (const f of data.failed ?? []) console.warn(warning(` ! ${f.path}: ${f.error}`));
43424
43468
  console.warn(warning("The project was still created and linked; the files above are missing from it."));
43425
43469
  }
43470
+ if (data.data?.loaded) {
43471
+ console.log("");
43472
+ console.log(success(`Loaded ${data.data.rows} row(s) into the app's database:`));
43473
+ printTableCounts(data.data.databases);
43474
+ } else if (data.data) {
43475
+ console.log("");
43476
+ console.warn(warning(`The bundle's rows were not loaded: ${data.data.error}`));
43477
+ console.warn(warning("The project was still created and linked, with an empty database. Delete it with `gipity project delete` and load again once the problem is fixed."));
43478
+ process.exitCode = 1;
43479
+ }
43426
43480
  console.log("");
43427
- console.log(`${muted("Next:")} cd ${dir} && ${brand("gipity deploy dev")}`);
43481
+ if (data.data?.loaded) {
43482
+ console.log(`${muted("Next:")} cd ${dir} && ${brand("gipity deploy prod")}`);
43483
+ console.log(muted("The rows are in the prod database. `gipity env create dev --data` gives you a dev copy with them."));
43484
+ } else {
43485
+ console.log(`${muted("Next:")} cd ${dir} && ${brand("gipity deploy dev")}`);
43486
+ }
43428
43487
  }));
43429
43488
 
43430
43489
  // src/commands/logs.ts
@@ -44531,8 +44590,9 @@ secretsCommand.command("rm <name>").alias("delete").description("Delete a secret
44531
44590
  init_api();
44532
44591
  init_config();
44533
44592
  init_colors();
44534
- var notifyCommand = new Command("notify").description("Web push notifications").addHelpText("after", "\nGipity Notify: send a test notification or inspect subscriptions.");
44535
- notifyCommand.command("test").description("Send a test push notification to yourself, a user, or everyone").option("--to <who>", "Recipient: a user guid, comma-separated guids, or 'all'", "all").option("--title <text>", "Notification title", "Test notification").option("--body <text>", "Notification body", "Hello from Gipity Notify \u{1F44B}").option("--url <url>", "URL to open when the notification is clicked").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44593
+ import { readFileSync as readFileSync22 } from "fs";
44594
+ var notifyCommand = new Command("notify").description("Push notifications (web and native iOS)").addHelpText("after", "\nGipity Notify: send a test notification, inspect subscriptions, or set up iOS push (notify apns).");
44595
+ notifyCommand.command("test").description("Send a test push notification (web and iOS devices) to a user or everyone").option("--to <who>", "Recipient: a user guid, comma-separated guids, or 'all'", "all").option("--title <text>", "Notification title", "Test notification").option("--body <text>", "Notification body", "Hello from Gipity Notify \u{1F44B}").option("--url <url>", "URL to open when the notification is clicked").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44536
44596
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
44537
44597
  const to2 = opts.to === "all" ? "all" : opts.to.includes(",") ? opts.to.split(",").map((s) => s.trim()) : opts.to;
44538
44598
  const notification = { title: opts.title, body: opts.body };
@@ -44545,11 +44605,22 @@ notifyCommand.command("test").description("Send a test push notification to your
44545
44605
  console.log(JSON.stringify(res.data));
44546
44606
  return;
44547
44607
  }
44548
- const { sent, failed, pruned } = res.data;
44549
- if (sent > 0) console.log(success(`\u2713 Sent to ${sent} device${sent === 1 ? "" : "s"}.`));
44550
- else console.log(warning("No devices received it: has anyone enabled notifications in the app yet? (gipity notify subs)"));
44608
+ const { sent, failed, pruned, results } = res.data;
44609
+ if (sent > 0) {
44610
+ const ios = results.filter((r) => r.transport === "apns" && r.status === "sent").length;
44611
+ const web = sent - ios;
44612
+ const split = ios > 0 ? ` (${web} web, ${ios} iOS)` : "";
44613
+ console.log(success(`\u2713 Sent to ${sent} device${sent === 1 ? "" : "s"}${split}.`));
44614
+ } else {
44615
+ console.log(warning("No devices received it: has anyone enabled notifications in the app yet? (gipity notify subs)"));
44616
+ }
44551
44617
  if (pruned) console.log(muted(` pruned ${pruned} expired subscription${pruned === 1 ? "" : "s"}`));
44552
- if (failed) console.log(muted(` ${failed} delivery failure${failed === 1 ? "" : "s"}`));
44618
+ if (failed) {
44619
+ console.log(muted(` ${failed} delivery failure${failed === 1 ? "" : "s"}`));
44620
+ for (const r of results) {
44621
+ if (r.status === "failed" && r.transport === "apns") console.log(muted(` iOS device ...${r.device}: ${r.reason ?? "failed"}`));
44622
+ }
44623
+ }
44553
44624
  }));
44554
44625
  notifyCommand.command("subs").description("Show how many push subscriptions this app has, per user").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44555
44626
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
@@ -44562,9 +44633,12 @@ notifyCommand.command("subs").description("Show how many push subscriptions this
44562
44633
  }
44563
44634
  const { total, byUser } = res.data;
44564
44635
  console.log(bold(`${total} subscription${total === 1 ? "" : "s"} across ${byUser.length} user${byUser.length === 1 ? "" : "s"}`));
44565
- for (const r of byUser) console.log(` ${r.user_guid} ${muted(`${r.count} device${r.count === 1 ? "" : "s"}`)}`);
44636
+ for (const r of byUser) {
44637
+ const split = r.ios > 0 ? ` (${r.web} web, ${r.ios} iOS)` : "";
44638
+ console.log(` ${r.user_guid} ${muted(`${r.count} device${r.count === 1 ? "" : "s"}${split}`)}`);
44639
+ }
44566
44640
  }));
44567
- notifyCommand.command("rm").description("Remove a user's push subscriptions (e.g. on account deletion)").requiredOption("--user <guid>", "User guid whose subscriptions to remove").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44641
+ notifyCommand.command("rm").description("Remove a user's push subscriptions and iOS devices (e.g. on account deletion)").requiredOption("--user <guid>", "User guid whose subscriptions to remove").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44568
44642
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
44569
44643
  const res = await post(
44570
44644
  `/api/${config.projectGuid}/services/notify/remove`,
@@ -44576,6 +44650,67 @@ notifyCommand.command("rm").description("Remove a user's push subscriptions (e.g
44576
44650
  }
44577
44651
  console.log(success(`Removed ${res.data.removed} subscription${res.data.removed === 1 ? "" : "s"} for ${opts.user}.`));
44578
44652
  }));
44653
+ function printApns(c) {
44654
+ if (!c.configured) {
44655
+ console.log(warning("iOS push is not set up. Run: gipity notify apns set --team-id <id> --key-id <id> --p8 <AuthKey.p8> --bundle-id <id>"));
44656
+ return;
44657
+ }
44658
+ console.log(` Team ID: ${c.teamId}`);
44659
+ console.log(` Key ID: ${c.keyId}`);
44660
+ console.log(` Bundle ID: ${c.bundleId}`);
44661
+ console.log(` Default: ${c.defaultEnvironment} ${muted("(for devices that register without an environment)")}`);
44662
+ }
44663
+ var apnsCommand = new Command("apns").description("Set up push notifications for a native iOS app (your own Apple key)").addHelpText("after", `
44664
+ Create an APNs key in your Apple Developer account (Certificates, Identifiers
44665
+ & Profiles > Keys > + > Apple Push Notifications service), download the
44666
+ AuthKey_<KEYID>.p8 file, then:
44667
+
44668
+ gipity notify apns set --team-id ABCDE12345 --key-id KEY1234567 \\
44669
+ --p8 ./AuthKey_KEY1234567.p8 --bundle-id com.example.myapp
44670
+
44671
+ The key is stored encrypted and never shown again. Your app registers each
44672
+ device with POST /api/<app-guid>/notify/devices; notify() then reaches it.`);
44673
+ apnsCommand.command("set").description("Store the APNs key for this app (all environments use it)").requiredOption("--team-id <id>", "Your 10-character Apple Team ID").requiredOption("--key-id <id>", "The 10-character Key ID of the APNs key").requiredOption("--p8 <file>", "Path to the AuthKey_<KEYID>.p8 file").requiredOption("--bundle-id <id>", "Your app bundle id, e.g. com.example.myapp").option("--sandbox", "Devices that register without an environment use the sandbox (development builds)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44674
+ const { config } = await resolveProjectContext({ projectOverride: opts.project });
44675
+ let p8;
44676
+ try {
44677
+ p8 = readFileSync22(opts.p8, "utf-8");
44678
+ } catch {
44679
+ throw new Error(`Can't read ${opts.p8}. Pass the path to the AuthKey_<KEYID>.p8 file from Apple.`);
44680
+ }
44681
+ const res = await put(`/api/${config.projectGuid}/services/notify/apns`, {
44682
+ team_id: opts.teamId,
44683
+ key_id: opts.keyId,
44684
+ bundle_id: opts.bundleId,
44685
+ p8,
44686
+ sandbox: !!opts.sandbox
44687
+ });
44688
+ if (opts.json) {
44689
+ console.log(JSON.stringify(res.data));
44690
+ return;
44691
+ }
44692
+ console.log(success("\u2713 iOS push is set up."));
44693
+ printApns(res.data);
44694
+ }));
44695
+ apnsCommand.command("show").description("Show the APNs setup for this app (never the key itself)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44696
+ const { config } = await resolveProjectContext({ projectOverride: opts.project });
44697
+ const res = await get(`/api/${config.projectGuid}/services/notify/apns`);
44698
+ if (opts.json) {
44699
+ console.log(JSON.stringify(res.data));
44700
+ return;
44701
+ }
44702
+ printApns(res.data);
44703
+ }));
44704
+ apnsCommand.command("rm").description("Remove the APNs key (iOS devices stop receiving notifications)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Notify", async () => {
44705
+ const { config } = await resolveProjectContext({ projectOverride: opts.project });
44706
+ const res = await del(`/api/${config.projectGuid}/services/notify/apns`);
44707
+ if (opts.json) {
44708
+ console.log(JSON.stringify(res.data));
44709
+ return;
44710
+ }
44711
+ console.log(res.data.removed ? success("\u2713 APNs key removed.") : warning("No APNs key was set."));
44712
+ }));
44713
+ notifyCommand.addCommand(apnsCommand);
44579
44714
 
44580
44715
  // src/commands/bug.ts
44581
44716
  init_api();
@@ -45215,7 +45350,7 @@ emailCommand.command("log").description("Recent email() sends and skipped attemp
45215
45350
  init_api();
45216
45351
  init_config();
45217
45352
  init_colors();
45218
- import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync17, readFileSync as readFileSync22 } from "fs";
45353
+ import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync17, readFileSync as readFileSync23 } from "fs";
45219
45354
  import { resolve as resolvePath2, dirname as dirname13, relative as relative5, isAbsolute as isAbsolute2, basename as basename7 } from "path";
45220
45355
 
45221
45356
  // src/commands/generate-async.ts
@@ -45588,7 +45723,7 @@ function readInputImages(paths) {
45588
45723
  return paths.map((p) => {
45589
45724
  let buf;
45590
45725
  try {
45591
- buf = readFileSync22(p);
45726
+ buf = readFileSync23(p);
45592
45727
  } catch (e) {
45593
45728
  throw new Error(`can't read --input image ${p} (${e.code || e.message}).`);
45594
45729
  }
@@ -45863,7 +45998,7 @@ Examples:
45863
45998
  console.error(error("Pass --lyrics or --lyrics-file, not both."));
45864
45999
  process.exit(1);
45865
46000
  }
45866
- const lyrics = opts.lyricsFile ? readFileSync22(opts.lyricsFile, "utf8").trim() : opts.lyrics;
46001
+ const lyrics = opts.lyricsFile ? readFileSync23(opts.lyricsFile, "utf8").trim() : opts.lyrics;
45867
46002
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/music`, {
45868
46003
  prompt: prompt2,
45869
46004
  duration_seconds: opts.duration,
@@ -45934,7 +46069,7 @@ var generateCommand = addGenerationSubcommands(new Command("generate").descripti
45934
46069
  // src/commands/ask.ts
45935
46070
  init_api();
45936
46071
  init_config();
45937
- import { readFileSync as readFileSync23, fstatSync } from "fs";
46072
+ import { readFileSync as readFileSync24, fstatSync } from "fs";
45938
46073
  init_colors();
45939
46074
  var IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
45940
46075
  var MAX_WARM_WAIT_S = 90;
@@ -45959,7 +46094,7 @@ function stdinIsPiped() {
45959
46094
  }
45960
46095
  function readTextFile(path5) {
45961
46096
  try {
45962
- return readFileSync23(path5 === "-" ? 0 : path5, "utf8");
46097
+ return readFileSync24(path5 === "-" ? 0 : path5, "utf8");
45963
46098
  } catch (e) {
45964
46099
  throw new Error(`can't read --file ${path5} (${e.code || e.message}).`);
45965
46100
  }
@@ -45969,7 +46104,7 @@ function readImage(path5) {
45969
46104
  if (!IMAGE_TYPES.has(mime)) throw new Error(`--image ${path5} is ${mime}; use a png, jpg, gif or webp.`);
45970
46105
  let buf;
45971
46106
  try {
45972
- buf = readFileSync23(path5);
46107
+ buf = readFileSync24(path5);
45973
46108
  } catch (e) {
45974
46109
  throw new Error(`can't read --image ${path5} (${e.code || e.message}).`);
45975
46110
  }
@@ -46026,14 +46161,14 @@ Examples:
46026
46161
  init_api();
46027
46162
  init_config();
46028
46163
  init_colors();
46029
- import { existsSync as existsSync19, readFileSync as readFileSync24 } from "fs";
46164
+ import { existsSync as existsSync19, readFileSync as readFileSync25 } from "fs";
46030
46165
  import { join as join24 } from "path";
46031
46166
  function readInstalledKitReadme(name) {
46032
46167
  const root = getProjectRoot() ?? process.cwd();
46033
46168
  const kitDir = join24(root, "src", "packages", name);
46034
46169
  if (!existsSync19(join24(kitDir, "package.json"))) return null;
46035
46170
  const readme = join24(kitDir, "README.md");
46036
- return existsSync19(readme) ? readFileSync24(readme, "utf-8") : null;
46171
+ return existsSync19(readme) ? readFileSync25(readme, "utf-8") : null;
46037
46172
  }
46038
46173
  function slugify2(title) {
46039
46174
  return title.toLowerCase().replace(/[`*_]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -46817,12 +46952,12 @@ var locationCommand = new Command("location").description("Show location").argum
46817
46952
  }));
46818
46953
 
46819
46954
  // src/commands/doctor.ts
46820
- import { existsSync as existsSync22, readFileSync as readFileSync26, statSync as statSync9 } from "fs";
46955
+ import { existsSync as existsSync22, readFileSync as readFileSync27, statSync as statSync9 } from "fs";
46821
46956
  import { join as join26, resolve as resolve17 } from "path";
46822
46957
  import { homedir as homedir17 } from "os";
46823
46958
 
46824
46959
  // src/updater/state.ts
46825
- import { readFileSync as readFileSync25, writeFileSync as writeFileSync18, mkdirSync as mkdirSync16, existsSync as existsSync21 } from "fs";
46960
+ import { readFileSync as readFileSync26, writeFileSync as writeFileSync18, mkdirSync as mkdirSync16, existsSync as existsSync21 } from "fs";
46826
46961
  import { dirname as dirname15, join as join25, resolve as resolve16 } from "path";
46827
46962
  import { homedir as homedir16 } from "os";
46828
46963
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -46837,7 +46972,7 @@ function findPkgRoot() {
46837
46972
  let dir = dirname15(fileURLToPath4(import.meta.url));
46838
46973
  for (; ; ) {
46839
46974
  try {
46840
- if (JSON.parse(readFileSync25(join25(dir, "package.json"), "utf-8")).name === "gipity") return dir;
46975
+ if (JSON.parse(readFileSync26(join25(dir, "package.json"), "utf-8")).name === "gipity") return dir;
46841
46976
  } catch {
46842
46977
  }
46843
46978
  const up2 = dirname15(dir);
@@ -46864,7 +46999,7 @@ function ensureDir() {
46864
46999
  function readState() {
46865
47000
  if (!existsSync21(STATE_FILE)) return { ...DEFAULT_STATE };
46866
47001
  try {
46867
- return { ...DEFAULT_STATE, ...JSON.parse(readFileSync25(STATE_FILE, "utf-8")) };
47002
+ return { ...DEFAULT_STATE, ...JSON.parse(readFileSync26(STATE_FILE, "utf-8")) };
46868
47003
  } catch {
46869
47004
  return { ...DEFAULT_STATE };
46870
47005
  }
@@ -46876,7 +47011,7 @@ function writeState(state) {
46876
47011
  function readSettings() {
46877
47012
  if (!existsSync21(SETTINGS_FILE)) return { ...DEFAULT_SETTINGS };
46878
47013
  try {
46879
- return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync25(SETTINGS_FILE, "utf-8")) };
47014
+ return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync26(SETTINGS_FILE, "utf-8")) };
46880
47015
  } catch {
46881
47016
  return { ...DEFAULT_SETTINGS };
46882
47017
  }
@@ -46913,7 +47048,7 @@ function localVersion() {
46913
47048
  const pkgPath = join26(LOCAL_PKG_DIR, "package.json");
46914
47049
  if (!existsSync22(pkgPath)) return null;
46915
47050
  try {
46916
- return JSON.parse(readFileSync26(pkgPath, "utf-8")).version ?? null;
47051
+ return JSON.parse(readFileSync27(pkgPath, "utf-8")).version ?? null;
46917
47052
  } catch {
46918
47053
  return null;
46919
47054
  }
@@ -46921,7 +47056,7 @@ function localVersion() {
46921
47056
  function shimVersion() {
46922
47057
  try {
46923
47058
  const url = new URL("../../package.json", import.meta.url);
46924
- return JSON.parse(readFileSync26(url, "utf-8")).version;
47059
+ return JSON.parse(readFileSync27(url, "utf-8")).version;
46925
47060
  } catch {
46926
47061
  return "unknown";
46927
47062
  }
@@ -47251,13 +47386,13 @@ var updateCommand = new Command("update").description("Update the CLI").option("
47251
47386
  init_api();
47252
47387
  init_utils();
47253
47388
  init_colors();
47254
- import { existsSync as existsSync26, readFileSync as readFileSync29, unlinkSync as unlinkSync9 } from "fs";
47389
+ import { existsSync as existsSync26, readFileSync as readFileSync30, unlinkSync as unlinkSync9 } from "fs";
47255
47390
  import { spawn as spawn2 } from "child_process";
47256
47391
 
47257
47392
  // src/relay/daemon.ts
47258
47393
  init_platform();
47259
47394
  init_config();
47260
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync19, existsSync as existsSync25, readFileSync as readFileSync28, writeFileSync as writeFileSync20, chmodSync as chmodSync4, closeSync as closeSync4, openSync as openSync4, unlinkSync as unlinkSync8 } from "fs";
47395
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync19, existsSync as existsSync25, readFileSync as readFileSync29, writeFileSync as writeFileSync20, chmodSync as chmodSync4, closeSync as closeSync4, openSync as openSync4, unlinkSync as unlinkSync8 } from "fs";
47261
47396
  import { stat, readFile } from "fs/promises";
47262
47397
  import { createInterface as createInterface2 } from "readline";
47263
47398
  import { homedir as homedir19, hostname as hostname6, platform as osPlatform3, loadavg as loadavg2, freemem as freemem2, totalmem as totalmem2, cpus as cpus2 } from "os";
@@ -49584,7 +49719,7 @@ async function resolveCwdForProject(d) {
49584
49719
  const configPath = join30(path5, ".gipity.json");
49585
49720
  if (existsSync25(configPath)) {
49586
49721
  try {
49587
- const cfg = JSON.parse(readFileSync28(configPath, "utf-8"));
49722
+ const cfg = JSON.parse(readFileSync29(configPath, "utf-8"));
49588
49723
  if (cfg.projectGuid === d.project_guid) return { cwd: path5, bootstrapped: false };
49589
49724
  log2("warn", "project dir exists but guid mismatch - using it anyway", {
49590
49725
  path: path5,
@@ -50167,7 +50302,7 @@ relayCommand.command("stop").description("Stop the background service").option("
50167
50302
  console.log(muted("Background service isn't running."));
50168
50303
  return;
50169
50304
  }
50170
- const pid = parseInt(readFileSync29(pidPath, "utf-8").trim(), 10);
50305
+ const pid = parseInt(readFileSync30(pidPath, "utf-8").trim(), 10);
50171
50306
  if (!pid || isNaN(pid)) {
50172
50307
  console.error(error("PID file is empty or malformed."));
50173
50308
  process.exit(1);
@@ -50316,7 +50451,7 @@ relayCommand.command("revoke").description("Revoke and forget this device").acti
50316
50451
  }
50317
50452
  const pidPath = getDaemonPidPath();
50318
50453
  if (existsSync26(pidPath)) {
50319
- const pid = parseInt(readFileSync29(pidPath, "utf-8").trim(), 10);
50454
+ const pid = parseInt(readFileSync30(pidPath, "utf-8").trim(), 10);
50320
50455
  if (pid && !isNaN(pid)) {
50321
50456
  try {
50322
50457
  process.kill(pid, "SIGTERM");
@@ -50335,7 +50470,7 @@ relayCommand.command("log").description("Tail the service log").option("-n, --li
50335
50470
  }
50336
50471
  const lines = parseInt(opts.lines, 10) || 100;
50337
50472
  try {
50338
- const all = readFileSync29(path5, "utf-8").split("\n");
50473
+ const all = readFileSync30(path5, "utf-8").split("\n");
50339
50474
  const tail2 = all.slice(-lines - 1).join("\n");
50340
50475
  process.stdout.write(tail2);
50341
50476
  } catch (err) {
@@ -50511,7 +50646,7 @@ init_api();
50511
50646
  init_auth();
50512
50647
  init_utils();
50513
50648
  init_colors();
50514
- import { existsSync as existsSync27, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync30, writeFileSync as writeFileSync21 } from "fs";
50649
+ import { existsSync as existsSync27, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync31, writeFileSync as writeFileSync21 } from "fs";
50515
50650
  import { homedir as homedir20, platform as osPlatform4 } from "os";
50516
50651
  import { join as join31, resolve as resolve19 } from "path";
50517
50652
  init_agents();
@@ -50524,7 +50659,7 @@ function removeInstallerPathLines() {
50524
50659
  if (!existsSync27(rc2)) continue;
50525
50660
  let text;
50526
50661
  try {
50527
- text = readFileSync30(rc2, "utf-8");
50662
+ text = readFileSync31(rc2, "utf-8");
50528
50663
  } catch {
50529
50664
  continue;
50530
50665
  }
@@ -50692,8 +50827,100 @@ var uninstallCommand = new Command("uninstall").description("Uninstall Gipity").
50692
50827
  });
50693
50828
 
50694
50829
  // src/commands/approval.ts
50830
+ import { readFileSync as readFileSync32 } from "node:fs";
50695
50831
  init_api();
50696
50832
  init_colors();
50833
+
50834
+ // src/approval-verify.ts
50835
+ import { createHash as createHash6, createPublicKey, verify as verify2 } from "node:crypto";
50836
+ var CHALLENGE_PREFIX = "gipity-approval:v1|";
50837
+ function canonicalJson(value) {
50838
+ if (value === null) return "null";
50839
+ switch (typeof value) {
50840
+ case "boolean":
50841
+ case "string":
50842
+ return JSON.stringify(value);
50843
+ case "number":
50844
+ if (!Number.isFinite(value)) throw new Error("payload contains a non-finite number");
50845
+ return JSON.stringify(value);
50846
+ case "object": {
50847
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
50848
+ const obj = value;
50849
+ return `{${Object.keys(obj).sort().map((k7) => {
50850
+ if (obj[k7] === void 0) throw new Error(`payload field '${k7}' is undefined`);
50851
+ return `${JSON.stringify(k7)}:${canonicalJson(obj[k7])}`;
50852
+ }).join(",")}}`;
50853
+ }
50854
+ default:
50855
+ throw new Error(`payload contains a value JSON can't represent (${typeof value})`);
50856
+ }
50857
+ }
50858
+ var sha256 = (data) => createHash6("sha256").update(data).digest();
50859
+ function payloadHash(payload) {
50860
+ return sha256(canonicalJson(payload)).toString("hex");
50861
+ }
50862
+ function approvalChallenge(id2, hash, expiresAt) {
50863
+ return sha256(`${CHALLENGE_PREFIX}${id2}|${hash}|${expiresAt}`).toString("base64url");
50864
+ }
50865
+ function sameKey(a, b7) {
50866
+ if (a.kty !== b7.kty) return false;
50867
+ if (a.kty === "EC") return a.crv === b7.crv && a.x === b7.x && a.y === b7.y;
50868
+ if (a.kty === "OKP") return a.crv === b7.crv && a.x === b7.x;
50869
+ if (a.kty === "RSA") return a.n === b7.n && a.e === b7.e;
50870
+ return false;
50871
+ }
50872
+ function verifySignature(jwk, data, signature) {
50873
+ const key = createPublicKey({ key: { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y, n: jwk.n, e: jwk.e }, format: "jwk" });
50874
+ return verify2(jwk.kty === "OKP" ? null : "sha256", data, key, signature);
50875
+ }
50876
+ function verifyApproval(approval, opts) {
50877
+ const checks = [];
50878
+ const add = (check, ok, detail) => checks.push(detail ? { check, ok, detail } : { check, ok });
50879
+ const proof = approval.proof;
50880
+ if (!proof) {
50881
+ add("proof present", false, `approval is ${approval.status}; there is no passkey proof`);
50882
+ return { ok: false, pinned: !!opts.pinnedJwk, checks };
50883
+ }
50884
+ const expectedRpId = new URL(opts.expectedOrigin).hostname;
50885
+ const hash = payloadHash(opts.payload);
50886
+ add("payload hash matches", hash === approval.payloadHash, hash === approval.payloadHash ? void 0 : `local ${hash}`);
50887
+ const challenge = approvalChallenge(approval.id, hash, approval.expiresAt);
50888
+ let clientData = {};
50889
+ const clientDataBytes = Buffer.from(proof.clientDataJSON, "base64url");
50890
+ try {
50891
+ clientData = JSON.parse(clientDataBytes.toString("utf8"));
50892
+ } catch {
50893
+ add("clientDataJSON parses", false);
50894
+ }
50895
+ add("clientData type is webauthn.get", clientData.type === "webauthn.get");
50896
+ add("clientData challenge matches", clientData.challenge === challenge);
50897
+ add(
50898
+ "clientData origin matches",
50899
+ clientData.origin === opts.expectedOrigin,
50900
+ clientData.origin === opts.expectedOrigin ? void 0 : `got ${String(clientData.origin)}`
50901
+ );
50902
+ const authData = Buffer.from(proof.authenticatorData, "base64url");
50903
+ const rpIdOk = authData.length >= 37 && authData.subarray(0, 32).equals(sha256(expectedRpId));
50904
+ add("rpIdHash matches", rpIdOk);
50905
+ const flags = authData.length >= 37 ? authData[32] : 0;
50906
+ add("user present (UP)", (flags & 1) !== 0);
50907
+ add("user verified (UV)", (flags & 4) !== 0);
50908
+ const key = opts.pinnedJwk ?? proof.publicKeyJwk;
50909
+ if (opts.pinnedJwk) add("proof key is the pinned key", sameKey(opts.pinnedJwk, proof.publicKeyJwk));
50910
+ let sigOk = false;
50911
+ try {
50912
+ sigOk = verifySignature(key, Buffer.concat([authData, sha256(clientDataBytes)]), Buffer.from(proof.signature, "base64url"));
50913
+ } catch {
50914
+ sigOk = false;
50915
+ }
50916
+ add("signature verifies", sigOk);
50917
+ const expiresMs = Date.parse(approval.expiresAt);
50918
+ const notExpired = Number.isFinite(expiresMs) && expiresMs > (opts.now ?? Date.now());
50919
+ add("not expired", notExpired, notExpired ? void 0 : `expired at ${approval.expiresAt}`);
50920
+ return { ok: checks.every((c) => c.ok), pinned: !!opts.pinnedJwk, checks };
50921
+ }
50922
+
50923
+ // src/commands/approval.ts
50697
50924
  function timeAgo(dateStr) {
50698
50925
  const diffMs = Date.now() - new Date(dateStr).getTime();
50699
50926
  const mins = Math.floor(diffMs / 6e4);
@@ -50715,7 +50942,7 @@ approvalCommand.command("list").description("List pending approvals").addOption(
50715
50942
  res.data,
50716
50943
  opts,
50717
50944
  "No approvals.",
50718
- (a) => `${a.guid} ${a.title} ${muted(`[${a.status}] ${timeAgo(a.created_at)}`)}`
50945
+ (a) => `${a.guid} ${a.title} ${muted(`[${a.status}${a.kind === "passkey" ? ", passkey" : ""}] ${timeAgo(a.created_at)}`)}`
50719
50946
  );
50720
50947
  }));
50721
50948
  approvalCommand.command("create <title...>").description("Create a pending approval").option("--description <text>", "Detailed context").addOption(new Option("--type <type>", "Approval type").choices(["yes_no", "choice", "text"]).default("yes_no")).option("--choices <a,b,c>", "Comma-separated options (for --type choice)").option("--prompt <text>", "Custom prompt shown to the user").option("--expires-in <minutes>", "Minutes until expiry (default: 10080 = 7d)").option("--json", "Output as JSON").action((titleParts, opts) => run("Create", async () => {
@@ -50780,6 +51007,68 @@ approvalCommand.command("cancel <guid>").description("Cancel a pending approval
50780
51007
  await post(`/approvals/${guid}/cancel`, {});
50781
51008
  printResult(success(`Cancelled ${guid}.`), opts, { guid, cancelled: true });
50782
51009
  }));
51010
+ function requireGuid(guid) {
51011
+ if (!guid.startsWith("ap_")) throw new Error("Expected approval guid like ap_xxxxxxxx");
51012
+ }
51013
+ approvalCommand.command("show <guid>").description("Show one approval (for a passkey approval: status, payload hash, expiry and whether it carries a signed proof)").option("--json", "Output as JSON").action((guid, opts) => run("Show", async () => {
51014
+ requireGuid(guid);
51015
+ const { data } = await get(`/approvals/${guid}`);
51016
+ const lines = [`${data.guid} ${data.title}`];
51017
+ if (data.description) lines.push(muted(data.description));
51018
+ if (data.passkey) {
51019
+ const p = data.passkey;
51020
+ lines.push(
51021
+ `Status: ${p.status} (passkey)`,
51022
+ `Approver: ${p.approver}`,
51023
+ `Payload hash: ${p.payloadHash}`,
51024
+ `Expires: ${p.expiresAt}`,
51025
+ `Resolved: ${p.resolvedAt ?? "-"}`,
51026
+ `Consumed: ${p.consumedAt ?? "-"}`,
51027
+ `Proof: ${p.proof ? `signed by passkey ${p.proof.credentialId}` : "none"}`
51028
+ );
51029
+ } else {
51030
+ lines.push(`Status: ${data.status}`);
51031
+ }
51032
+ printResult(lines.join("\n"), opts, data);
51033
+ }));
51034
+ approvalCommand.command("passkeys").description("List the passkeys you approve with (add them in the browser at the printed link)").option("--remove <id>", "Remove one of your passkeys by id").option("--json", "Output as JSON").action((opts) => run("Passkeys", async () => {
51035
+ if (opts.remove) {
51036
+ await del(`/approvals/passkeys/credentials/${encodeURIComponent(opts.remove)}`);
51037
+ printResult(success(`Removed ${opts.remove}.`), opts, { id: opts.remove, removed: true });
51038
+ return;
51039
+ }
51040
+ const { data } = await get("/approvals/passkeys/credentials");
51041
+ const manageUrl = `${getBaseUrl()}/approvals/passkeys`;
51042
+ if (opts.json) {
51043
+ console.log(JSON.stringify({ passkeys: data, manageUrl }));
51044
+ return;
51045
+ }
51046
+ console.log(data.length ? data.map((k7) => `${k7.id} ${k7.label ?? "Passkey"} ${muted(`added ${k7.createdAt.slice(0, 10)}${k7.lastUsedAt ? `, last used ${k7.lastUsedAt.slice(0, 10)}` : ""}`)}`).join("\n") : "No passkeys yet.");
51047
+ console.log(muted(`Add or remove passkeys in the browser: ${manageUrl}`));
51048
+ }));
51049
+ approvalCommand.command("verify <guid>").description("Verify a passkey approval offline, as a device does: recompute the payload hash and challenge and check the passkey signature").requiredOption("--payload <file>", "JSON file with the exact payload the approval is for").option("--key <file>", "The approver's public key (JWK JSON) pinned at enrollment; without it the proof's own key is used and the result says so").option("--origin <url>", "Relying-party origin the passkey signed for (default: the API base)").option("--json", "Output as JSON").action((guid, opts) => run("Verify", async () => {
51050
+ requireGuid(guid);
51051
+ const payload = JSON.parse(readFileSync32(opts.payload, "utf8"));
51052
+ const pinnedJwk = opts.key ? JSON.parse(readFileSync32(opts.key, "utf8")) : void 0;
51053
+ const { data } = await get(`/approvals/${guid}`);
51054
+ if (!data.passkey) throw new Error(`${guid} is not a passkey approval`);
51055
+ const expectedOrigin = new URL(opts.origin ?? getBaseUrl()).origin;
51056
+ const result = verifyApproval(data.passkey, { payload, pinnedJwk, expectedOrigin });
51057
+ if (opts.json) {
51058
+ console.log(JSON.stringify({ id: guid, status: data.passkey.status, ...result }));
51059
+ } else {
51060
+ for (const c of result.checks) console.log(`${c.ok ? "ok " : "FAIL"} ${c.check}${c.detail ? muted(` (${c.detail})`) : ""}`);
51061
+ if (!result.pinned) console.log(muted("Key not pinned: checked against the key in the proof. Pass --key with the approver key you pinned."));
51062
+ if (result.ok && data.passkey.status !== "approved") console.log(muted(`Signature is valid, but the approval is ${data.passkey.status}.`));
51063
+ }
51064
+ if (!result.ok) {
51065
+ if (opts.json) {
51066
+ process.exitCode = 1;
51067
+ return;
51068
+ }
51069
+ throw new Error("verification failed");
51070
+ }
51071
+ }));
50783
51072
 
50784
51073
  // src/commands/gmail.ts
50785
51074
  init_api();
@@ -50830,7 +51119,7 @@ gmailCommand.command("reply").description("Reply to a Gmail thread. Get thread-i
50830
51119
  }));
50831
51120
 
50832
51121
  // src/commands/text.ts
50833
- import { readFileSync as readFileSync31 } from "fs";
51122
+ import { readFileSync as readFileSync33 } from "fs";
50834
51123
  init_colors();
50835
51124
 
50836
51125
  // src/helpers/text-analysis.ts
@@ -50985,10 +51274,10 @@ function areAnagrams(a, b7) {
50985
51274
 
50986
51275
  // src/commands/text.ts
50987
51276
  function resolveInput(args, opts) {
50988
- if (opts.file) return readFileSync31(opts.file, "utf-8");
51277
+ if (opts.file) return readFileSync33(opts.file, "utf-8");
50989
51278
  if (args.length) return args.join(" ");
50990
51279
  try {
50991
- return readFileSync31(0, "utf-8");
51280
+ return readFileSync33(0, "utf-8");
50992
51281
  } catch {
50993
51282
  return "";
50994
51283
  }
@@ -51284,11 +51573,11 @@ function installOutputTrace(label2) {
51284
51573
  installOutputTrace("index");
51285
51574
  var __dirname = dirname17(fileURLToPath5(import.meta.url));
51286
51575
  installNetworking();
51287
- var pkg = JSON.parse(readFileSync32(resolve20(__dirname, "../package.json"), "utf-8"));
51576
+ var pkg = JSON.parse(readFileSync34(resolve20(__dirname, "../package.json"), "utf-8"));
51288
51577
  function versionLabel() {
51289
51578
  const base = `v${pkg.version}`;
51290
51579
  try {
51291
- const info2 = JSON.parse(readFileSync32(resolve20(__dirname, "build-info.json"), "utf-8"));
51580
+ const info2 = JSON.parse(readFileSync34(resolve20(__dirname, "build-info.json"), "utf-8"));
51292
51581
  if (info2?.sha) return `${base} (dev ${info2.sha}${info2.dirty ? ", modified" : ""})`;
51293
51582
  } catch {
51294
51583
  }