gipity 1.1.27 → 1.1.28

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,13 +6993,13 @@ 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\`). 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). \`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\`). 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
 
7000
7000
  ## Use first-party services before reaching outside
7001
7001
 
7002
- Gipity ships first-party services for what apps usually pull from third parties - auth, location/geocoding, LLM, image/audio/video generation, transcription, file uploads, realtime, web push notifications (Gipity Notify - no VAPID keys, no Firebase/OneSignal; works on iOS home-screen web apps), and email (from a deployed app's function with the injected \`email()\` service - \`services: ['email']\`, no SMTP/SendGrid/Nodemailer; check it with \`gipity email test <to>\`). Before calling an external API or adding an npm package for one of these, check \`gipity skill list\` for a match. First-party services need no API keys, cost less, and keep data in-house. Reach outside only when the catalog has no equivalent - and say so when you do.
7002
+ Gipity ships first-party services for what apps usually pull from third parties - auth, location/geocoding, LLM, image/audio/video generation, transcription, file uploads, realtime, web push notifications (Gipity Notify - no VAPID keys, no Firebase/OneSignal; works on iOS home-screen web apps), semantic search (\`embed()\` + pgvector in the app's own DB - no Pinecone/Weaviate/vector DB), and email (from a deployed app's function with the injected \`email()\` service - \`services: ['email']\`, no SMTP/SendGrid/Nodemailer; check it with \`gipity email test <to>\`). Before calling an external API or adding an npm package for one of these, check \`gipity skill list\` for a match. First-party services need no API keys, cost less, and keep data in-house. Reach outside only when the catalog has no equivalent - and say so when you do.
7003
7003
 
7004
7004
  ## Don't guess Gipity facts - look them up
7005
7005
 
@@ -7118,8 +7118,8 @@ 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-audio\` - sound effects, music, transcription
7121
- - \`app-auth\` - sign in with Gipity, popup vs redirect
7122
- - \`app-files\` - uploads, variants, file listing
7121
+ - \`app-auth\` - sign in: Gipity accounts or app-owned users (Google, email code), popup vs redirect
7122
+ - \`app-files\` - uploads, then displaying files and the storage helper (ownership check, delete)
7123
7123
  - \`app-image\` - text-to-image AND instruction editing (pass \`images\` to edit an uploaded photo); providers, sizes, aspect ratios
7124
7124
  - \`app-llm\` - chat completions, streaming, image input
7125
7125
  - \`app-location\` - user location & reverse geocoding for deployed apps (first-party - no third-party geocoder)
@@ -7127,13 +7127,15 @@ App services skills (load before calling \`/services/*\` endpoints):
7127
7127
  - \`app-payments\` - charge end-users real money - Stripe one-time purchases & subscriptions, via the stripe kit (gipity add stripe)
7128
7128
  - \`app-realtime\` - Gipity Realtime rooms, relay vs state
7129
7129
  - \`app-tts\` - voices, models, dialogue, languages, word timestamps
7130
+ - \`app-users\` - app-owned users: Google/Apple/Discord/email-code sign-in, own credentials, hooks, gipity project users
7131
+ - \`app-vector-search\` - semantic search, RAG, 'find similar' and fuzzy match over the app's own DB - embed() service + pre-installed pgvector and pg_trgm, no vector DB
7130
7132
  - \`app-video\` - Gipity Video: models, aspect, resolution
7131
7133
 
7132
7134
  App development skills:
7133
7135
  - \`agent-deploy\` - headless auth via agent API tokens (GIPITY_TOKEN) for unattended deploys
7134
7136
  - \`app-database\` - app Postgres database: migrations, the db helper, transactions, table permissions
7135
7137
  - \`app-debugging\` - debug a deployed app: page inspect/eval, screenshots, function logs
7136
- - \`app-development\` - functions, database, and API
7138
+ - \`app-development\` - functions, database, API, and services a function can call
7137
7139
  - \`app-import\` - import apps from GitHub/.gip bundles (incl. Vercel/Replit/Lovable porting) and export any project as a portable .gip - gipity load/save, gipity github connect
7138
7140
  - \`app-records\` - Gipity Records: declared tables \u2192 validated CRUD, provenance, workflows, auto UI
7139
7141
  - \`app-testing\` - testing deployed app functions (ctx.fn.call/callAs, the per-file test DB)
@@ -9160,7 +9162,8 @@ function with401Hint(status, message) {
9160
9162
  function apiErrorFrom(res, json, label2, hint = true) {
9161
9163
  const err = json?.error ?? {};
9162
9164
  const message = err.message || `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ""} from ${label2}`;
9163
- return new ApiError(res.status, err.code || "UNKNOWN", hint ? with401Hint(res.status, message) : message, json?.data);
9165
+ const data = json?.data ?? (typeof err.retry_after_s === "number" ? { retry_after_s: err.retry_after_s } : void 0);
9166
+ return new ApiError(res.status, err.code || "UNKNOWN", hint ? with401Hint(res.status, message) : message, data);
9164
9167
  }
9165
9168
  async function getHeaders() {
9166
9169
  return {
@@ -34365,7 +34368,7 @@ var {
34365
34368
  init_config();
34366
34369
  init_setup();
34367
34370
  init_utils();
34368
- import { readFileSync as readFileSync30 } from "fs";
34371
+ import { readFileSync as readFileSync31 } from "fs";
34369
34372
  import { fileURLToPath as fileURLToPath4 } from "url";
34370
34373
  import { dirname as dirname16, resolve as resolve18 } from "path";
34371
34374
 
@@ -35123,6 +35126,34 @@ function walkLocal(root, ignorePatterns, baseline) {
35123
35126
  walk(root);
35124
35127
  return result;
35125
35128
  }
35129
+ function localEmptyDirs(root, ignorePatterns) {
35130
+ const empty = [];
35131
+ function walk(dir) {
35132
+ let entries;
35133
+ try {
35134
+ entries = readdirSync4(dir, { withFileTypes: true });
35135
+ } catch {
35136
+ return true;
35137
+ }
35138
+ let hasFile = false;
35139
+ for (const entry of entries) {
35140
+ const full = join10(dir, entry.name);
35141
+ const rel2 = relative(root, full).replace(/\\/g, "/");
35142
+ if (shouldIgnore(rel2, ignorePatterns)) continue;
35143
+ if (entry.isDirectory()) {
35144
+ if (shouldIgnore(rel2 + "/", ignorePatterns) || shouldIgnore(rel2 + "/x", ignorePatterns)) continue;
35145
+ if (existsSync8(join10(full, CONFIG_FILE2))) continue;
35146
+ if (walk(full)) hasFile = true;
35147
+ else empty.push(rel2);
35148
+ } else if (entry.isFile()) {
35149
+ hasFile = true;
35150
+ }
35151
+ }
35152
+ return hasFile;
35153
+ }
35154
+ walk(root);
35155
+ return empty.filter((d) => !empty.some((o) => o.startsWith(d + "/"))).sort();
35156
+ }
35126
35157
  async function ensureLocalHashes(root, local, paths) {
35127
35158
  for (const path5 of paths) {
35128
35159
  const info2 = local.get(path5);
@@ -36523,9 +36554,6 @@ var SUBSTITUTABLE_EXTS = /* @__PURE__ */ new Set([
36523
36554
  function escapeHtml(s) {
36524
36555
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
36525
36556
  }
36526
- function jsEscape(s) {
36527
- return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
36528
- }
36529
36557
  var ACCENT_PALETTE = [
36530
36558
  "#f59e0b",
36531
36559
  "#f97316",
@@ -36612,7 +36640,6 @@ function buildTemplateVars(v7) {
36612
36640
  }, null, 2).replace(/<\//g, "<\\/");
36613
36641
  return {
36614
36642
  "{{TITLE}}": safeTitle,
36615
- "{{JS_TITLE}}": jsEscape(v7.projectName),
36616
36643
  "{{PROJECT_GUID}}": v7.projectGuid,
36617
36644
  "{{DATABASE}}": slug,
36618
36645
  "{{HEAD_BLOCK}}": buildHeadBlock(v7),
@@ -39078,7 +39105,7 @@ ${bold("Transient console errors")} ${muted(`(${transientErrors.length}, not rep
39078
39105
  if (crossOriginErrors.length > 0) {
39079
39106
  console.log(`
39080
39107
  ${bold("Cross-origin console errors")} ${muted(`(${crossOriginErrors.length}, source hidden by the browser)`)}:`);
39081
- console.log(muted(`Message-less: the throwing <script> lacks CORS, so the browser hides its source and there's no own-code stack to chase. Gipity's injected SDK is itself cross-origin, so if your app loads no third-party CDN scripts these are platform noise; ignore them. If your app DOES load a third-party <script>, add crossorigin="anonymous" to that tag to surface the real error.`));
39108
+ console.log(muted(`Message-less: a <script> loaded without CORS threw, so the browser hides the message. Your own scripts and the Gipity SDK report full errors, so this is a third-party <script> (e.g. a CDN): add crossorigin="anonymous" to that tag to see the real error. Don't assume it's harmless: confirm the page works with gipity page eval <url> "<expr>".`));
39082
39109
  }
39083
39110
  const isImplicitFavicon = (entry) => {
39084
39111
  const urlPart = entry.replace(/\s*\([^)]*\)\s*$/, "");
@@ -39418,6 +39445,12 @@ init_api();
39418
39445
  init_config();
39419
39446
  init_colors();
39420
39447
  init_utils();
39448
+ var TABLE_CELL_MAX = 200;
39449
+ function tableCell(value) {
39450
+ const text = value === null || value === void 0 ? "NULL" : typeof value === "object" ? JSON.stringify(value) : String(value);
39451
+ if (text.length <= TABLE_CELL_MAX) return text;
39452
+ return `${text.slice(0, 60)}\u2026 (${text.length} chars; --json for all)`;
39453
+ }
39421
39454
  var dbCommand = new Command("db").description("Manage databases");
39422
39455
  dbCommand.command("query <sql>").description("Run SQL").option("--database <name>", "Database name").option("--field <path>", "Print only this field of the result (dot path, e.g. rows.0.status)").option("--json", "Output as JSON").action((sql, opts) => run("Query", async () => {
39423
39456
  const config = requireConfig2();
@@ -39443,7 +39476,7 @@ dbCommand.command("query <sql>").description("Run SQL").option("--database <name
39443
39476
  const columns = Object.keys(res.data.rows[0]);
39444
39477
  console.log(columns.join(" "));
39445
39478
  for (const row2 of res.data.rows) {
39446
- console.log(columns.map((c) => String(row2[c] ?? "NULL")).join(" "));
39479
+ console.log(columns.map((c) => tableCell(row2[c])).join(" "));
39447
39480
  }
39448
39481
  }
39449
39482
  if (res.data.affectedRows !== void 0) {
@@ -39773,6 +39806,7 @@ function isWriteTarget(code, p) {
39773
39806
  const afterInputFlag = /(?:^|[\s'"`])(?:-i|--input)[= ]\s*['"`]?$/.test(before);
39774
39807
  return cmd === "ffmpeg" && !afterInputFlag;
39775
39808
  }
39809
+ var MAX_INPUT_DIRS = 500;
39776
39810
  function resolveRelativeCwd() {
39777
39811
  const configPath = getConfigPath();
39778
39812
  if (!configPath) return void 0;
@@ -39916,14 +39950,19 @@ GCC/Rust).
39916
39950
  process.exit(1);
39917
39951
  }
39918
39952
  }
39953
+ let inputDirs;
39919
39954
  if (getConfigPath()) {
39920
39955
  await sync({ interactive: false, progress: opts.json ? void 0 : createProgressReporter() });
39956
+ const root = dirname11(getConfigPath());
39957
+ const dirs = localEmptyDirs(root, effectiveIgnore(root, requireConfig2().ignore));
39958
+ if (dirs.length) inputDirs = dirs.slice(0, MAX_INPUT_DIRS);
39921
39959
  }
39922
39960
  const doRun = () => post(`/projects/${config.projectGuid}/sandbox/execute`, {
39923
39961
  code: source,
39924
39962
  language,
39925
39963
  timeout: isNaN(timeout) ? 30 : timeout,
39926
39964
  input_files: opts.input,
39965
+ input_dirs: inputDirs,
39927
39966
  cwd,
39928
39967
  // The filter must run SERVER-side (in the output extractor): skipping
39929
39968
  // only in the CLI would still write the files into project storage and
@@ -40028,7 +40067,291 @@ init_colors();
40028
40067
  init_utils();
40029
40068
  import { join as join19 } from "path";
40030
40069
  import { mkdirSync as mkdirSync11 } from "fs";
40070
+
40071
+ // src/commands/project-auth.ts
40072
+ init_api();
40073
+ init_config();
40074
+ init_colors();
40075
+ import { readFileSync as readFileSync18 } from "fs";
40031
40076
  var AUTH_MODES = ["gipity", "app", "both"];
40077
+ var PROVIDERS = ["google", "apple", "discord"];
40078
+ var PROVIDER_LABEL = { google: "Google", apple: "Apple", discord: "Discord" };
40079
+ function fail(msg) {
40080
+ console.error(error(msg));
40081
+ process.exit(1);
40082
+ }
40083
+ function credentialsLabel(p) {
40084
+ if (p.credentials === "own") return "own";
40085
+ if (p.credentials === "shared") return "shared (Gipity)";
40086
+ return "not set";
40087
+ }
40088
+ function formatStatus(s) {
40089
+ const lines = [
40090
+ `Sign-in: ${s.auth_mode}`,
40091
+ `Unique names: ${s.unique_player_names ? "on" : "off"}`,
40092
+ `Email codes: ${s.email_code ? "on" : "off"}`,
40093
+ ""
40094
+ ];
40095
+ const rows = s.providers.map((p) => [PROVIDER_LABEL[p.provider] ?? p.provider, credentialsLabel(p), p.note ?? ""]);
40096
+ const w0 = Math.max("Provider".length, ...rows.map((r) => r[0].length));
40097
+ const w12 = Math.max("Credentials".length, ...rows.map((r) => r[1].length));
40098
+ lines.push(bold(`${"Provider".padEnd(w0)} ${"Credentials".padEnd(w12)} Note`));
40099
+ for (const r of rows) lines.push(`${r[0].padEnd(w0)} ${r[1].padEnd(w12)} ${muted(r[2])}`.trimEnd());
40100
+ for (const w of s.warnings) lines.push("", warning(w));
40101
+ lines.push("", muted("Set up a provider: gipity project auth provider <google|apple|discord>"));
40102
+ return lines.join("\n");
40103
+ }
40104
+ var SETUP_STEPS = {
40105
+ google: (r) => [
40106
+ "Google Cloud console > APIs & Services > Credentials > Create credentials > OAuth client ID.",
40107
+ "Application type: Web application.",
40108
+ `Under "Authorized redirect URIs" add: ${r}`,
40109
+ "Copy the client ID and client secret.",
40110
+ "APIs & Services > OAuth consent screen: set your app name and logo (this is what users see).",
40111
+ "The basic scopes (openid email profile) need no Google verification.",
40112
+ "gipity project auth provider google --client-id <id> --client-secret <secret>"
40113
+ ],
40114
+ apple: (r) => [
40115
+ "Apple Developer > Certificates, Identifiers & Profiles > Identifiers > add a Services ID.",
40116
+ " Its identifier is your client ID.",
40117
+ `Enable Sign in with Apple on it, register your domain and the return URL: ${r}`,
40118
+ "Keys > add a key with Sign in with Apple enabled. Note its Key ID and download the .p8 file (only once).",
40119
+ "Your Team ID is on the Membership details page.",
40120
+ "gipity project auth provider apple --client-id <services-id> --team-id <team> --key-id <key> --private-key-file AuthKey_XXXX.p8"
40121
+ ],
40122
+ discord: (r) => [
40123
+ "Discord Developer Portal > Applications > your application > OAuth2.",
40124
+ `Add the redirect: ${r}`,
40125
+ "Copy the client ID and reset/copy the client secret.",
40126
+ "gipity project auth provider discord --client-id <id> --client-secret <secret>"
40127
+ ]
40128
+ };
40129
+ function formatProvider(p) {
40130
+ const name = PROVIDER_LABEL[p.provider];
40131
+ const lines = [
40132
+ `${bold(name)}: ${credentialsLabel(p)}${p.available ? "" : muted(" (off)")}`
40133
+ ];
40134
+ if (p.note) lines.push(muted(p.note));
40135
+ lines.push("", `Redirect URI: ${p.redirect_uri}`, "", "Use your own credentials:");
40136
+ let n = 0;
40137
+ for (const step of SETUP_STEPS[p.provider](p.redirect_uri)) {
40138
+ lines.push(step.startsWith(" ") ? ` ${step.trim()}` : `${++n}. ${step}`);
40139
+ }
40140
+ if (p.provider === "google") {
40141
+ lines.push("", muted("Switching Google from shared to your own credentials keeps every existing user (a Google account has the same id under any client)."));
40142
+ }
40143
+ if (p.provider !== "apple" && p.credentials === "own") {
40144
+ lines.push("", muted(`Back to Gipity's shared credentials: gipity project auth provider ${p.provider} --shared`));
40145
+ }
40146
+ return lines.join("\n");
40147
+ }
40148
+ function registerAuthCommand(projectCommand2) {
40149
+ const auth = projectCommand2.command("auth [mode]").description("Show or set who can sign in to the deployed app: gipity, app (its own users), or both").enablePositionalOptions().addHelpText("after", `
40150
+ Modes:
40151
+ gipity Sign in with Gipity only (default)
40152
+ app Users sign in to this app alone, without a Gipity account:
40153
+ Google, Apple, Discord and email codes for web apps (the hosted sign-in
40154
+ page / Gipity.auth.signIn), Steam (POST /api/<guid>/auth/steam) and guest
40155
+ devices (POST /api/<guid>/auth/guest) for games
40156
+ both Either
40157
+
40158
+ Sign-in providers:
40159
+ gipity project auth provider <google|apple|discord> show setup steps and the redirect URI
40160
+ Google and Discord work at once on Gipity's shared credentials; Apple needs your own.
40161
+ Manage the app's users: gipity project users
40162
+
40163
+ --unique-names on|off
40164
+ On: no two players of this app can have the same display name (case and
40165
+ lookalike letters ignored). A taken name is refused with DISPLAY_NAME_TAKEN;
40166
+ GET /api/<guid>/auth/player/name-available?name=... checks one and suggests
40167
+ free alternatives. Players who already share a name keep it, and sign in with
40168
+ nameConflict: true until they rename. Off by default.
40169
+
40170
+ Steam also needs the Steamworks publisher key and AppID:
40171
+ gipity secrets set STEAM_WEB_API_KEY <key>
40172
+ gipity secrets set STEAM_APP_ID <appid>
40173
+ See: gipity skill read steam-game`).option("--unique-names <on|off>", "Require unique player display names in this app").option("--json", "Output as JSON").action((mode, opts) => run("Auth", async () => {
40174
+ const config = requireConfig2();
40175
+ const body = {};
40176
+ if (mode !== void 0) {
40177
+ if (!AUTH_MODES.includes(mode)) {
40178
+ fail(`Unknown mode "${mode}". Use one of: ${AUTH_MODES.join(", ")} (or: provider <name>).`);
40179
+ }
40180
+ body.auth_mode = mode;
40181
+ }
40182
+ if (opts.uniqueNames !== void 0) {
40183
+ if (opts.uniqueNames !== "on" && opts.uniqueNames !== "off") {
40184
+ fail(`--unique-names takes "on" or "off", not "${opts.uniqueNames}".`);
40185
+ }
40186
+ body.unique_player_names = opts.uniqueNames === "on";
40187
+ }
40188
+ if (Object.keys(body).length === 0) {
40189
+ const res2 = await get(`/projects/${config.projectGuid}/auth`);
40190
+ printResult(formatStatus(res2.data), opts, res2.data);
40191
+ return;
40192
+ }
40193
+ const res = await put(`/projects/${config.projectGuid}`, body);
40194
+ const lines = [];
40195
+ if (body.auth_mode) lines.push(success(`Sign-in set to "${body.auth_mode}".`));
40196
+ if (body.unique_player_names !== void 0) {
40197
+ lines.push(success(`Unique names ${body.unique_player_names ? "on" : "off"}.`));
40198
+ const sharing = res.data.players_sharing_names ?? 0;
40199
+ if (sharing > 0) {
40200
+ lines.push(muted(`${sharing} existing player${sharing === 1 ? "" : "s"} share${sharing === 1 ? "s" : ""} a name with an earlier player. They keep it, and sign in with nameConflict: true until they rename.`));
40201
+ }
40202
+ }
40203
+ printResult(lines.join("\n"), opts, { ...body, ...res.data.players_sharing_names !== void 0 ? { players_sharing_names: res.data.players_sharing_names } : {} });
40204
+ }));
40205
+ auth.command("provider <name>").description("Show setup for a sign-in provider (google, apple, discord), set your own credentials, or go back to shared").option("--client-id <id>", "OAuth client ID (Apple: the Services ID)").option("--client-secret <secret>", "OAuth client secret (Google, Discord)").option("--team-id <id>", "Apple Team ID").option("--key-id <id>", "Apple Sign in with Apple key ID").option("--private-key-file <path>", "Apple .p8 private key file").option("--shared", "Remove your own credentials and use Gipity's shared ones").option("--json", "Output as JSON").action((name, opts) => run("Provider", async () => {
40206
+ const provider = name.toLowerCase();
40207
+ if (!PROVIDERS.includes(provider)) fail(`Unknown provider "${name}". Use one of: ${PROVIDERS.join(", ")}.`);
40208
+ const config = requireConfig2();
40209
+ const base = `/projects/${config.projectGuid}/auth/providers/${provider}`;
40210
+ const label2 = PROVIDER_LABEL[provider];
40211
+ const credFlags = ["clientId", "clientSecret", "teamId", "keyId", "privateKeyFile"].filter((k7) => opts[k7] !== void 0);
40212
+ if (opts.shared) {
40213
+ if (credFlags.length) fail("--shared cannot be combined with credential flags.");
40214
+ const res2 = await del(base);
40215
+ const msg = res2.data.credentials === "shared" ? success(`${label2} sign-in now uses Gipity's shared credentials.`) : success(`Removed your ${label2} credentials.`) + "\n" + muted(`${label2} sign-in is off until you set your own credentials.`);
40216
+ printResult(msg, opts, res2.data);
40217
+ return;
40218
+ }
40219
+ if (credFlags.length === 0) {
40220
+ const res2 = await get(`/projects/${config.projectGuid}/auth`);
40221
+ const p = res2.data.providers.find((x) => x.provider === provider);
40222
+ if (!p) fail(`${label2} sign-in is not available.`);
40223
+ printResult(formatProvider(p), opts, p);
40224
+ return;
40225
+ }
40226
+ let body;
40227
+ if (provider === "apple") {
40228
+ const missing = [["clientId", "--client-id"], ["teamId", "--team-id"], ["keyId", "--key-id"], ["privateKeyFile", "--private-key-file"]].filter(([k7]) => !opts[k7]).map(([, f]) => f);
40229
+ if (missing.length) fail(`Apple needs ${missing.join(", ")}. See: gipity project auth provider apple`);
40230
+ if (opts.clientSecret) fail("Apple takes --team-id, --key-id and --private-key-file, not --client-secret.");
40231
+ let privateKey;
40232
+ try {
40233
+ privateKey = readFileSync18(opts.privateKeyFile, "utf-8");
40234
+ } catch (err) {
40235
+ fail(`Cannot read ${opts.privateKeyFile}: ${err.code === "ENOENT" ? "no such file" : err.message}`);
40236
+ }
40237
+ if (!privateKey.includes("PRIVATE KEY")) fail(`${opts.privateKeyFile} does not look like a .p8 private key.`);
40238
+ body = { client_id: opts.clientId, team_id: opts.teamId, key_id: opts.keyId, private_key: privateKey };
40239
+ } else {
40240
+ const missing = [["clientId", "--client-id"], ["clientSecret", "--client-secret"]].filter(([k7]) => !opts[k7]).map(([, f]) => f);
40241
+ if (missing.length) fail(`${label2} needs ${missing.join(" and ")}. See: gipity project auth provider ${provider}`);
40242
+ const extra = ["teamId", "keyId", "privateKeyFile"].filter((k7) => opts[k7] !== void 0);
40243
+ if (extra.length) fail(`--team-id, --key-id and --private-key-file are for Apple only.`);
40244
+ body = { client_id: opts.clientId, client_secret: opts.clientSecret };
40245
+ }
40246
+ const res = await put(base, body);
40247
+ const lines = [success(`${label2} sign-in now uses your own credentials.`)];
40248
+ if (provider === "google") lines.push(muted("Existing Google users keep their accounts."));
40249
+ printResult(lines.join("\n"), opts, res.data);
40250
+ }));
40251
+ }
40252
+
40253
+ // src/commands/project-users.ts
40254
+ init_api();
40255
+ init_config();
40256
+ init_colors();
40257
+ init_utils();
40258
+ import { writeFileSync as writeFileSync12 } from "fs";
40259
+ var EXPORT_PAGE_SIZE = 500;
40260
+ function fail2(msg) {
40261
+ console.error(error(msg));
40262
+ process.exit(1);
40263
+ }
40264
+ function usersPath(params) {
40265
+ const q = new URLSearchParams();
40266
+ if (params.search) q.set("search", params.search);
40267
+ if (params.limit !== void 0) q.set("limit", String(params.limit));
40268
+ if (params.cursor) q.set("cursor", params.cursor);
40269
+ const qs = q.toString();
40270
+ return `/projects/${requireConfig2().projectGuid}/app-users${qs ? `?${qs}` : ""}`;
40271
+ }
40272
+ function day(iso) {
40273
+ return iso ? iso.slice(0, 10) : "-";
40274
+ }
40275
+ function formatTable(users) {
40276
+ const head = ["GUID", "Name", "Email", "Providers", "Created", "Last sign-in"];
40277
+ const rows = users.map((u) => [u.guid, u.display_name ?? "-", u.email ?? "-", u.providers.join(", ") || "-", day(u.created_at), day(u.last_login_at)]);
40278
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
40279
+ const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd();
40280
+ return [bold(line(head)), ...rows.map(line)].join("\n");
40281
+ }
40282
+ function csvField(value) {
40283
+ return /[",\r\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
40284
+ }
40285
+ function toCsv(users) {
40286
+ const cols = ["guid", "display_name", "email", "providers", "created_at", "last_login_at"];
40287
+ const rows = users.map((u) => [u.guid, u.display_name ?? "", u.email ?? "", u.providers.join(";"), u.created_at, u.last_login_at ?? ""]);
40288
+ return [cols, ...rows].map((r) => r.map(csvField).join(",")).join("\n") + "\n";
40289
+ }
40290
+ function registerUsersCommand(projectCommand2) {
40291
+ const users = projectCommand2.command("users").description("Manage the app's own users (app sign-in mode): list, export, delete, sign out").addHelpText("after", `
40292
+ These are the people who signed in to this app with Google, Apple, Discord, an
40293
+ email code, Steam or a guest device. They belong to the app, not to Gipity.
40294
+ gipity project users --search ann find users by name or email
40295
+ gipity project users export -o users.csv every user, as CSV (or --format json)
40296
+ gipity project users delete <guid> erase a user (runs the app's user_deleted hooks)
40297
+ gipity project users signout <guid> end all of a user's web sessions`);
40298
+ users.command("list", { isDefault: true }).description("List the app's users").option("--search <text>", "Match name or email").option("--limit <n>", "How many to show (1-500, default 100)").option("--json", "Output as JSON").action((opts) => run("Users", async () => {
40299
+ let limit;
40300
+ if (opts.limit !== void 0) {
40301
+ limit = Number(opts.limit);
40302
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500) fail2(`--limit takes a whole number from 1 to 500, not "${opts.limit}".`);
40303
+ }
40304
+ const res = await get(usersPath({ search: opts.search, limit }));
40305
+ const d = res.data;
40306
+ if (opts.json) {
40307
+ console.log(JSON.stringify(d));
40308
+ return;
40309
+ }
40310
+ if (d.users.length === 0) {
40311
+ console.log(muted(opts.search ? `No users match "${opts.search}".` : "No users yet."));
40312
+ return;
40313
+ }
40314
+ console.log(formatTable(d.users));
40315
+ console.log("");
40316
+ console.log(muted(`${d.users.length} of ${d.total} user${d.total === 1 ? "" : "s"}`));
40317
+ if (d.users.length < d.total) {
40318
+ console.log(muted("Narrow with --search, show more with --limit (up to 500), or get them all: gipity project users export"));
40319
+ }
40320
+ }));
40321
+ users.command("export").description("Export every user of the app as CSV or JSON").option("--format <format>", "csv or json", "csv").option("-o, --output <file>", "Write to this file instead of stdout").option("--json", "Output the result as JSON (with -o)").action((opts) => run("Export", async () => {
40322
+ if (opts.format !== "csv" && opts.format !== "json") fail2(`--format takes "csv" or "json", not "${opts.format}".`);
40323
+ const all = [];
40324
+ let cursor = null;
40325
+ do {
40326
+ const res = await get(usersPath({ limit: EXPORT_PAGE_SIZE, cursor }));
40327
+ all.push(...res.data.users);
40328
+ cursor = res.data.next_cursor;
40329
+ } while (cursor);
40330
+ const out = opts.format === "csv" ? toCsv(all) : JSON.stringify(all, null, 2) + "\n";
40331
+ if (!opts.output) {
40332
+ process.stdout.write(out);
40333
+ return;
40334
+ }
40335
+ writeFileSync12(opts.output, out);
40336
+ printResult(success(`Exported ${all.length} user${all.length === 1 ? "" : "s"} to ${opts.output}.`), opts, { file: opts.output, count: all.length, format: opts.format });
40337
+ }));
40338
+ users.command("delete <userGuid>").description("Erase a user and everything the app keeps for them (runs the app's user_deleted hooks)").option("--json", "Output as JSON").action((userGuid, opts) => run("Delete", async () => {
40339
+ const ok = await confirm(`Delete user ${userGuid}? This erases the user and runs the app's user_deleted hooks to remove their data. It cannot be undone.`);
40340
+ if (!ok) {
40341
+ console.log("Cancelled.");
40342
+ return;
40343
+ }
40344
+ const res = await del(`/projects/${requireConfig2().projectGuid}/app-users/${encodeURIComponent(userGuid)}`);
40345
+ printResult(success(`Deleted user ${userGuid}.`), opts, { guid: userGuid, ...res.data });
40346
+ }));
40347
+ users.command("signout <userGuid>").description("Sign a user out everywhere (revoke all of the user's web sessions)").option("--json", "Output as JSON").action((userGuid, opts) => run("Sign out", async () => {
40348
+ const res = await post(`/projects/${requireConfig2().projectGuid}/app-users/${encodeURIComponent(userGuid)}/signout`);
40349
+ const n = res.data.signed_out_sessions;
40350
+ printResult(success(`Signed out ${userGuid}: ${n} session${n === 1 ? "" : "s"} ended.`), opts, { guid: userGuid, ...res.data });
40351
+ }));
40352
+ }
40353
+
40354
+ // src/commands/project.ts
40032
40355
  var projectCommand = new Command("project").description("Manage projects").enablePositionalOptions().argument("[name]", "Switch to project by name/slug").option("--json", "Output as JSON").action((name, opts) => run("Project", async () => {
40033
40356
  const config = requireConfig2();
40034
40357
  if (name) {
@@ -40144,68 +40467,13 @@ projectCommand.command("info").description("Show current project").option("--jso
40144
40467
  if (p.description) console.log(`Desc: ${p.description}`);
40145
40468
  }
40146
40469
  }));
40147
- projectCommand.command("auth [mode]").description("Show or set who can sign in to the deployed app: gipity, app (Steam / guest players), or both").addHelpText("after", `
40148
- Modes:
40149
- gipity Sign in with Gipity only (default)
40150
- app Players sign in to this app alone, without a Gipity account:
40151
- Steam (POST /api/<guid>/auth/steam) or a guest device (POST /api/<guid>/auth/guest)
40152
- both Either
40153
-
40154
- --unique-names on|off
40155
- On: no two players of this app can have the same display name (case and
40156
- lookalike letters ignored). A taken name is refused with DISPLAY_NAME_TAKEN;
40157
- GET /api/<guid>/auth/player/name-available?name=... checks one and suggests
40158
- free alternatives. Players who already share a name keep it, and sign in with
40159
- nameConflict: true until they rename. Off by default.
40160
-
40161
- Steam also needs the Steamworks publisher key and AppID:
40162
- gipity secrets set STEAM_WEB_API_KEY <key>
40163
- gipity secrets set STEAM_APP_ID <appid>
40164
- See: gipity skill read steam-game`).option("--unique-names <on|off>", "Require unique player display names in this app").option("--json", "Output as JSON").action((mode, opts) => run("Auth", async () => {
40165
- const config = requireConfig2();
40166
- const body = {};
40167
- if (mode !== void 0) {
40168
- if (!AUTH_MODES.includes(mode)) {
40169
- console.error(error(`Unknown mode "${mode}". Use one of: ${AUTH_MODES.join(", ")}.`));
40170
- process.exit(1);
40171
- }
40172
- body.auth_mode = mode;
40173
- }
40174
- if (opts.uniqueNames !== void 0) {
40175
- if (opts.uniqueNames !== "on" && opts.uniqueNames !== "off") {
40176
- console.error(error(`--unique-names takes "on" or "off", not "${opts.uniqueNames}".`));
40177
- process.exit(1);
40178
- }
40179
- body.unique_player_names = opts.uniqueNames === "on";
40180
- }
40181
- if (Object.keys(body).length === 0) {
40182
- const res2 = await get(`/projects/${config.projectGuid}`);
40183
- const p = res2.data;
40184
- printResult(
40185
- `Sign-in: ${p.auth_mode}
40186
- Unique names: ${p.unique_player_names ? "on" : "off"}`,
40187
- opts,
40188
- { auth_mode: p.auth_mode, unique_player_names: p.unique_player_names }
40189
- );
40190
- return;
40191
- }
40192
- const res = await put(`/projects/${config.projectGuid}`, body);
40193
- const lines = [];
40194
- if (body.auth_mode) lines.push(success(`Sign-in set to "${body.auth_mode}".`));
40195
- if (body.unique_player_names !== void 0) {
40196
- lines.push(success(`Unique names ${body.unique_player_names ? "on" : "off"}.`));
40197
- const sharing = res.data.players_sharing_names ?? 0;
40198
- if (sharing > 0) {
40199
- lines.push(muted(`${sharing} existing player${sharing === 1 ? "" : "s"} share${sharing === 1 ? "s" : ""} a name with an earlier player. They keep it, and sign in with nameConflict: true until they rename.`));
40200
- }
40201
- }
40202
- printResult(lines.join("\n"), opts, { ...body, ...res.data.players_sharing_names !== void 0 ? { players_sharing_names: res.data.players_sharing_names } : {} });
40203
- }));
40470
+ registerAuthCommand(projectCommand);
40471
+ registerUsersCommand(projectCommand);
40204
40472
 
40205
40473
  // src/commands/workflow.ts
40206
40474
  init_api();
40207
40475
  init_config();
40208
- import { existsSync as existsSync15, mkdirSync as mkdirSync12, writeFileSync as writeFileSync12 } from "fs";
40476
+ import { existsSync as existsSync15, mkdirSync as mkdirSync12, writeFileSync as writeFileSync13 } from "fs";
40209
40477
  import { join as join20 } from "path";
40210
40478
  init_colors();
40211
40479
  function mergedOpts(cmd) {
@@ -40301,11 +40569,11 @@ async function listWorkflows(opts) {
40301
40569
  console.log(muted(`Project: ${config.projectSlug} (use --all for every project)`));
40302
40570
  }
40303
40571
  printList(scoped.data, opts, opts.all || !config ? "No workflows." : `No workflows in ${config.projectSlug}.`, (w) => {
40304
- const statusText = w.is_active ? success("on") : error("off");
40572
+ const statusText2 = w.is_active ? success("on") : error("off");
40305
40573
  const cron = w.cron_expression ? ` ${muted(`cron: ${w.cron_expression}`)}` : "";
40306
40574
  const table = w.trigger_table ? ` ${muted(`table: ${w.trigger_table}`)}` : "";
40307
40575
  const proj = w.project_slug ? ` ${muted(`(${w.project_slug})`)}` : "";
40308
- const line = `${bold(w.name)} [${statusText}] ${muted(w.trigger_type)}${cron}${table}${proj}`;
40576
+ const line = `${bold(w.name)} [${statusText2}] ${muted(w.trigger_type)}${cron}${table}${proj}`;
40309
40577
  return w.description ? `${line}
40310
40578
  ${muted(w.description)}` : line;
40311
40579
  });
@@ -40424,7 +40692,7 @@ workflowCommand.command("create").description("Create a workflow from a YAML fil
40424
40692
  const local = join20(root, HEARTBEAT_PATH);
40425
40693
  if (!existsSync15(local)) {
40426
40694
  mkdirSync12(join20(root, "workflows"), { recursive: true });
40427
- writeFileSync12(local, HEARTBEAT_YAML);
40695
+ writeFileSync13(local, HEARTBEAT_YAML);
40428
40696
  }
40429
40697
  await pushFile(local);
40430
40698
  }
@@ -40730,6 +40998,64 @@ creditsCommand.command("usage").description("Show recent usage").option("--limit
40730
40998
  });
40731
40999
  }));
40732
41000
 
41001
+ // src/commands/account.ts
41002
+ init_api();
41003
+ init_colors();
41004
+ init_utils();
41005
+ var NSFW_TERMS = [
41006
+ "Turning on NSFW services lets this account use adult (NSFW) image models.",
41007
+ "",
41008
+ "By turning it on you confirm that:",
41009
+ " - you are 18 or older;",
41010
+ " - nothing you make involves minors, ever;",
41011
+ " - you will not make sexual images of real people;",
41012
+ " - you will not make content showing sexual violence or non-consent;",
41013
+ " - you are responsible for what your apps show and to whom.",
41014
+ "",
41015
+ "Prompts are checked for safety and kept for abuse review. Gipity may turn this off.",
41016
+ "While it is on, app payments (Stripe Connect) stop working for your apps.",
41017
+ "Buying credits and your plan are not affected."
41018
+ ].join("\n");
41019
+ function renderState(s) {
41020
+ console.log(`NSFW services: ${s.allow_nsfw_services ? bold("on") : dim("off")}`);
41021
+ if (s.nsfw_attested_at) console.log(muted(` Terms accepted: ${s.nsfw_attested_at.slice(0, 10)}`));
41022
+ if (s.allow_nsfw_services) console.log(muted(" App payments (Stripe Connect) are off while this is on."));
41023
+ else if (!s.self_serve_open) console.log(muted(" Not open for self-serve yet."));
41024
+ }
41025
+ var accountCommand = new Command("account").description("Account settings").addHelpText("after", "\nAccount-level settings for your Gipity account, e.g. `gipity account nsfw status`.");
41026
+ var nsfwCommand = accountCommand.command("nsfw").description("Allow NSFW services (adult image models) for this account");
41027
+ nsfwCommand.command("status", { isDefault: true }).description("Show whether NSFW services are on").option("--json", "Output as JSON").action((opts) => run("Account", async () => {
41028
+ const res = await get("/users/me/nsfw");
41029
+ if (opts.json) {
41030
+ console.log(JSON.stringify(res.data));
41031
+ return;
41032
+ }
41033
+ renderState(res.data);
41034
+ }));
41035
+ nsfwCommand.command("on").description("Turn NSFW services on (confirms you are 18+ and accept the adult-content terms)").option("-y, --yes", "Accept the terms without asking").option("--json", "Output as JSON").action((opts) => run("Account", async () => {
41036
+ if (!opts.json) console.log(`${NSFW_TERMS}
41037
+ `);
41038
+ const ok = await confirm(`Turn on ${brand("NSFW services")} and accept these terms?`, { default: "no", skip: opts.yes === true });
41039
+ if (!ok) {
41040
+ console.log(muted("Left off."));
41041
+ process.exit(1);
41042
+ }
41043
+ const res = await patch("/users/me/nsfw", { allow: true, attest: true });
41044
+ if (opts.json) {
41045
+ console.log(JSON.stringify(res.data));
41046
+ return;
41047
+ }
41048
+ renderState(res.data);
41049
+ }));
41050
+ nsfwCommand.command("off").description("Turn NSFW services off (app payments work again)").option("--json", "Output as JSON").action((opts) => run("Account", async () => {
41051
+ const res = await patch("/users/me/nsfw", { allow: false });
41052
+ if (opts.json) {
41053
+ console.log(JSON.stringify(res.data));
41054
+ return;
41055
+ }
41056
+ renderState(res.data);
41057
+ }));
41058
+
40733
41059
  // src/commands/file.ts
40734
41060
  init_api();
40735
41061
  init_config();
@@ -40936,7 +41262,7 @@ init_platform();
40936
41262
  init_auth();
40937
41263
  init_api();
40938
41264
  import { join as join22, dirname as dirname12, resolve as resolve13, basename as basename6, sep as sep6 } from "path";
40939
- import { existsSync as existsSync17, mkdirSync as mkdirSync14, readFileSync as readFileSync19, writeFileSync as writeFileSync14, renameSync as renameSync2, readdirSync as readdirSync8, statSync as statSync8 } from "fs";
41265
+ import { existsSync as existsSync17, mkdirSync as mkdirSync14, readFileSync as readFileSync20, writeFileSync as writeFileSync15, renameSync as renameSync2, readdirSync as readdirSync8, statSync as statSync8 } from "fs";
40940
41266
  import { homedir as homedir15 } from "os";
40941
41267
  import { fileURLToPath as fileURLToPath2 } from "url";
40942
41268
  import { randomUUID } from "crypto";
@@ -41296,14 +41622,14 @@ init_claude_setup();
41296
41622
  init_agents();
41297
41623
 
41298
41624
  // src/prefs.ts
41299
- import { existsSync as existsSync16, mkdirSync as mkdirSync13, readFileSync as readFileSync18, writeFileSync as writeFileSync13 } from "fs";
41625
+ import { existsSync as existsSync16, mkdirSync as mkdirSync13, readFileSync as readFileSync19, writeFileSync as writeFileSync14 } from "fs";
41300
41626
  import { homedir as homedir14 } from "os";
41301
41627
  import { join as join21 } from "path";
41302
41628
  var PREFS_PATH = join21(homedir14(), ".gipity", "prefs.json");
41303
41629
  function readPrefs() {
41304
41630
  if (!existsSync16(PREFS_PATH)) return {};
41305
41631
  try {
41306
- const parsed = JSON.parse(readFileSync18(PREFS_PATH, "utf-8"));
41632
+ const parsed = JSON.parse(readFileSync19(PREFS_PATH, "utf-8"));
41307
41633
  return {
41308
41634
  lastAgent: typeof parsed.lastAgent === "string" ? parsed.lastAgent : void 0
41309
41635
  };
@@ -41316,7 +41642,7 @@ function writePrefs(update) {
41316
41642
  const current = readPrefs();
41317
41643
  const next = { ...current, ...update };
41318
41644
  mkdirSync13(join21(homedir14(), ".gipity"), { recursive: true });
41319
- writeFileSync13(PREFS_PATH, JSON.stringify(next, null, 2) + "\n");
41645
+ writeFileSync14(PREFS_PATH, JSON.stringify(next, null, 2) + "\n");
41320
41646
  } catch {
41321
41647
  }
41322
41648
  }
@@ -41329,7 +41655,7 @@ function readOwnPkg(fromDir) {
41329
41655
  const p = join22(d, "package.json");
41330
41656
  if (existsSync17(p)) {
41331
41657
  try {
41332
- const pkg2 = JSON.parse(readFileSync19(p, "utf-8"));
41658
+ const pkg2 = JSON.parse(readFileSync20(p, "utf-8"));
41333
41659
  if (pkg2.name === "gipity") return pkg2;
41334
41660
  } catch {
41335
41661
  }
@@ -41426,7 +41752,7 @@ function hasStreamJsonFlag(args) {
41426
41752
  function markFolderTrusted(dir) {
41427
41753
  try {
41428
41754
  const file = join22(homedir15(), ".claude.json");
41429
- const cfg = existsSync17(file) ? JSON.parse(readFileSync19(file, "utf-8")) : {};
41755
+ const cfg = existsSync17(file) ? JSON.parse(readFileSync20(file, "utf-8")) : {};
41430
41756
  if (typeof cfg !== "object" || cfg === null) return;
41431
41757
  if (typeof cfg.projects !== "object" || cfg.projects === null) cfg.projects = {};
41432
41758
  const entry = typeof cfg.projects[dir] === "object" && cfg.projects[dir] !== null ? cfg.projects[dir] : {};
@@ -41434,7 +41760,7 @@ function markFolderTrusted(dir) {
41434
41760
  entry.hasTrustDialogAccepted = true;
41435
41761
  cfg.projects[dir] = entry;
41436
41762
  const tmp = `${file}.gipity-tmp`;
41437
- writeFileSync14(tmp, JSON.stringify(cfg, null, 2));
41763
+ writeFileSync15(tmp, JSON.stringify(cfg, null, 2));
41438
41764
  renameSync2(tmp, file);
41439
41765
  } catch {
41440
41766
  }
@@ -43548,7 +43874,7 @@ async function recordsHttp(opts) {
43548
43874
  del: (path5, body) => publicRequest("DELETE", path5, body, headers)
43549
43875
  };
43550
43876
  }
43551
- recordsCommand.command("list").description("List record tables").option("--json", "Output as JSON").action((opts) => run("List", async () => {
43877
+ recordsCommand.command("tables").description("List the tables exposed through Gipity Records").option("--json", "Output as JSON").action((opts) => run("Tables", async () => {
43552
43878
  const config = requireConfig2();
43553
43879
  const res = await get(`/api/${config.projectGuid}/records-config`);
43554
43880
  printList(
@@ -43588,7 +43914,7 @@ recordsCommand.command("config <table>").description("Show or set a table's Reco
43588
43914
  d
43589
43915
  );
43590
43916
  }));
43591
- recordsCommand.command("query <table>").description("List records (full-text search, filter, sort, recycle bin)").option("-q, --q <text>", "Full-text search across the table's text columns (needs `--searchable true` on the table)").option("--filter <filter>", 'AND filter string, "col:op:value" comma-joined. Ops: eq, neq, gt, gte, lt, lte, like, ilike, in (pipe-separated values), is_null, not_null. Full grammar: gipity skill read app-records').option("--any <filter>", 'OR filter group, same grammar and ops as --filter (e.g., "owner:eq:me,shared:eq:true")').option("--sort <sort>", 'Sort string (e.g., "created_at:desc")').option("--limit <n>", "Max rows", "20").option("--offset <n>", "Offset", "0").option("--fields <fields>", "Comma-separated column names").option("--include-deleted", "Include soft-deleted rows (owner/editor)").option("--only-deleted", "Only soft-deleted rows - the recycle bin (owner/editor)").option(ANON_FLAG, ANON_HELP).option("--json", "Output as JSON").action((table, opts) => run("Query", async () => {
43917
+ recordsCommand.command("list <table>").description("List a table's records (full-text search, filter, sort, recycle bin)").option("-q, --q <text>", "Full-text search across the table's text columns (needs `--searchable true` on the table)").option("--filter <filter>", 'AND filter string, "col:op:value" comma-joined. Ops: eq, neq, gt, gte, lt, lte, like, ilike, in (pipe-separated values), is_null, not_null. Full grammar: gipity skill read app-records').option("--any <filter>", 'OR filter group, same grammar and ops as --filter (e.g., "owner:eq:me,shared:eq:true")').option("--sort <sort>", 'Sort string (e.g., "created_at:desc")').option("--limit <n>", "Max rows", "20").option("--offset <n>", "Offset", "0").option("--fields <fields>", "Comma-separated column names").option("--include-deleted", "Include soft-deleted rows (owner/editor)").option("--only-deleted", "Only soft-deleted rows - the recycle bin (owner/editor)").option(ANON_FLAG, ANON_HELP).option("--json", "Output as JSON").action((table, opts) => run("List", async () => {
43592
43918
  const api = await recordsHttp(opts);
43593
43919
  const params = new URLSearchParams();
43594
43920
  if (opts.q) params.set("q", opts.q);
@@ -43649,7 +43975,7 @@ recordsCommand.command("delete <table> <id>").description("Delete a record (soft
43649
43975
  );
43650
43976
  const data = res?.data ?? { table, id: id2, deleted: true, purged: !!opts.purge };
43651
43977
  printResult(
43652
- data.purged ? "Purged - the row and its audit history are gone." : `Deleted. If "${table}" declares a soft-delete column the row is only stamped deleted (see it with \`gipity records query ${table} --only-deleted\`, bring it back with \`gipity records restore ${table} ${id2}\`, remove it for good with \`--purge\`).`,
43978
+ data.purged ? "Purged - the row and its audit history are gone." : `Deleted. If "${table}" declares a soft-delete column the row is only stamped deleted (see it with \`gipity records list ${table} --only-deleted\`, bring it back with \`gipity records restore ${table} ${id2}\`, remove it for good with \`--purge\`).`,
43653
43979
  opts,
43654
43980
  data
43655
43981
  );
@@ -44148,8 +44474,8 @@ jobCommand.command("submit <name> [body]").description("Submit a job (returns a
44148
44474
  } else {
44149
44475
  const tag = res.data.replayed ? warning(" (replayed)") : "";
44150
44476
  console.log(`${bold(res.data.run_guid)} ${muted(res.data.status)}${tag}`);
44151
- const TERMINAL = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44152
- if (!TERMINAL.has(res.data.status)) {
44477
+ const TERMINAL2 = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44478
+ if (!TERMINAL2.has(res.data.status)) {
44153
44479
  console.error(muted(`Block until it finishes: gipity job wait ${res.data.run_guid}`));
44154
44480
  }
44155
44481
  }
@@ -44175,7 +44501,7 @@ jobCommand.command("status <runGuid>").description("Show status of a job run").o
44175
44501
  }));
44176
44502
  jobCommand.command("wait <runGuid>").description("Block until a job run finishes, or exit at --timeout so the shell never hangs (poll again to keep waiting)").option("--timeout <seconds>", "Max seconds to wait before giving up and reporting current progress. Bare number = seconds; an explicit unit (90s) means the same here and on `sandbox run --timeout`.", "90").option("--interval <seconds>", "Seconds between polls", "3").option("--json", "Output as JSON").action((runGuid, opts) => run("Wait", async () => {
44177
44503
  const config = requireConfig2();
44178
- const TERMINAL = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44504
+ const TERMINAL2 = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44179
44505
  const durOpt = parseDuration(opts.timeout, "s");
44180
44506
  const timeoutSec = durOpt ? Math.max(1, Math.round(durOpt.value)) : parseInt(opts.timeout, 10);
44181
44507
  const timeout = Number.isFinite(timeoutSec) && timeoutSec > 0 ? timeoutSec : 90;
@@ -44184,7 +44510,7 @@ jobCommand.command("wait <runGuid>").description("Block until a job run finishes
44184
44510
  const fetchRun = async () => (await get(`/projects/${config.projectGuid}/jobs/runs/${encodeURIComponent(runGuid)}`)).data;
44185
44511
  let r = await fetchRun();
44186
44512
  let lastProgress = "";
44187
- while (!TERMINAL.has(r.status) && Date.now() < deadline) {
44513
+ while (!TERMINAL2.has(r.status) && Date.now() < deadline) {
44188
44514
  if (!opts.json) {
44189
44515
  const prog = r.progress_pct != null ? `${Math.round(r.progress_pct * 100)}%${r.progress_message ? ` (${r.progress_message})` : ""}` : r.status;
44190
44516
  if (prog !== lastProgress) {
@@ -44197,7 +44523,7 @@ jobCommand.command("wait <runGuid>").description("Block until a job run finishes
44197
44523
  await new Promise((res) => setTimeout(res, Math.min(interval * 1e3, remaining)));
44198
44524
  r = await fetchRun();
44199
44525
  }
44200
- const done = TERMINAL.has(r.status);
44526
+ const done = TERMINAL2.has(r.status);
44201
44527
  if (opts.json) {
44202
44528
  console.log(JSON.stringify(done ? r : { ...r, waiting: true, timed_out: true }));
44203
44529
  } else if (!done) {
@@ -44565,9 +44891,214 @@ emailCommand.command("log").description("Recent email() sends and skipped attemp
44565
44891
  init_api();
44566
44892
  init_config();
44567
44893
  init_colors();
44568
- import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync15, readFileSync as readFileSync20 } from "fs";
44894
+ import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync16, readFileSync as readFileSync21 } from "fs";
44569
44895
  import { resolve as resolvePath2, dirname as dirname13, relative as relative5, isAbsolute, basename as basename7 } from "path";
44570
44896
 
44897
+ // src/commands/generate-async.ts
44898
+ init_api();
44899
+ init_config();
44900
+ init_colors();
44901
+ init_utils();
44902
+ var isQueuedModel = (model) => !!model && model.startsWith("gipity-");
44903
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired"]);
44904
+ var gensPath = (guid) => `/projects/${guid}/generate/image/generations`;
44905
+ function pollMs() {
44906
+ const v7 = Number(process.env.GIPITY_GENERATE_POLL_MS);
44907
+ return Number.isFinite(v7) && v7 > 0 ? v7 : 2e3;
44908
+ }
44909
+ function fmtEta(ms2) {
44910
+ if (ms2 == null || !Number.isFinite(ms2)) return null;
44911
+ const s = Math.round(ms2 / 1e3);
44912
+ if (s < 10) return "under 10s";
44913
+ if (s < 90) return `about ${s}s`;
44914
+ const m = Math.round(s / 60);
44915
+ if (m < 90) return `about ${m} min`;
44916
+ return `about ${Math.round(m / 60)} h`;
44917
+ }
44918
+ function statusText(g) {
44919
+ switch (g.status) {
44920
+ case "queued": {
44921
+ const ahead = g.queue_position != null ? Math.max(0, g.queue_position - 1) : null;
44922
+ const eta = fmtEta(g.eta_ms);
44923
+ const where = ahead === null ? "queued" : ahead === 0 ? "queued: next up" : `queued: ${ahead} ahead`;
44924
+ return eta ? `${where}, ${eta}` : where;
44925
+ }
44926
+ case "dispatched":
44927
+ return "starting";
44928
+ case "running": {
44929
+ if (g.phase === "loading") return "loading the model";
44930
+ if (g.step != null && g.total) return `rendering ${g.step}/${g.total}`;
44931
+ if (g.progress != null) return `rendering ${Math.round(g.progress * 100)}%`;
44932
+ return "rendering";
44933
+ }
44934
+ case "succeeded":
44935
+ return "done";
44936
+ case "failed":
44937
+ return `failed: ${g.error?.message ?? "unknown error"}`;
44938
+ case "cancelled":
44939
+ return "cancelled";
44940
+ case "expired":
44941
+ return "expired: it waited too long in the queue (not charged)";
44942
+ }
44943
+ }
44944
+ async function submitGenerations(projectGuid2, body) {
44945
+ const res = await post(gensPath(projectGuid2), body);
44946
+ return res.data;
44947
+ }
44948
+ async function fetchGenerations(projectGuid2, ids) {
44949
+ const res = await get(`${gensPath(projectGuid2)}?ids=${ids.map(encodeURIComponent).join(",")}`);
44950
+ return res.data;
44951
+ }
44952
+ function combinedText(gens) {
44953
+ if (gens.length === 1) return statusText(gens[0]);
44954
+ const done = gens.filter((g) => TERMINAL.has(g.status)).length;
44955
+ const live = gens.find((g) => !TERMINAL.has(g.status));
44956
+ return `${done}/${gens.length} finished${live ? `; ${statusText(live)}` : ""}`;
44957
+ }
44958
+ async function waitForGenerations(projectGuid2, initial, opts = {}) {
44959
+ const ids = initial.map((g) => g.id);
44960
+ const tty = !!process.stdout.isTTY && !opts.json;
44961
+ const say = (line) => opts.json ? console.error(line) : console.log(line);
44962
+ let gens = initial;
44963
+ let last = "";
44964
+ let lineOpen = false;
44965
+ const draw = (text) => {
44966
+ if (tty) {
44967
+ process.stdout.write(`\r ${muted(text)}\x1B[K`);
44968
+ lineOpen = true;
44969
+ } else if (text !== last) {
44970
+ say(` ${text}`);
44971
+ }
44972
+ last = text;
44973
+ };
44974
+ const closeLine = () => {
44975
+ if (lineOpen) {
44976
+ process.stdout.write("\r\x1B[K");
44977
+ lineOpen = false;
44978
+ }
44979
+ };
44980
+ let interrupted = false;
44981
+ const onSigint = () => {
44982
+ interrupted = true;
44983
+ };
44984
+ process.on("SIGINT", onSigint);
44985
+ try {
44986
+ draw(combinedText(gens));
44987
+ while (!gens.every((g) => TERMINAL.has(g.status))) {
44988
+ await sleepUnlessInterrupted(pollMs(), () => interrupted);
44989
+ if (interrupted) break;
44990
+ gens = await fetchGenerations(projectGuid2, ids);
44991
+ draw(combinedText(gens));
44992
+ }
44993
+ } finally {
44994
+ process.off("SIGINT", onSigint);
44995
+ closeLine();
44996
+ }
44997
+ if (interrupted) {
44998
+ const open = gens.filter((g) => !TERMINAL.has(g.status)).map((g) => g.id);
44999
+ if (process.stdin.isTTY && await confirm(`Cancel ${open.length === 1 ? "the generation" : `${open.length} generations`}? No leaves ${open.length === 1 ? "it" : "them"} queued`, { default: "no", headless: "no" })) {
45000
+ for (const id2 of open) await post(`${gensPath(projectGuid2)}/${encodeURIComponent(id2)}/cancel`);
45001
+ console.log(muted(`Cancelled ${open.join(" ")} (not charged).`));
45002
+ } else {
45003
+ console.error(muted(`Left queued. Check later with: gipity generate status ${open.join(" ")}`));
45004
+ }
45005
+ process.exit(130);
45006
+ }
45007
+ return gens;
45008
+ }
45009
+ function sleepUnlessInterrupted(ms2, stop) {
45010
+ return new Promise((resolve19) => {
45011
+ const started = Date.now();
45012
+ const tick = () => {
45013
+ if (stop() || Date.now() - started >= ms2) return resolve19();
45014
+ setTimeout(tick, Math.min(100, ms2));
45015
+ };
45016
+ tick();
45017
+ });
45018
+ }
45019
+ function printGeneration(g) {
45020
+ const head = g.status === "succeeded" ? success(g.id) : g.status === "failed" || g.status === "expired" ? error(g.id) : g.id;
45021
+ console.log(`${head} ${muted(g.model)} ${statusText(g)}`);
45022
+ if (g.status === "succeeded" && g.outputs?.full?.url) console.log(` ${muted("url:")} ${g.outputs.full.url}`);
45023
+ if (g.credits_charged != null && g.credits_charged > 0) console.log(` ${muted("credits:")} ${g.credits_charged}`);
45024
+ }
45025
+ var statusCommand2 = new Command("status").description("Show where queued or finished image generations are").argument("<ids...>", "Generation ids (gen_...)").option("--json", "Output as JSON").action((ids, opts) => run("Generation status", async () => {
45026
+ const { config } = await resolveProjectContext();
45027
+ const gens = await fetchGenerations(config.projectGuid, ids);
45028
+ if (opts.json) {
45029
+ console.log(JSON.stringify(gens));
45030
+ return;
45031
+ }
45032
+ const found = new Set(gens.map((g) => g.id));
45033
+ for (const g of gens) printGeneration(g);
45034
+ for (const id2 of ids.filter((i) => !found.has(i))) console.log(`${error(id2)} not found`);
45035
+ }));
45036
+ var cancelCommand = new Command("cancel").description("Cancel queued or running image generations (a cancelled one is not charged)").argument("<ids...>", "Generation ids (gen_...)").option("--json", "Output as JSON").action((ids, opts) => run("Cancel", async () => {
45037
+ const { config } = await resolveProjectContext();
45038
+ const out = [];
45039
+ for (const id2 of ids) {
45040
+ const res = await post(`${gensPath(config.projectGuid)}/${encodeURIComponent(id2)}/cancel`);
45041
+ out.push(res.data);
45042
+ }
45043
+ if (opts.json) {
45044
+ console.log(JSON.stringify(out));
45045
+ return;
45046
+ }
45047
+ for (const g of out) printGeneration(g);
45048
+ }));
45049
+ var listCommand = new Command("list").description("List your recent image generations in this project").option("--open", "Only queued or running ones").option("--limit <n>", "How many (default 20)", (v7) => parseInt(v7, 10)).option("--json", "Output as JSON").action((opts) => run("List generations", async () => {
45050
+ const { config } = await resolveProjectContext();
45051
+ const qs = opts.open ? "status=open" : `limit=${Number.isFinite(opts.limit) ? opts.limit : 20}`;
45052
+ const res = await get(`${gensPath(config.projectGuid)}?${qs}`);
45053
+ if (opts.json) {
45054
+ console.log(JSON.stringify(res.data));
45055
+ return;
45056
+ }
45057
+ if (!res.data.length) {
45058
+ console.log(muted(opts.open ? "Nothing queued or running." : "No generations yet."));
45059
+ return;
45060
+ }
45061
+ for (const g of res.data) printGeneration(g);
45062
+ }));
45063
+ function fmtWait(s) {
45064
+ return s === void 0 ? "?" : fmtEta(s * 1e3) ?? "?";
45065
+ }
45066
+ var modelsCommand = new Command("models").description("List image models, with prices and queue estimates for Gipity GPU models").option("--json", "Output as JSON").action((opts) => run("Image models", async () => {
45067
+ const { config } = await resolveProjectContext();
45068
+ const res = await get(
45069
+ `/projects/${config.projectGuid}/generate/image/models`
45070
+ );
45071
+ if (opts.json) {
45072
+ console.log(JSON.stringify(res.data));
45073
+ return;
45074
+ }
45075
+ const { models, gipity_gpu: gpu } = res.data;
45076
+ const cloud = models.filter((m) => !isQueuedModel(m.id));
45077
+ const queued = models.filter((m) => isQueuedModel(m.id));
45078
+ if (cloud.length) {
45079
+ console.log("Cloud models (one request, immediate):");
45080
+ for (const m of cloud) console.log(` ${m.id.padEnd(30)} ${muted(m.provider)}`);
45081
+ }
45082
+ if (queued.length) {
45083
+ if (cloud.length) console.log("");
45084
+ console.log("Gipity GPU models (queued, half the usual price):");
45085
+ if (gpu) {
45086
+ console.log(muted(gpu.online ? ` queue: ${gpu.queue?.paid_ahead ?? 0} paid + ${gpu.queue?.free_ahead ?? 0} free ahead; wait ${fmtWait(gpu.est_wait_s?.paid)} on a paid plan, ${fmtWait(gpu.est_wait_s?.free)} on Free` : " offline right now: new jobs wait in the queue until it is back"));
45087
+ }
45088
+ const width = Math.max(...queued.map((m) => m.id.length));
45089
+ for (const m of queued) {
45090
+ const price = m.price_credits != null ? `${m.price_credits} credits` : "not priced yet";
45091
+ const tags = [m.nsfw ? warning("NSFW") : "", m.max_references ? muted(`refs:${m.max_references}`) : ""].filter(Boolean).join(" ");
45092
+ const state = m.available === false ? error(`unavailable${m.unavailable_reason ? `: ${m.unavailable_reason}` : ""}`) : "";
45093
+ console.log(` ${m.id.padEnd(width)} ${price.padEnd(16)} ${[tags, state].filter(Boolean).join(" ")}`.trimEnd());
45094
+ if (m.label || m.description) console.log(muted(` ${"".padEnd(width)} ${[m.label, m.description].filter(Boolean).join(": ")}`));
45095
+ }
45096
+ }
45097
+ }));
45098
+ function addGenerationSubcommands(parent) {
45099
+ return parent.addCommand(statusCommand2).addCommand(cancelCommand).addCommand(listCommand).addCommand(modelsCommand);
45100
+ }
45101
+
44571
45102
  // src/provider-docs.ts
44572
45103
  var GEMINI_TTS_VOICES_DOC = `Zephyr, Puck, Charon, Kore, Fenrir, Leda, Orus, Aoede, Callirrhoe, Autonoe, Enceladus, Iapetus, Umbriel, Algieba, Despina, Erinome, Algenib, Rasalgethi, Laomedeia, Achernar, Alnilam, Schedar, Gacrux, Pulcherrima, Achird, Zubenelgenubi, Vindemiatrix, Sadachbia, Sadaltager, Sulafat`;
44573
45104
  var IMAGE_GEMINI_ASPECT_RATIO_IDS = [
@@ -44667,7 +45198,7 @@ async function downloadFile(url, filename, explicit) {
44667
45198
  const outPath = explicit ? filename : correctExtension(filename, buffer);
44668
45199
  if (explicit) noteFormatMismatch(filename, buffer);
44669
45200
  ensureOutputDir(outPath);
44670
- writeFileSync15(outPath, buffer);
45201
+ writeFileSync16(outPath, buffer);
44671
45202
  const savedPath = resolvePath2(outPath);
44672
45203
  await pushGenerated(savedPath);
44673
45204
  return savedPath;
@@ -44733,7 +45264,7 @@ function readInputImages(paths) {
44733
45264
  return paths.map((p) => {
44734
45265
  let buf;
44735
45266
  try {
44736
- buf = readFileSync20(p);
45267
+ buf = readFileSync21(p);
44737
45268
  } catch (e) {
44738
45269
  throw new Error(`can't read --input image ${p} (${e.code || e.message}).`);
44739
45270
  }
@@ -44751,6 +45282,13 @@ ${IMAGE_MODELS_TABLE}
44751
45282
  Tier aliases (pass to --model instead of an id; each names a provider+model):
44752
45283
  ${IMAGE_TIER_ALIASES_DOC}
44753
45284
 
45285
+ Gipity GPU models (--model gipity-...; list them with \`gipity generate models\`):
45286
+ half the usual price for the same model, but queued: paid plans go first, and a
45287
+ job may wait a while. The CLI waits and shows the queue position, then saves the
45288
+ image. --no-wait queues it and prints the id instead (check it with
45289
+ \`gipity generate status <id>\`). GPU-only options: --aspect, --n, --ref, --avoid,
45290
+ --nsfw, --format. NSFW models need "Allow NSFW services" on your account.
45291
+
44754
45292
  Editing (--input): pass one or more source images and the prompt becomes an edit
44755
45293
  instruction applied to them - "make it night time", "add a hat", "remove the car
44756
45294
  in the background", or compose several inputs together. Editing routes to Gemini
@@ -44763,10 +45301,17 @@ Examples:
44763
45301
  gipity generate image "landscape sunset" --provider gemini --aspect-ratio 16:9 --image-size 2K
44764
45302
  gipity generate image "product photo" --provider openai --model gpt-image-2 --size 1536x1024 --quality high
44765
45303
  gipity generate image "abstract art" --provider bfl --model flux-2-pro -o art.png
44766
- `).argument("<prompt>", "Text description of the image, or (with --input) the edit instruction to apply").option("--input <file>", "Source image to edit/compose (repeatable). With --input the prompt is an edit instruction; routes to Gemini.", (v7, acc) => (acc || []).concat(v7)).addOption(new Option("--provider <provider>", "Image provider (default: bfl)").choices(IMAGE_PROVIDER_IDS)).option("--model <model>", `Model id for the chosen provider, or a tier alias (${IMAGE_TIER_ALIAS_IDS.join(", ")}); see Models below`).option("--size <size>", 'Dimensions as WxH, e.g. "1024x1024" (OpenAI/BFL)').addOption(new Option("--quality <quality>", "Quality (OpenAI gpt-image models only)").choices(IMAGE_QUALITY_IDS)).addOption(new Option("--aspect-ratio <ratio>", "Aspect ratio (Gemini only)").choices(IMAGE_GEMINI_ASPECT_RATIO_IDS)).addOption(new Option("--image-size <size>", "Output resolution (Gemini only)").choices(IMAGE_GEMINI_SIZE_IDS)).option("--seed <n>", "Deterministic seed (BFL only): reuse one seed to keep a set of images visually coherent", (v7) => parseInt(v7, 10)).option("-o, --output <file>", "Output path (default ./generated.png). For an image your app ships, write it into the source tree so it deploys, e.g. -o src/assets/images/hero.png; the cwd default is fine for one-off generation.").option("--json", "Output as JSON").action(async (prompt2, opts) => {
45304
+ gipity generate image "a red canoe at sunrise" --model gipity-krea2-realistic --aspect landscape
45305
+ gipity generate image "same canoe, now at night" --model gipity-qwen21-consistent --ref gen_abc12345
45306
+ gipity generate image "a lighthouse" --model gipity-krea2-realistic --n 4 --no-wait
45307
+ `).argument("<prompt>", "Text description of the image, or (with --input) the edit instruction to apply").option("--input <file>", "Source image to edit/compose (repeatable). With --input the prompt is an edit instruction; routes to Gemini.", (v7, acc) => (acc || []).concat(v7)).addOption(new Option("--provider <provider>", "Image provider (default: bfl)").choices(IMAGE_PROVIDER_IDS)).option("--model <model>", `Model id for the chosen provider, or a tier alias (${IMAGE_TIER_ALIAS_IDS.join(", ")}); see Models below`).option("--size <size>", 'Dimensions as WxH, e.g. "1024x1024" (Gemini snaps to its nearest tier and aspect ratio)').addOption(new Option("--quality <quality>", "Quality (OpenAI gpt-image models only)").choices(IMAGE_QUALITY_IDS)).addOption(new Option("--aspect-ratio <ratio>", "Aspect ratio (Gemini only)").choices(IMAGE_GEMINI_ASPECT_RATIO_IDS)).addOption(new Option("--image-size <size>", "Output resolution tier (Gemini only; each model supports only some, see the app-image skill)").choices(IMAGE_GEMINI_SIZE_IDS)).option("--seed <n>", "Deterministic seed (BFL and Gipity GPU models): reuse one seed to keep a set of images visually coherent", (v7) => parseInt(v7, 10)).option("-o, --output <file>", "Output path (default ./generated.png). For an image your app ships, write it into the source tree so it deploys, e.g. -o src/assets/images/hero.png; the cwd default is fine for one-off generation. With --n > 1 the files are numbered (hero-1.png, hero-2.png).").addOption(new Option("--aspect <aspect>", "Shape (Gipity GPU models)").choices(["portrait", "square", "landscape"])).option("--n <count>", "Number of images, 1-4, with consecutive seeds (Gipity GPU models)", (v7) => parseInt(v7, 10)).option("--ref <gen_id>", "An earlier generation to keep consistent with (repeatable; models that take references)", (v7, acc) => (acc || []).concat(v7)).option("--avoid <text>", "What to keep out of the image (Gipity GPU models that support it)").option("--nsfw", 'Allow adult content (NSFW models; needs "Allow NSFW services" on your account)').addOption(new Option("--format <format>", "Full-size file format (Gipity GPU models; default jpeg)").choices(["jpeg", "png"])).option("--no-wait", "Queue it and print the generation id(s) instead of waiting").option("--json", "Output as JSON").action(async (prompt2, opts) => {
44767
45308
  try {
44768
45309
  const { config } = await resolveProjectContext();
44769
45310
  if (opts.output) ensureOutputDir(opts.output);
45311
+ if (isQueuedModel(opts.model) || opts.wait === false) {
45312
+ await generateQueued(config.projectGuid, prompt2, opts);
45313
+ return;
45314
+ }
44770
45315
  const inputImages = opts.input ? readInputImages(opts.input) : void 0;
44771
45316
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/image`, {
44772
45317
  prompt: prompt2,
@@ -44792,8 +45337,10 @@ Examples:
44792
45337
  console.log(muted(`Generated with ${result.provider}/${result.model}`));
44793
45338
  printMetrics([
44794
45339
  ...generationMetrics(result, elapsed),
45340
+ result.width && result.height ? { label: "pixels", value: `${result.width}x${result.height}` } : null,
44795
45341
  result.seed !== void 0 ? { label: "seed", value: `${result.seed} ${muted(`(pass --seed ${result.seed} to keep the next image coherent)`)}` } : null
44796
45342
  ]);
45343
+ if (result.note) console.log(muted(result.note));
44797
45344
  console.log(success(`Saved to ${savedPath}`));
44798
45345
  }
44799
45346
  } catch (err) {
@@ -44801,6 +45348,72 @@ Examples:
44801
45348
  process.exit(1);
44802
45349
  }
44803
45350
  });
45351
+ function numberedPath(base, i, n) {
45352
+ if (n <= 1) return base;
45353
+ const dot = base.lastIndexOf(".");
45354
+ const slash = Math.max(base.lastIndexOf("/"), base.lastIndexOf("\\"));
45355
+ return dot > slash ? `${base.slice(0, dot)}-${i + 1}${base.slice(dot)}` : `${base}-${i + 1}`;
45356
+ }
45357
+ async function generateQueued(projectGuid2, prompt2, opts) {
45358
+ if (opts.input) throw new Error("--input editing is not available on queued generations; drop --input or pick a cloud model.");
45359
+ if (!opts.model || !String(opts.model).startsWith("gipity-")) {
45360
+ throw new Error("--no-wait is for Gipity GPU models (--model gipity-...; see `gipity generate models`). Cloud models render right away: drop --no-wait.");
45361
+ }
45362
+ const started = Date.now();
45363
+ const submitted = await submitGenerations(projectGuid2, {
45364
+ model: opts.model,
45365
+ prompt: prompt2,
45366
+ avoid: opts.avoid,
45367
+ aspect: opts.aspect,
45368
+ size: opts.size,
45369
+ seed: Number.isFinite(opts.seed) ? opts.seed : void 0,
45370
+ n: Number.isFinite(opts.n) ? opts.n : void 0,
45371
+ nsfw: opts.nsfw ? true : void 0,
45372
+ format: opts.format,
45373
+ references: opts.ref
45374
+ });
45375
+ if (opts.wait === false) {
45376
+ if (opts.json) {
45377
+ console.log(JSON.stringify(submitted));
45378
+ return;
45379
+ }
45380
+ for (const g of submitted) console.log(`${g.id} ${muted(statusText(g))}`);
45381
+ console.log(muted(`Check with: gipity generate status ${submitted.map((g) => g.id).join(" ")}`));
45382
+ return;
45383
+ }
45384
+ if (!opts.json) console.log(muted(`Queued ${submitted.length === 1 ? submitted[0].id : submitted.map((g) => g.id).join(", ")} on ${opts.model}`));
45385
+ const done = await waitForGenerations(projectGuid2, submitted, { json: !!opts.json });
45386
+ const elapsed = (Date.now() - started) / 1e3;
45387
+ const saved = [];
45388
+ for (let i = 0; i < done.length; i++) {
45389
+ const g = done[i];
45390
+ const url = g.status === "succeeded" ? g.outputs?.full?.url : void 0;
45391
+ if (!url) {
45392
+ saved.push({ gen: g, path: null });
45393
+ continue;
45394
+ }
45395
+ const ext = (g.outputs?.full?.mime ?? "").includes("png") ? "png" : "jpg";
45396
+ const target = numberedPath(opts.output || `generated.${ext}`, i, done.length);
45397
+ saved.push({ gen: g, path: await downloadFile(url, target, !!opts.output) });
45398
+ }
45399
+ const failed = saved.filter((s) => !s.path);
45400
+ if (opts.json) {
45401
+ console.log(JSON.stringify(saved.map((s) => ({ ...s.gen, saved: s.path })).map((r) => ({ ...r, generation_seconds: Math.round(elapsed * 10) / 10 }))));
45402
+ } else {
45403
+ const credits = done.reduce((sum, g) => sum + (g.credits_charged ?? 0), 0);
45404
+ console.log(muted(`Generated with gipity/${opts.model}`));
45405
+ const first = saved.find((s) => s.path)?.gen;
45406
+ printMetrics([
45407
+ { label: "time", value: fmtSeconds(elapsed) },
45408
+ first?.width && first?.height ? { label: "pixels", value: `${first.width}x${first.height}` } : null,
45409
+ first?.seed != null ? { label: "seed", value: `${first.seed} ${muted(`(pass --seed ${first.seed} to keep the next image coherent)`)}` } : null,
45410
+ credits > 0 ? { label: "credits", value: credits.toLocaleString("en-US") } : null
45411
+ ]);
45412
+ for (const s of failed) console.error(error(`${s.gen.id} ${statusText(s.gen)}`));
45413
+ for (const s of saved) if (s.path) console.log(success(`Saved ${s.gen.id} to ${s.path}`));
45414
+ }
45415
+ if (failed.length === done.length) process.exit(1);
45416
+ }
44804
45417
  var videoCommand = new Command("video").description("Generate a short video (3-10 seconds) from a text prompt").addHelpText("after", `
44805
45418
  Models (default: gemini-omni-1.1-flash):
44806
45419
  ${VIDEO_MODELS_TABLE}
@@ -44854,7 +45467,7 @@ voice ids: gipity service call "tts/voices?provider=elevenlabs" --get
44854
45467
 
44855
45468
  Gemini voices: ${GEMINI_TTS_VOICES_DOC}
44856
45469
 
44857
- Multi-speaker (--speakers, Gemini only): JSON array like
45470
+ Multi-speaker (--speakers, Gemini only): JSON array of exactly 2 speakers like
44858
45471
  [{"name":"Joe","voice":"Kore"},{"name":"Jane","voice":"Puck"}]; format the
44859
45472
  text as "Name: dialogue" on each line.
44860
45473
 
@@ -44863,7 +45476,7 @@ Examples:
44863
45476
  gipity generate speech "\u3053\u3093\u306B\u3061\u306F\u4E16\u754C" --provider gemini --voice Kore --language ja-JP
44864
45477
  gipity generate speech "Bonjour le monde" --provider gemini --language fr-FR
44865
45478
  gipity generate speech 'Joe: Hey!\\nJane: Hi there!' --provider gemini --speakers '[{"name":"Joe","voice":"Charon"},{"name":"Jane","voice":"Leda"}]'
44866
- `).argument("<text>", "Text to convert to speech (max 5000 characters)").addOption(new Option("--provider <provider>", "TTS provider (default: elevenlabs)").choices(TTS_PROVIDER_IDS)).option("--voice <voice>", "Voice ID or name (provider-specific; see Voices below)").option("--language <code>", "BCP-47 language code, e.g. ja-JP, es-ES (Gemini only, 60+ languages)").option("--speakers <json>", "Multi-speaker config as JSON array (Gemini only, up to 2 speakers)").option("-o, --output <file>", "Output path (default ./speech.mp3; --provider gemini returns WAV, so name it .wav). For audio your app ships, write it into the source tree so it deploys, e.g. -o src/assets/sounds/intro.mp3; the cwd default is fine for one-off generation.").option("--json", "Output as JSON").action(async (text, opts) => {
45479
+ `).argument("<text>", "Text to convert to speech (max 5000 characters)").addOption(new Option("--provider <provider>", "TTS provider (default: elevenlabs)").choices(TTS_PROVIDER_IDS)).option("--voice <voice>", "Voice ID or name (provider-specific; see Voices below)").option("--language <code>", "BCP-47 language code, e.g. ja-JP, es-ES (Gemini only, 60+ languages)").option("--speakers <json>", "Multi-speaker config as JSON array (Gemini only, exactly 2 speakers)").option("-o, --output <file>", "Output path (default ./speech.mp3; --provider gemini returns WAV, so name it .wav). For audio your app ships, write it into the source tree so it deploys, e.g. -o src/assets/sounds/intro.mp3; the cwd default is fine for one-off generation.").option("--json", "Output as JSON").action(async (text, opts) => {
44867
45480
  try {
44868
45481
  const { config } = await resolveProjectContext();
44869
45482
  if (opts.output) ensureOutputDir(opts.output);
@@ -44926,7 +45539,7 @@ Examples:
44926
45539
  console.error(error("Pass --lyrics or --lyrics-file, not both."));
44927
45540
  process.exit(1);
44928
45541
  }
44929
- const lyrics = opts.lyricsFile ? readFileSync20(opts.lyricsFile, "utf8").trim() : opts.lyrics;
45542
+ const lyrics = opts.lyricsFile ? readFileSync21(opts.lyricsFile, "utf8").trim() : opts.lyrics;
44930
45543
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/music`, {
44931
45544
  prompt: prompt2,
44932
45545
  duration_seconds: opts.duration,
@@ -44992,14 +45605,26 @@ Examples:
44992
45605
  process.exit(1);
44993
45606
  }
44994
45607
  });
44995
- var generateCommand = new Command("generate").description("Generate images, video, speech, sound effects, or music").addCommand(imageCommand).addCommand(videoCommand).addCommand(speechCommand).addCommand(soundCommand).addCommand(musicCommand);
45608
+ var generateCommand = addGenerationSubcommands(new Command("generate").description("Generate images, video, speech, sound effects, or music").addCommand(imageCommand).addCommand(videoCommand).addCommand(speechCommand).addCommand(soundCommand).addCommand(musicCommand));
44996
45609
 
44997
45610
  // src/commands/ask.ts
44998
45611
  init_api();
44999
45612
  init_config();
45000
- import { readFileSync as readFileSync21, fstatSync } from "fs";
45613
+ import { readFileSync as readFileSync22, fstatSync } from "fs";
45001
45614
  init_colors();
45002
45615
  var IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
45616
+ var MAX_WARM_WAIT_S = 90;
45617
+ async function askWithWarmRetry(call, onWarming) {
45618
+ try {
45619
+ return await call();
45620
+ } catch (e) {
45621
+ if (!(e instanceof ApiError) || e.code !== "MODEL_WARMING") throw e;
45622
+ const waitS = Math.min(Number(e.data?.retry_after_s ?? 45), MAX_WARM_WAIT_S);
45623
+ onWarming(waitS);
45624
+ await new Promise((r) => setTimeout(r, waitS * 1e3));
45625
+ return call();
45626
+ }
45627
+ }
45003
45628
  function stdinIsPiped() {
45004
45629
  try {
45005
45630
  const st2 = fstatSync(0);
@@ -45010,7 +45635,7 @@ function stdinIsPiped() {
45010
45635
  }
45011
45636
  function readTextFile(path5) {
45012
45637
  try {
45013
- return readFileSync21(path5 === "-" ? 0 : path5, "utf8");
45638
+ return readFileSync22(path5 === "-" ? 0 : path5, "utf8");
45014
45639
  } catch (e) {
45015
45640
  throw new Error(`can't read --file ${path5} (${e.code || e.message}).`);
45016
45641
  }
@@ -45020,7 +45645,7 @@ function readImage(path5) {
45020
45645
  if (!IMAGE_TYPES.has(mime)) throw new Error(`--image ${path5} is ${mime}; use a png, jpg, gif or webp.`);
45021
45646
  let buf;
45022
45647
  try {
45023
- buf = readFileSync21(path5);
45648
+ buf = readFileSync22(path5);
45024
45649
  } catch (e) {
45025
45650
  throw new Error(`can't read --image ${path5} (${e.code || e.message}).`);
45026
45651
  }
@@ -45033,7 +45658,7 @@ function buildAskPrompt(words, files) {
45033
45658
  ${f.content.trimEnd()}`);
45034
45659
  return parts.join("\n\n");
45035
45660
  }
45036
- var askCommand = new Command("ask").description("Ask a model one question and print the answer: no chat history, no tools. Attach text with --file (- for stdin) or images with --image").argument("[prompt...]", "The question or instruction").option("--file <path...>", "Add a text file to the prompt (repeatable); - reads stdin").option("--image <path...>", "Attach an image: png, jpg, gif or webp (repeatable)").option("--model <model>", "Model id, alias (small, fast, medium, large, haiku, sonnet, opus, ...) or provider (openai, anthropic, gemini). Default: small").option("--system <text>", "Replace the default system prompt").option("--schema <json>", "Answer with a JSON value matching this JSON schema; prints the JSON").option("--max-tokens <n>", "Cap the answer length", (v7) => parseInt(v7, 10)).option("--json", "Output the whole result (answer, model, tokens) as JSON").addHelpText("after", `
45661
+ var askCommand = new Command("ask").description("Ask a model one question and print the answer: no chat history, no tools. Attach text with --file (- for stdin) or images with --image").argument("[prompt...]", "The question or instruction").option("--file <path...>", "Add a text file to the prompt (repeatable); - reads stdin").option("--image <path...>", "Attach an image: png, jpg, gif or webp (repeatable)").option("--model <model>", "Model id, alias (small, fast, medium, large, haiku, sonnet, opus, ...) or provider (openai, anthropic, gemini). gipity-qwen3.6-35b runs on Gipity GPU at half price (text only). Default: small").option("--system <text>", "Replace the default system prompt").option("--schema <json>", "Answer with a JSON value matching this JSON schema; prints the JSON").option("--max-tokens <n>", "Cap the answer length", (v7) => parseInt(v7, 10)).option("--json", "Output the whole result (answer, model, tokens) as JSON").addHelpText("after", `
45037
45662
  Examples:
45038
45663
  gipity ask "what does HTTP 425 mean?"
45039
45664
  cat errors.log | gipity ask "group these by root cause" --file -
@@ -45062,7 +45687,8 @@ Examples:
45062
45687
  if (images.length) body.images = images;
45063
45688
  if (schema !== void 0) body.schema = schema;
45064
45689
  if (opts.maxTokens) body.max_tokens = opts.maxTokens;
45065
- const call = () => post(`/projects/${config.projectGuid}/generate/text`, body);
45690
+ const once = () => post(`/projects/${config.projectGuid}/generate/text`, body);
45691
+ const call = () => askWithWarmRetry(once, (s) => console.error(`The model is loading; retrying in ${s}s...`));
45066
45692
  const result = opts.json || !process.stderr.isTTY ? await call() : await withSpinner("Thinking...", call, { done: null });
45067
45693
  if (opts.json) {
45068
45694
  console.log(JSON.stringify(result));
@@ -45076,14 +45702,14 @@ Examples:
45076
45702
  init_api();
45077
45703
  init_config();
45078
45704
  init_colors();
45079
- import { existsSync as existsSync18, readFileSync as readFileSync22 } from "fs";
45705
+ import { existsSync as existsSync18, readFileSync as readFileSync23 } from "fs";
45080
45706
  import { join as join23 } from "path";
45081
45707
  function readInstalledKitReadme(name) {
45082
45708
  const root = getProjectRoot() ?? process.cwd();
45083
45709
  const kitDir = join23(root, "src", "packages", name);
45084
45710
  if (!existsSync18(join23(kitDir, "package.json"))) return null;
45085
45711
  const readme = join23(kitDir, "README.md");
45086
- return existsSync18(readme) ? readFileSync22(readme, "utf-8") : null;
45712
+ return existsSync18(readme) ? readFileSync23(readme, "utf-8") : null;
45087
45713
  }
45088
45714
  function slugify2(title) {
45089
45715
  return title.toLowerCase().replace(/[`*_]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -45861,12 +46487,12 @@ var locationCommand = new Command("location").description("Show location").argum
45861
46487
  }));
45862
46488
 
45863
46489
  // src/commands/doctor.ts
45864
- import { existsSync as existsSync21, readFileSync as readFileSync24, statSync as statSync9 } from "fs";
46490
+ import { existsSync as existsSync21, readFileSync as readFileSync25, statSync as statSync9 } from "fs";
45865
46491
  import { join as join25, resolve as resolve15 } from "path";
45866
46492
  import { homedir as homedir17 } from "os";
45867
46493
 
45868
46494
  // src/updater/state.ts
45869
- import { readFileSync as readFileSync23, writeFileSync as writeFileSync16, mkdirSync as mkdirSync16, existsSync as existsSync20 } from "fs";
46495
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync17, mkdirSync as mkdirSync16, existsSync as existsSync20 } from "fs";
45870
46496
  import { join as join24 } from "path";
45871
46497
  import { homedir as homedir16 } from "os";
45872
46498
  var GIPITY_DIR = join24(homedir16(), ".gipity");
@@ -45891,19 +46517,19 @@ function ensureDir() {
45891
46517
  function readState() {
45892
46518
  if (!existsSync20(STATE_FILE)) return { ...DEFAULT_STATE };
45893
46519
  try {
45894
- return { ...DEFAULT_STATE, ...JSON.parse(readFileSync23(STATE_FILE, "utf-8")) };
46520
+ return { ...DEFAULT_STATE, ...JSON.parse(readFileSync24(STATE_FILE, "utf-8")) };
45895
46521
  } catch {
45896
46522
  return { ...DEFAULT_STATE };
45897
46523
  }
45898
46524
  }
45899
46525
  function writeState(state) {
45900
46526
  ensureDir();
45901
- writeFileSync16(STATE_FILE, JSON.stringify(state, null, 2));
46527
+ writeFileSync17(STATE_FILE, JSON.stringify(state, null, 2));
45902
46528
  }
45903
46529
  function readSettings() {
45904
46530
  if (!existsSync20(SETTINGS_FILE)) return { ...DEFAULT_SETTINGS };
45905
46531
  try {
45906
- return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync23(SETTINGS_FILE, "utf-8")) };
46532
+ return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync24(SETTINGS_FILE, "utf-8")) };
45907
46533
  } catch {
45908
46534
  return { ...DEFAULT_SETTINGS };
45909
46535
  }
@@ -45940,7 +46566,7 @@ function localVersion() {
45940
46566
  const pkgPath = join25(LOCAL_PKG_DIR, "package.json");
45941
46567
  if (!existsSync21(pkgPath)) return null;
45942
46568
  try {
45943
- return JSON.parse(readFileSync24(pkgPath, "utf-8")).version ?? null;
46569
+ return JSON.parse(readFileSync25(pkgPath, "utf-8")).version ?? null;
45944
46570
  } catch {
45945
46571
  return null;
45946
46572
  }
@@ -45948,7 +46574,7 @@ function localVersion() {
45948
46574
  function shimVersion() {
45949
46575
  try {
45950
46576
  const url = new URL("../../package.json", import.meta.url);
45951
- return JSON.parse(readFileSync24(url, "utf-8")).version;
46577
+ return JSON.parse(readFileSync25(url, "utf-8")).version;
45952
46578
  } catch {
45953
46579
  return "unknown";
45954
46580
  }
@@ -46068,7 +46694,7 @@ var doctorCommand = new Command("doctor").description("Check install + environme
46068
46694
  import { appendFileSync } from "fs";
46069
46695
 
46070
46696
  // src/updater/install.ts
46071
- import { existsSync as existsSync22, mkdirSync as mkdirSync17, rmSync as rmSync2, statSync as statSync10, unlinkSync as unlinkSync6, writeFileSync as writeFileSync17 } from "fs";
46697
+ import { existsSync as existsSync22, mkdirSync as mkdirSync17, rmSync as rmSync2, statSync as statSync10, unlinkSync as unlinkSync6, writeFileSync as writeFileSync18 } from "fs";
46072
46698
  import { dirname as dirname15, join as join26 } from "path";
46073
46699
  init_platform();
46074
46700
  var UPDATE_LOCK = join26(GIPITY_DIR, "update.lock");
@@ -46094,18 +46720,18 @@ function resetLocalTree(dir = LOCAL_DIR) {
46094
46720
  mkdirSync17(dir, { recursive: true });
46095
46721
  rmSync2(join26(dir, "node_modules"), { recursive: true, force: true });
46096
46722
  rmSync2(join26(dir, "package-lock.json"), { force: true });
46097
- writeFileSync17(join26(dir, "package.json"), JSON.stringify({ name: "gipity-local", private: true, version: "0.0.0" }, null, 2));
46723
+ writeFileSync18(join26(dir, "package.json"), JSON.stringify({ name: "gipity-local", private: true, version: "0.0.0" }, null, 2));
46098
46724
  }
46099
46725
  function acquireUpdateLock(lockPath2 = UPDATE_LOCK) {
46100
46726
  mkdirSync17(dirname15(lockPath2), { recursive: true });
46101
46727
  try {
46102
- writeFileSync17(lockPath2, String(process.pid), { flag: "wx" });
46728
+ writeFileSync18(lockPath2, String(process.pid), { flag: "wx" });
46103
46729
  return true;
46104
46730
  } catch {
46105
46731
  try {
46106
46732
  if (Date.now() - statSync10(lockPath2).mtimeMs > LOCK_STALE_MS2) {
46107
46733
  unlinkSync6(lockPath2);
46108
- writeFileSync17(lockPath2, String(process.pid), { flag: "wx" });
46734
+ writeFileSync18(lockPath2, String(process.pid), { flag: "wx" });
46109
46735
  return true;
46110
46736
  }
46111
46737
  } catch {
@@ -46265,13 +46891,13 @@ var updateCommand = new Command("update").description("Update the CLI").option("
46265
46891
  init_api();
46266
46892
  init_utils();
46267
46893
  init_colors();
46268
- import { existsSync as existsSync25, readFileSync as readFileSync27, unlinkSync as unlinkSync9 } from "fs";
46894
+ import { existsSync as existsSync25, readFileSync as readFileSync28, unlinkSync as unlinkSync9 } from "fs";
46269
46895
  import { spawn as spawn2 } from "child_process";
46270
46896
 
46271
46897
  // src/relay/daemon.ts
46272
46898
  init_platform();
46273
46899
  init_config();
46274
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync19, existsSync as existsSync24, readFileSync as readFileSync26, writeFileSync as writeFileSync18, chmodSync as chmodSync4, closeSync as closeSync4, openSync as openSync4, unlinkSync as unlinkSync8 } from "fs";
46900
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync19, existsSync as existsSync24, readFileSync as readFileSync27, writeFileSync as writeFileSync19, chmodSync as chmodSync4, closeSync as closeSync4, openSync as openSync4, unlinkSync as unlinkSync8 } from "fs";
46275
46901
  import { stat, readFile } from "fs/promises";
46276
46902
  import { createInterface as createInterface2 } from "readline";
46277
46903
  import { homedir as homedir19, hostname as hostname6, platform as osPlatform3, loadavg as loadavg2, freemem as freemem2, totalmem as totalmem2, cpus as cpus2 } from "os";
@@ -48598,7 +49224,7 @@ async function resolveCwdForProject(d) {
48598
49224
  const configPath = join29(path5, ".gipity.json");
48599
49225
  if (existsSync24(configPath)) {
48600
49226
  try {
48601
- const cfg = JSON.parse(readFileSync26(configPath, "utf-8"));
49227
+ const cfg = JSON.parse(readFileSync27(configPath, "utf-8"));
48602
49228
  if (cfg.projectGuid === d.project_guid) return { cwd: path5, bootstrapped: false };
48603
49229
  log2("warn", "project dir exists but guid mismatch - using it anyway", {
48604
49230
  path: path5,
@@ -48612,7 +49238,7 @@ async function resolveCwdForProject(d) {
48612
49238
  log2("info", "bootstrapping new project dir", { slug: d.project_slug, path: path5 });
48613
49239
  mkdirSync19(path5, { recursive: true });
48614
49240
  const apiBase2 = getApiBaseOverride() || DEFAULT_API_BASE;
48615
- writeFileSync18(configPath, JSON.stringify({
49241
+ writeFileSync19(configPath, JSON.stringify({
48616
49242
  projectGuid: d.project_guid,
48617
49243
  projectSlug: d.project_slug,
48618
49244
  accountSlug: d.account_slug,
@@ -49094,7 +49720,7 @@ function registerInstallCommands(relayCommand2) {
49094
49720
  // src/commands/relay.ts
49095
49721
  var relayCommand = new Command("relay").description("Pair with the web CLI");
49096
49722
  relayCommand.command("setup").description("Pair this machine and start the relay - non-interactive (for installers/GUIs)").option("--name <name>", "Device name shown in the web CLI (default: this machine's hostname)").option("--no-start", "Pair only; do not start the relay daemon now").option("--no-autostart", "Skip the OS login service (use when a supervising app owns the daemon)").option("--force", "Re-pair even if already paired (re-registers this machine, rotating its token)").option("--json", "Machine-readable output").action(async (opts) => {
49097
- const fail = (code, message) => {
49723
+ const fail3 = (code, message) => {
49098
49724
  if (opts.json) {
49099
49725
  console.log(JSON.stringify({ ok: false, code, error: message }));
49100
49726
  } else {
@@ -49108,9 +49734,9 @@ relayCommand.command("setup").description("Pair this machine and start the relay
49108
49734
  device = await pairDevice({ name: opts.name, force: opts.force });
49109
49735
  } catch (err) {
49110
49736
  if (err instanceof ApiError && err.statusCode === 401) {
49111
- return fail("not_authenticated", "Not logged in - cannot pair this machine.");
49737
+ return fail3("not_authenticated", "Not logged in - cannot pair this machine.");
49112
49738
  }
49113
- return fail("pair_failed", `Could not pair: ${err?.message || err}`);
49739
+ return fail3("pair_failed", `Could not pair: ${err?.message || err}`);
49114
49740
  }
49115
49741
  let daemonStarted = false;
49116
49742
  if (opts.start) {
@@ -49127,7 +49753,7 @@ relayCommand.command("setup").description("Pair this machine and start the relay
49127
49753
  if (err instanceof UnsupportedPlatformError) {
49128
49754
  autostart.supported = false;
49129
49755
  } else {
49130
- return fail("autostart_failed", `Autostart install failed: ${err?.message || err}`);
49756
+ return fail3("autostart_failed", `Autostart install failed: ${err?.message || err}`);
49131
49757
  }
49132
49758
  }
49133
49759
  }
@@ -49181,7 +49807,7 @@ relayCommand.command("stop").description("Stop the background service").option("
49181
49807
  console.log(muted("Background service isn't running."));
49182
49808
  return;
49183
49809
  }
49184
- const pid = parseInt(readFileSync27(pidPath, "utf-8").trim(), 10);
49810
+ const pid = parseInt(readFileSync28(pidPath, "utf-8").trim(), 10);
49185
49811
  if (!pid || isNaN(pid)) {
49186
49812
  console.error(error("PID file is empty or malformed."));
49187
49813
  process.exit(1);
@@ -49330,7 +49956,7 @@ relayCommand.command("revoke").description("Revoke and forget this device").acti
49330
49956
  }
49331
49957
  const pidPath = getDaemonPidPath();
49332
49958
  if (existsSync25(pidPath)) {
49333
- const pid = parseInt(readFileSync27(pidPath, "utf-8").trim(), 10);
49959
+ const pid = parseInt(readFileSync28(pidPath, "utf-8").trim(), 10);
49334
49960
  if (pid && !isNaN(pid)) {
49335
49961
  try {
49336
49962
  process.kill(pid, "SIGTERM");
@@ -49349,7 +49975,7 @@ relayCommand.command("log").description("Tail the service log").option("-n, --li
49349
49975
  }
49350
49976
  const lines = parseInt(opts.lines, 10) || 100;
49351
49977
  try {
49352
- const all = readFileSync27(path5, "utf-8").split("\n");
49978
+ const all = readFileSync28(path5, "utf-8").split("\n");
49353
49979
  const tail2 = all.slice(-lines - 1).join("\n");
49354
49980
  process.stdout.write(tail2);
49355
49981
  } catch (err) {
@@ -49525,7 +50151,7 @@ init_api();
49525
50151
  init_auth();
49526
50152
  init_utils();
49527
50153
  init_colors();
49528
- import { existsSync as existsSync26, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync28, writeFileSync as writeFileSync19 } from "fs";
50154
+ import { existsSync as existsSync26, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync29, writeFileSync as writeFileSync20 } from "fs";
49529
50155
  import { homedir as homedir20, platform as osPlatform4 } from "os";
49530
50156
  import { join as join30, resolve as resolve17 } from "path";
49531
50157
  init_agents();
@@ -49538,7 +50164,7 @@ function removeInstallerPathLines() {
49538
50164
  if (!existsSync26(rc2)) continue;
49539
50165
  let text;
49540
50166
  try {
49541
- text = readFileSync28(rc2, "utf-8");
50167
+ text = readFileSync29(rc2, "utf-8");
49542
50168
  } catch {
49543
50169
  continue;
49544
50170
  }
@@ -49548,7 +50174,7 @@ function removeInstallerPathLines() {
49548
50174
  );
49549
50175
  if (kept.length === lines.length) continue;
49550
50176
  try {
49551
- writeFileSync19(rc2, kept.join("\n"));
50177
+ writeFileSync20(rc2, kept.join("\n"));
49552
50178
  touched.push(rc2);
49553
50179
  } catch {
49554
50180
  }
@@ -49844,7 +50470,7 @@ gmailCommand.command("reply").description("Reply to a Gmail thread. Get thread-i
49844
50470
  }));
49845
50471
 
49846
50472
  // src/commands/text.ts
49847
- import { readFileSync as readFileSync29 } from "fs";
50473
+ import { readFileSync as readFileSync30 } from "fs";
49848
50474
  init_colors();
49849
50475
 
49850
50476
  // src/helpers/text-analysis.ts
@@ -49999,10 +50625,10 @@ function areAnagrams(a, b7) {
49999
50625
 
50000
50626
  // src/commands/text.ts
50001
50627
  function resolveInput(args, opts) {
50002
- if (opts.file) return readFileSync29(opts.file, "utf-8");
50628
+ if (opts.file) return readFileSync30(opts.file, "utf-8");
50003
50629
  if (args.length) return args.join(" ");
50004
50630
  try {
50005
- return readFileSync29(0, "utf-8");
50631
+ return readFileSync30(0, "utf-8");
50006
50632
  } catch {
50007
50633
  return "";
50008
50634
  }
@@ -50298,11 +50924,11 @@ function installOutputTrace(label2) {
50298
50924
  installOutputTrace("index");
50299
50925
  var __dirname = dirname16(fileURLToPath4(import.meta.url));
50300
50926
  installNetworking();
50301
- var pkg = JSON.parse(readFileSync30(resolve18(__dirname, "../package.json"), "utf-8"));
50927
+ var pkg = JSON.parse(readFileSync31(resolve18(__dirname, "../package.json"), "utf-8"));
50302
50928
  function versionLabel() {
50303
50929
  const base = `v${pkg.version}`;
50304
50930
  try {
50305
- const info2 = JSON.parse(readFileSync30(resolve18(__dirname, "build-info.json"), "utf-8"));
50931
+ const info2 = JSON.parse(readFileSync31(resolve18(__dirname, "build-info.json"), "utf-8"));
50306
50932
  if (info2?.sha) return `${base} (dev ${info2.sha}${info2.dirty ? ", modified" : ""})`;
50307
50933
  } catch {
50308
50934
  }
@@ -50343,7 +50969,7 @@ var backendGroup = [dbCommand, fnCommand, secretsCommand, keyCommand, logsComman
50343
50969
  var servicesGroup = [serviceCommand, generateCommand, askCommand, notifyCommand, paymentsCommand, realtimeCommand, recordsCommand, rbacCommand, auditCommand, domainCommand, tokenCommand];
50344
50970
  var filesGroup = [syncCommand, fileCommand, pushCommand, uploadCommand, storageCommand];
50345
50971
  var utilitiesGroup = [sandboxCommand, emailCommand, gmailCommand, locationCommand, textCommand, bugCommand];
50346
- var connectGroup = [loginCommand, logoutCommand, buildCommand, githubCommand, creditsCommand, doctorCommand, updateCommand, uninstallCommand];
50972
+ var connectGroup = [loginCommand, logoutCommand, buildCommand, githubCommand, creditsCommand, accountCommand, doctorCommand, updateCommand, uninstallCommand];
50347
50973
  var HELP_SECTIONS = [
50348
50974
  { title: "Start here", cmds: startGroup },
50349
50975
  { title: "App build & ship", cmds: buildGroup },
@@ -50365,8 +50991,10 @@ var SKILL_DOCS = {
50365
50991
  fn: "app-development",
50366
50992
  notify: "app-notify",
50367
50993
  payments: "app-payments",
50994
+ account: "plans",
50368
50995
  records: "app-records",
50369
50996
  key: "app-auth",
50997
+ secrets: "app-function-services",
50370
50998
  realtime: "app-realtime",
50371
50999
  job: "jobs",
50372
51000
  workflow: "workflow",