gipity 1.1.27 → 1.1.29

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
@@ -3979,10 +3979,10 @@ function prompt(question, output = process.stdout) {
3979
3979
  return Promise.reject(new Error(`prompt() called without a TTY: ${question.trim()}`));
3980
3980
  }
3981
3981
  const rl2 = createInterface({ input: process.stdin, output });
3982
- return new Promise((resolve19) => {
3982
+ return new Promise((resolve20) => {
3983
3983
  rl2.question(question, (answer) => {
3984
3984
  rl2.close();
3985
- resolve19(answer.trim());
3985
+ resolve20(answer.trim());
3986
3986
  });
3987
3987
  });
3988
3988
  }
@@ -4013,7 +4013,7 @@ async function confirm(question, opts = {}) {
4013
4013
  const wasRaw = stdin.isRaw ?? false;
4014
4014
  stdin.setRawMode(true);
4015
4015
  stdin.resume();
4016
- return new Promise((resolve19) => {
4016
+ return new Promise((resolve20) => {
4017
4017
  stdin.once("data", (key) => {
4018
4018
  stdin.setRawMode(wasRaw);
4019
4019
  stdin.pause();
@@ -4028,12 +4028,12 @@ async function confirm(question, opts = {}) {
4028
4028
  else if (k7 === "n") answer = false;
4029
4029
  else answer = defaultYes;
4030
4030
  console.log(answer ? "y" : "n");
4031
- resolve19(answer);
4031
+ resolve20(answer);
4032
4032
  });
4033
4033
  });
4034
4034
  }
4035
4035
  function pickOne(label2, max, defaultIdx = 1) {
4036
- return new Promise((resolve19, reject) => {
4036
+ return new Promise((resolve20, reject) => {
4037
4037
  process.stdout.write(` ${bold(label2)} (1-${max}) [${bold(String(defaultIdx))}]: `);
4038
4038
  const { stdin } = process;
4039
4039
  const wasRaw = stdin.isRaw ?? false;
@@ -4055,13 +4055,13 @@ function pickOne(label2, max, defaultIdx = 1) {
4055
4055
  if (ch === "\r" || ch === "\n") {
4056
4056
  cleanup();
4057
4057
  console.log(String(defaultIdx));
4058
- return resolve19(defaultIdx);
4058
+ return resolve20(defaultIdx);
4059
4059
  }
4060
4060
  const n = parseInt(ch, 10);
4061
4061
  if (n >= 1 && n <= max) {
4062
4062
  cleanup();
4063
4063
  console.log(String(n));
4064
- return resolve19(n);
4064
+ return resolve20(n);
4065
4065
  }
4066
4066
  };
4067
4067
  const onEnd = () => {
@@ -5420,8 +5420,8 @@ var require_streamx = __commonJS({
5420
5420
  return this;
5421
5421
  },
5422
5422
  next() {
5423
- return new Promise(function(resolve19, reject) {
5424
- promiseResolve = resolve19;
5423
+ return new Promise(function(resolve20, reject) {
5424
+ promiseResolve = resolve20;
5425
5425
  promiseReject = reject;
5426
5426
  const data = stream.read();
5427
5427
  if (data !== null) ondata(data);
@@ -5451,11 +5451,11 @@ var require_streamx = __commonJS({
5451
5451
  }
5452
5452
  function destroy(err) {
5453
5453
  stream.destroy(err);
5454
- return new Promise((resolve19, reject) => {
5455
- if (stream._duplexState & DESTROYED) return resolve19({ value: void 0, done: true });
5454
+ return new Promise((resolve20, reject) => {
5455
+ if (stream._duplexState & DESTROYED) return resolve20({ value: void 0, done: true });
5456
5456
  stream.once("close", function() {
5457
5457
  if (err) reject(err);
5458
- else resolve19({ value: void 0, done: true });
5458
+ else resolve20({ value: void 0, done: true });
5459
5459
  });
5460
5460
  });
5461
5461
  }
@@ -5499,8 +5499,8 @@ var require_streamx = __commonJS({
5499
5499
  const writes = pending + (ws2._duplexState & WRITE_WRITING ? 1 : 0);
5500
5500
  if (writes === 0) return Promise.resolve(true);
5501
5501
  if (state.drains === null) state.drains = [];
5502
- return new Promise((resolve19) => {
5503
- state.drains.push({ writes, resolve: resolve19 });
5502
+ return new Promise((resolve20) => {
5503
+ state.drains.push({ writes, resolve: resolve20 });
5504
5504
  });
5505
5505
  }
5506
5506
  write(data) {
@@ -5605,10 +5605,10 @@ var require_streamx = __commonJS({
5605
5605
  cb2(null);
5606
5606
  }
5607
5607
  function pipelinePromise(...streams) {
5608
- return new Promise((resolve19, reject) => {
5608
+ return new Promise((resolve20, reject) => {
5609
5609
  return pipeline(...streams, (err) => {
5610
5610
  if (err) return reject(err);
5611
- resolve19();
5611
+ resolve20();
5612
5612
  });
5613
5613
  });
5614
5614
  }
@@ -6263,16 +6263,16 @@ var require_extract = __commonJS({
6263
6263
  entryCallback = null;
6264
6264
  cb2(err);
6265
6265
  }
6266
- function onnext(resolve19, reject) {
6266
+ function onnext(resolve20, reject) {
6267
6267
  if (error2) {
6268
6268
  return reject(error2);
6269
6269
  }
6270
6270
  if (entryStream) {
6271
- resolve19({ value: entryStream, done: false });
6271
+ resolve20({ value: entryStream, done: false });
6272
6272
  entryStream = null;
6273
6273
  return;
6274
6274
  }
6275
- promiseResolve = resolve19;
6275
+ promiseResolve = resolve20;
6276
6276
  promiseReject = reject;
6277
6277
  consumeCallback(null);
6278
6278
  if (extract3._finished && promiseResolve) {
@@ -6300,11 +6300,11 @@ var require_extract = __commonJS({
6300
6300
  function destroy(err) {
6301
6301
  extract3.destroy(err);
6302
6302
  consumeCallback(err);
6303
- return new Promise((resolve19, reject) => {
6304
- if (extract3.destroyed) return resolve19({ value: void 0, done: true });
6303
+ return new Promise((resolve20, reject) => {
6304
+ if (extract3.destroyed) return resolve20({ value: void 0, done: true });
6305
6305
  extract3.once("close", function() {
6306
6306
  if (err) reject(err);
6307
- else resolve19({ value: void 0, done: true });
6307
+ else resolve20({ value: void 0, done: true });
6308
6308
  });
6309
6309
  });
6310
6310
  }
@@ -6705,13 +6705,13 @@ function claudeAuthStatus() {
6705
6705
  }
6706
6706
  }
6707
6707
  function claudeAuthStatusAsync() {
6708
- return new Promise((resolve19) => {
6708
+ return new Promise((resolve20) => {
6709
6709
  let out = "";
6710
6710
  let settled = false;
6711
6711
  const done = (v7) => {
6712
6712
  if (!settled) {
6713
6713
  settled = true;
6714
- resolve19(v7);
6714
+ resolve20(v7);
6715
6715
  }
6716
6716
  };
6717
6717
  let child;
@@ -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 {
@@ -9229,7 +9232,7 @@ async function postForTarEntries(path5, body, retried = false) {
9229
9232
  }
9230
9233
  const extract3 = tar.extract();
9231
9234
  const entries = [];
9232
- const done = new Promise((resolve19, reject) => {
9235
+ const done = new Promise((resolve20, reject) => {
9233
9236
  extract3.on("entry", (header, stream, next) => {
9234
9237
  const chunks = [];
9235
9238
  stream.on("data", (c) => chunks.push(c));
@@ -9240,7 +9243,7 @@ async function postForTarEntries(path5, body, retried = false) {
9240
9243
  stream.on("error", reject);
9241
9244
  stream.resume();
9242
9245
  });
9243
- extract3.on("finish", () => resolve19());
9246
+ extract3.on("finish", () => resolve20());
9244
9247
  extract3.on("error", reject);
9245
9248
  });
9246
9249
  return read(async () => {
@@ -34365,9 +34368,9 @@ var {
34365
34368
  init_config();
34366
34369
  init_setup();
34367
34370
  init_utils();
34368
- import { readFileSync as readFileSync30 } from "fs";
34371
+ import { readFileSync as readFileSync32 } from "fs";
34369
34372
  import { fileURLToPath as fileURLToPath4 } from "url";
34370
- import { dirname as dirname16, resolve as resolve18 } from "path";
34373
+ import { dirname as dirname16, resolve as resolve19 } from "path";
34371
34374
 
34372
34375
  // src/helpers/output.ts
34373
34376
  var frameOpen = false;
@@ -34795,25 +34798,25 @@ async function hashFile(path5) {
34795
34798
  const hash = createHash("sha256");
34796
34799
  let size = 0;
34797
34800
  const stream = createReadStream(path5);
34798
- await new Promise((resolve19, reject) => {
34801
+ await new Promise((resolve20, reject) => {
34799
34802
  stream.on("data", (chunk) => {
34800
34803
  const buf = chunk;
34801
34804
  hash.update(buf);
34802
34805
  size += buf.length;
34803
34806
  });
34804
- stream.on("end", () => resolve19());
34807
+ stream.on("end", () => resolve20());
34805
34808
  stream.on("error", reject);
34806
34809
  });
34807
34810
  return { sha256: hash.digest("hex"), size };
34808
34811
  }
34809
34812
  function readRange(path5, start, end) {
34810
- return new Promise((resolve19, reject) => {
34813
+ return new Promise((resolve20, reject) => {
34811
34814
  const chunks = [];
34812
34815
  const stream = createReadStream(path5, { start, end });
34813
34816
  stream.on("data", (c) => {
34814
34817
  chunks.push(c);
34815
34818
  });
34816
- stream.on("end", () => resolve19(Buffer.concat(chunks)));
34819
+ stream.on("end", () => resolve20(Buffer.concat(chunks)));
34817
34820
  stream.on("error", reject);
34818
34821
  });
34819
34822
  }
@@ -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);
@@ -35176,7 +35207,7 @@ async function fetchRemote(projectGuid2) {
35176
35207
  function extractTarToMap(stream, idleMs, onBytes, keep) {
35177
35208
  const extract3 = tar2.extract();
35178
35209
  const files = /* @__PURE__ */ new Map();
35179
- return new Promise((resolve19, reject) => {
35210
+ return new Promise((resolve20, reject) => {
35180
35211
  let settled = false;
35181
35212
  let idle;
35182
35213
  const arm = () => {
@@ -35212,7 +35243,7 @@ function extractTarToMap(stream, idleMs, onBytes, keep) {
35212
35243
  });
35213
35244
  entryStream.resume();
35214
35245
  });
35215
- extract3.on("finish", () => done(resolve19, files));
35246
+ extract3.on("finish", () => done(resolve20, files));
35216
35247
  extract3.on("error", (e) => done(reject, e));
35217
35248
  stream.on("error", (e) => done(reject, e));
35218
35249
  arm();
@@ -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,69 +40467,14 @@ 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";
40209
- import { join as join20 } from "path";
40476
+ import { existsSync as existsSync15, mkdirSync as mkdirSync12, readFileSync as readFileSync19, writeFileSync as writeFileSync13 } from "fs";
40477
+ import { isAbsolute, join as join20, resolve as resolve13 } from "path";
40210
40478
  init_colors();
40211
40479
  function mergedOpts(cmd) {
40212
40480
  return cmd.optsWithGlobals();
@@ -40268,7 +40536,7 @@ function printStepRuns(steps, emptyNote) {
40268
40536
  }
40269
40537
  }
40270
40538
  var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
40271
- var sleep2 = (ms2) => new Promise((resolve19) => setTimeout(resolve19, ms2));
40539
+ var sleep2 = (ms2) => new Promise((resolve20) => setTimeout(resolve20, ms2));
40272
40540
  async function waitForRun(wfGuid, prevGuid, timeoutSec) {
40273
40541
  const deadline = Date.now() + timeoutSec * 1e3;
40274
40542
  let runGuid;
@@ -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
  });
@@ -40412,7 +40680,13 @@ steps:
40412
40680
  then return { summary, needs_attention } where needs_attention is a list of short strings.
40413
40681
  tools: [memory, db_query]
40414
40682
  `;
40415
- workflowCommand.command("create").description("Create a workflow from a YAML file in the project (e.g. workflows/foo.yaml)").option("--from <path>", "Project-relative YAML file path").option("--heartbeat", `Scaffold ${HEARTBEAT_PATH} (a daily check-in that keeps notes in project memory) and create it`).option("--name <name>", "Override the name in the YAML").option("--json", "Output as JSON").action((_opts, cmd) => run("Create", async () => {
40683
+ function readWorkflowYaml(from) {
40684
+ const candidates = isAbsolute(from) ? [from] : [resolve13(from), ...getProjectRoot() ? [join20(getProjectRoot(), from)] : []];
40685
+ const found = candidates.find((p) => existsSync15(p));
40686
+ if (!found) throw new Error(`No workflow file at ${from}.`);
40687
+ return readFileSync19(found, "utf-8");
40688
+ }
40689
+ workflowCommand.command("create").description("Create a workflow from a YAML file in the project (e.g. workflows/foo.yaml)").option("--from <path>", "Workflow YAML file (any local path, e.g. workflows/foo.yaml)").option("--heartbeat", `Scaffold ${HEARTBEAT_PATH} (a daily check-in that keeps notes in project memory) and create it`).option("--name <name>", "Override the name in the YAML").option("--json", "Output as JSON").action((_opts, cmd) => run("Create", async () => {
40416
40690
  const opts = mergedOpts(cmd);
40417
40691
  const config = requireConfig2();
40418
40692
  if (opts.from && opts.heartbeat) throw new Error("Pass --from <path> or --heartbeat, not both.");
@@ -40424,12 +40698,12 @@ workflowCommand.command("create").description("Create a workflow from a YAML fil
40424
40698
  const local = join20(root, HEARTBEAT_PATH);
40425
40699
  if (!existsSync15(local)) {
40426
40700
  mkdirSync12(join20(root, "workflows"), { recursive: true });
40427
- writeFileSync12(local, HEARTBEAT_YAML);
40701
+ writeFileSync13(local, HEARTBEAT_YAML);
40428
40702
  }
40429
40703
  await pushFile(local);
40430
40704
  }
40431
40705
  const body = {
40432
- config_yaml_path: from,
40706
+ config_yaml: readWorkflowYaml(from),
40433
40707
  project_guid: config.projectGuid
40434
40708
  };
40435
40709
  if (opts.name) body.name = opts.name;
@@ -40437,12 +40711,12 @@ workflowCommand.command("create").description("Create a workflow from a YAML fil
40437
40711
  const guid = res.data.short_guid ?? res.data.guid;
40438
40712
  printResult(`Workflow created from ${from} (${guid}).`, opts, { created: true, guid, from });
40439
40713
  }));
40440
- workflowCommand.command("edit <name>").alias("update").description("Update a workflow from a YAML file").requiredOption("--from <path>", "Project-relative YAML file path").option("--json", "Output as JSON").action((name, _opts, cmd) => run("Edit", async () => {
40714
+ workflowCommand.command("edit <name>").alias("update").description("Update a workflow from a YAML file").requiredOption("--from <path>", "Workflow YAML file (any local path, e.g. workflows/foo.yaml)").option("--json", "Output as JSON").action((name, _opts, cmd) => run("Edit", async () => {
40441
40715
  const opts = mergedOpts(cmd);
40442
40716
  const config = requireConfig2();
40443
40717
  const wf2 = await resolveWorkflow(name);
40444
40718
  await put(`/workflows/${wf2.short_guid}`, {
40445
- config_yaml_path: opts.from,
40719
+ config_yaml: readWorkflowYaml(opts.from),
40446
40720
  project_guid: config.projectGuid
40447
40721
  });
40448
40722
  printResult(`Updated "${wf2.name}" from ${opts.from}.`, opts, { updated: wf2.name });
@@ -40730,6 +41004,64 @@ creditsCommand.command("usage").description("Show recent usage").option("--limit
40730
41004
  });
40731
41005
  }));
40732
41006
 
41007
+ // src/commands/account.ts
41008
+ init_api();
41009
+ init_colors();
41010
+ init_utils();
41011
+ var NSFW_TERMS = [
41012
+ "Turning on NSFW services lets this account use adult (NSFW) image models.",
41013
+ "",
41014
+ "By turning it on you confirm that:",
41015
+ " - you are 18 or older;",
41016
+ " - nothing you make involves minors, ever;",
41017
+ " - you will not make sexual images of real people;",
41018
+ " - you will not make content showing sexual violence or non-consent;",
41019
+ " - you are responsible for what your apps show and to whom.",
41020
+ "",
41021
+ "Prompts are checked for safety and kept for abuse review. Gipity may turn this off.",
41022
+ "While it is on, app payments (Stripe Connect) stop working for your apps.",
41023
+ "Buying credits and your plan are not affected."
41024
+ ].join("\n");
41025
+ function renderState(s) {
41026
+ console.log(`NSFW services: ${s.allow_nsfw_services ? bold("on") : dim("off")}`);
41027
+ if (s.nsfw_attested_at) console.log(muted(` Terms accepted: ${s.nsfw_attested_at.slice(0, 10)}`));
41028
+ if (s.allow_nsfw_services) console.log(muted(" App payments (Stripe Connect) are off while this is on."));
41029
+ else if (!s.self_serve_open) console.log(muted(" Not open for self-serve yet."));
41030
+ }
41031
+ var accountCommand = new Command("account").description("Account settings").addHelpText("after", "\nAccount-level settings for your Gipity account, e.g. `gipity account nsfw status`.");
41032
+ var nsfwCommand = accountCommand.command("nsfw").description("Allow NSFW services (adult image models) for this account");
41033
+ nsfwCommand.command("status", { isDefault: true }).description("Show whether NSFW services are on").option("--json", "Output as JSON").action((opts) => run("Account", async () => {
41034
+ const res = await get("/users/me/nsfw");
41035
+ if (opts.json) {
41036
+ console.log(JSON.stringify(res.data));
41037
+ return;
41038
+ }
41039
+ renderState(res.data);
41040
+ }));
41041
+ 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 () => {
41042
+ if (!opts.json) console.log(`${NSFW_TERMS}
41043
+ `);
41044
+ const ok = await confirm(`Turn on ${brand("NSFW services")} and accept these terms?`, { default: "no", skip: opts.yes === true });
41045
+ if (!ok) {
41046
+ console.log(muted("Left off."));
41047
+ process.exit(1);
41048
+ }
41049
+ const res = await patch("/users/me/nsfw", { allow: true, attest: true });
41050
+ if (opts.json) {
41051
+ console.log(JSON.stringify(res.data));
41052
+ return;
41053
+ }
41054
+ renderState(res.data);
41055
+ }));
41056
+ nsfwCommand.command("off").description("Turn NSFW services off (app payments work again)").option("--json", "Output as JSON").action((opts) => run("Account", async () => {
41057
+ const res = await patch("/users/me/nsfw", { allow: false });
41058
+ if (opts.json) {
41059
+ console.log(JSON.stringify(res.data));
41060
+ return;
41061
+ }
41062
+ renderState(res.data);
41063
+ }));
41064
+
40733
41065
  // src/commands/file.ts
40734
41066
  init_api();
40735
41067
  init_config();
@@ -40935,8 +41267,8 @@ storageCommand.command("retention").description("View or adjust your file versio
40935
41267
  init_platform();
40936
41268
  init_auth();
40937
41269
  init_api();
40938
- 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";
41270
+ import { join as join22, dirname as dirname12, resolve as resolve14, basename as basename6, sep as sep6 } from "path";
41271
+ import { existsSync as existsSync17, mkdirSync as mkdirSync14, readFileSync as readFileSync21, writeFileSync as writeFileSync15, renameSync as renameSync2, readdirSync as readdirSync8, statSync as statSync8 } from "fs";
40940
41272
  import { homedir as homedir15 } from "os";
40941
41273
  import { fileURLToPath as fileURLToPath2 } from "url";
40942
41274
  import { randomUUID } from "crypto";
@@ -41296,14 +41628,14 @@ init_claude_setup();
41296
41628
  init_agents();
41297
41629
 
41298
41630
  // src/prefs.ts
41299
- import { existsSync as existsSync16, mkdirSync as mkdirSync13, readFileSync as readFileSync18, writeFileSync as writeFileSync13 } from "fs";
41631
+ import { existsSync as existsSync16, mkdirSync as mkdirSync13, readFileSync as readFileSync20, writeFileSync as writeFileSync14 } from "fs";
41300
41632
  import { homedir as homedir14 } from "os";
41301
41633
  import { join as join21 } from "path";
41302
41634
  var PREFS_PATH = join21(homedir14(), ".gipity", "prefs.json");
41303
41635
  function readPrefs() {
41304
41636
  if (!existsSync16(PREFS_PATH)) return {};
41305
41637
  try {
41306
- const parsed = JSON.parse(readFileSync18(PREFS_PATH, "utf-8"));
41638
+ const parsed = JSON.parse(readFileSync20(PREFS_PATH, "utf-8"));
41307
41639
  return {
41308
41640
  lastAgent: typeof parsed.lastAgent === "string" ? parsed.lastAgent : void 0
41309
41641
  };
@@ -41316,7 +41648,7 @@ function writePrefs(update) {
41316
41648
  const current = readPrefs();
41317
41649
  const next = { ...current, ...update };
41318
41650
  mkdirSync13(join21(homedir14(), ".gipity"), { recursive: true });
41319
- writeFileSync13(PREFS_PATH, JSON.stringify(next, null, 2) + "\n");
41651
+ writeFileSync14(PREFS_PATH, JSON.stringify(next, null, 2) + "\n");
41320
41652
  } catch {
41321
41653
  }
41322
41654
  }
@@ -41329,7 +41661,7 @@ function readOwnPkg(fromDir) {
41329
41661
  const p = join22(d, "package.json");
41330
41662
  if (existsSync17(p)) {
41331
41663
  try {
41332
- const pkg2 = JSON.parse(readFileSync19(p, "utf-8"));
41664
+ const pkg2 = JSON.parse(readFileSync21(p, "utf-8"));
41333
41665
  if (pkg2.name === "gipity") return pkg2;
41334
41666
  } catch {
41335
41667
  }
@@ -41426,7 +41758,7 @@ function hasStreamJsonFlag(args) {
41426
41758
  function markFolderTrusted(dir) {
41427
41759
  try {
41428
41760
  const file = join22(homedir15(), ".claude.json");
41429
- const cfg = existsSync17(file) ? JSON.parse(readFileSync19(file, "utf-8")) : {};
41761
+ const cfg = existsSync17(file) ? JSON.parse(readFileSync21(file, "utf-8")) : {};
41430
41762
  if (typeof cfg !== "object" || cfg === null) return;
41431
41763
  if (typeof cfg.projects !== "object" || cfg.projects === null) cfg.projects = {};
41432
41764
  const entry = typeof cfg.projects[dir] === "object" && cfg.projects[dir] !== null ? cfg.projects[dir] : {};
@@ -41434,7 +41766,7 @@ function markFolderTrusted(dir) {
41434
41766
  entry.hasTrustDialogAccepted = true;
41435
41767
  cfg.projects[dir] = entry;
41436
41768
  const tmp = `${file}.gipity-tmp`;
41437
- writeFileSync14(tmp, JSON.stringify(cfg, null, 2));
41769
+ writeFileSync15(tmp, JSON.stringify(cfg, null, 2));
41438
41770
  renameSync2(tmp, file);
41439
41771
  } catch {
41440
41772
  }
@@ -41545,7 +41877,7 @@ async function runLaunch(cmdName, cmdCfg, opts) {
41545
41877
  let existing = getConfig();
41546
41878
  let forceAdoptCwd = false;
41547
41879
  if (existing && !opts.newProject && !opts.project && !nonInteractive) {
41548
- const cwdHasConfig = existsSync17(resolve13(process.cwd(), ".gipity.json"));
41880
+ const cwdHasConfig = existsSync17(resolve14(process.cwd(), ".gipity.json"));
41549
41881
  if (!cwdHasConfig && isLikelyEmpty(process.cwd())) {
41550
41882
  const ancestorRoot = dirname12(getConfigPath());
41551
41883
  console.log(` ${bold("You are inside an existing Gipity project.")}
@@ -43548,7 +43880,7 @@ async function recordsHttp(opts) {
43548
43880
  del: (path5, body) => publicRequest("DELETE", path5, body, headers)
43549
43881
  };
43550
43882
  }
43551
- recordsCommand.command("list").description("List record tables").option("--json", "Output as JSON").action((opts) => run("List", async () => {
43883
+ recordsCommand.command("tables").description("List the tables exposed through Gipity Records").option("--json", "Output as JSON").action((opts) => run("Tables", async () => {
43552
43884
  const config = requireConfig2();
43553
43885
  const res = await get(`/api/${config.projectGuid}/records-config`);
43554
43886
  printList(
@@ -43588,7 +43920,7 @@ recordsCommand.command("config <table>").description("Show or set a table's Reco
43588
43920
  d
43589
43921
  );
43590
43922
  }));
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 () => {
43923
+ 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
43924
  const api = await recordsHttp(opts);
43593
43925
  const params = new URLSearchParams();
43594
43926
  if (opts.q) params.set("q", opts.q);
@@ -43649,7 +43981,7 @@ recordsCommand.command("delete <table> <id>").description("Delete a record (soft
43649
43981
  );
43650
43982
  const data = res?.data ?? { table, id: id2, deleted: true, purged: !!opts.purge };
43651
43983
  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\`).`,
43984
+ 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
43985
  opts,
43654
43986
  data
43655
43987
  );
@@ -44148,8 +44480,8 @@ jobCommand.command("submit <name> [body]").description("Submit a job (returns a
44148
44480
  } else {
44149
44481
  const tag = res.data.replayed ? warning(" (replayed)") : "";
44150
44482
  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)) {
44483
+ const TERMINAL2 = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44484
+ if (!TERMINAL2.has(res.data.status)) {
44153
44485
  console.error(muted(`Block until it finishes: gipity job wait ${res.data.run_guid}`));
44154
44486
  }
44155
44487
  }
@@ -44175,7 +44507,7 @@ jobCommand.command("status <runGuid>").description("Show status of a job run").o
44175
44507
  }));
44176
44508
  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
44509
  const config = requireConfig2();
44178
- const TERMINAL = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44510
+ const TERMINAL2 = /* @__PURE__ */ new Set(["success", "failed", "cancelled", "canceled", "error"]);
44179
44511
  const durOpt = parseDuration(opts.timeout, "s");
44180
44512
  const timeoutSec = durOpt ? Math.max(1, Math.round(durOpt.value)) : parseInt(opts.timeout, 10);
44181
44513
  const timeout = Number.isFinite(timeoutSec) && timeoutSec > 0 ? timeoutSec : 90;
@@ -44184,7 +44516,7 @@ jobCommand.command("wait <runGuid>").description("Block until a job run finishes
44184
44516
  const fetchRun = async () => (await get(`/projects/${config.projectGuid}/jobs/runs/${encodeURIComponent(runGuid)}`)).data;
44185
44517
  let r = await fetchRun();
44186
44518
  let lastProgress = "";
44187
- while (!TERMINAL.has(r.status) && Date.now() < deadline) {
44519
+ while (!TERMINAL2.has(r.status) && Date.now() < deadline) {
44188
44520
  if (!opts.json) {
44189
44521
  const prog = r.progress_pct != null ? `${Math.round(r.progress_pct * 100)}%${r.progress_message ? ` (${r.progress_message})` : ""}` : r.status;
44190
44522
  if (prog !== lastProgress) {
@@ -44197,7 +44529,7 @@ jobCommand.command("wait <runGuid>").description("Block until a job run finishes
44197
44529
  await new Promise((res) => setTimeout(res, Math.min(interval * 1e3, remaining)));
44198
44530
  r = await fetchRun();
44199
44531
  }
44200
- const done = TERMINAL.has(r.status);
44532
+ const done = TERMINAL2.has(r.status);
44201
44533
  if (opts.json) {
44202
44534
  console.log(JSON.stringify(done ? r : { ...r, waiting: true, timed_out: true }));
44203
44535
  } else if (!done) {
@@ -44343,9 +44675,9 @@ jobCommand.command("cancel <runGuid>").description("Cancel a queued or running j
44343
44675
  }));
44344
44676
  jobCommand.command("run-local <name>").description("Run the job in a local Docker container against your local filesystem (no platform round-trip)").option("--image <image>", "Docker image to run inside", "easyclaw/sandbox:latest").option("--no-deps", "Skip pip/npm install even if a deps file is present").option("--json", "Capture the job's output and print one JSON result (exitCode, stdout, stderr) instead of streaming it").action(async (name, opts) => {
44345
44677
  const { existsSync: existsSync27, statSync: statSync12 } = await import("node:fs");
44346
- const { resolve: resolve19, join: join32 } = await import("node:path");
44678
+ const { resolve: resolve20, join: join32 } = await import("node:path");
44347
44679
  const { spawnCommand: spawnCommand2, spawnSyncCommand: spawnSyncCommand2 } = await Promise.resolve().then(() => (init_platform(), platform_exports));
44348
- const jobDir = resolve19(process.cwd(), "jobs", name);
44680
+ const jobDir = resolve20(process.cwd(), "jobs", name);
44349
44681
  if (!existsSync27(jobDir) || !statSync12(jobDir).isDirectory()) {
44350
44682
  console.error(error(`jobs/${name}/ not found in current directory`));
44351
44683
  process.exit(1);
@@ -44565,8 +44897,213 @@ emailCommand.command("log").description("Recent email() sends and skipped attemp
44565
44897
  init_api();
44566
44898
  init_config();
44567
44899
  init_colors();
44568
- import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync15, readFileSync as readFileSync20 } from "fs";
44569
- import { resolve as resolvePath2, dirname as dirname13, relative as relative5, isAbsolute, basename as basename7 } from "path";
44900
+ import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync16, readFileSync as readFileSync22 } from "fs";
44901
+ import { resolve as resolvePath2, dirname as dirname13, relative as relative5, isAbsolute as isAbsolute2, basename as basename7 } from "path";
44902
+
44903
+ // src/commands/generate-async.ts
44904
+ init_api();
44905
+ init_config();
44906
+ init_colors();
44907
+ init_utils();
44908
+ var isQueuedModel = (model) => !!model && model.startsWith("gipity-");
44909
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired"]);
44910
+ var gensPath = (guid) => `/projects/${guid}/generate/image/generations`;
44911
+ function pollMs() {
44912
+ const v7 = Number(process.env.GIPITY_GENERATE_POLL_MS);
44913
+ return Number.isFinite(v7) && v7 > 0 ? v7 : 2e3;
44914
+ }
44915
+ function fmtEta(ms2) {
44916
+ if (ms2 == null || !Number.isFinite(ms2)) return null;
44917
+ const s = Math.round(ms2 / 1e3);
44918
+ if (s < 10) return "under 10s";
44919
+ if (s < 90) return `about ${s}s`;
44920
+ const m = Math.round(s / 60);
44921
+ if (m < 90) return `about ${m} min`;
44922
+ return `about ${Math.round(m / 60)} h`;
44923
+ }
44924
+ function statusText(g) {
44925
+ switch (g.status) {
44926
+ case "queued": {
44927
+ const ahead = g.queue_position != null ? Math.max(0, g.queue_position - 1) : null;
44928
+ const eta = fmtEta(g.eta_ms);
44929
+ const where = ahead === null ? "queued" : ahead === 0 ? "queued: next up" : `queued: ${ahead} ahead`;
44930
+ return eta ? `${where}, ${eta}` : where;
44931
+ }
44932
+ case "dispatched":
44933
+ return "starting";
44934
+ case "running": {
44935
+ if (g.phase === "loading") return "loading the model";
44936
+ if (g.step != null && g.total) return `rendering ${g.step}/${g.total}`;
44937
+ if (g.progress != null) return `rendering ${Math.round(g.progress * 100)}%`;
44938
+ return "rendering";
44939
+ }
44940
+ case "succeeded":
44941
+ return "done";
44942
+ case "failed":
44943
+ return `failed: ${g.error?.message ?? "unknown error"}`;
44944
+ case "cancelled":
44945
+ return "cancelled";
44946
+ case "expired":
44947
+ return "expired: it waited too long in the queue (not charged)";
44948
+ }
44949
+ }
44950
+ async function submitGenerations(projectGuid2, body) {
44951
+ const res = await post(gensPath(projectGuid2), body);
44952
+ return res.data;
44953
+ }
44954
+ async function fetchGenerations(projectGuid2, ids) {
44955
+ const res = await get(`${gensPath(projectGuid2)}?ids=${ids.map(encodeURIComponent).join(",")}`);
44956
+ return res.data;
44957
+ }
44958
+ function combinedText(gens) {
44959
+ if (gens.length === 1) return statusText(gens[0]);
44960
+ const done = gens.filter((g) => TERMINAL.has(g.status)).length;
44961
+ const live = gens.find((g) => !TERMINAL.has(g.status));
44962
+ return `${done}/${gens.length} finished${live ? `; ${statusText(live)}` : ""}`;
44963
+ }
44964
+ async function waitForGenerations(projectGuid2, initial, opts = {}) {
44965
+ const ids = initial.map((g) => g.id);
44966
+ const tty = !!process.stdout.isTTY && !opts.json;
44967
+ const say = (line) => opts.json ? console.error(line) : console.log(line);
44968
+ let gens = initial;
44969
+ let last = "";
44970
+ let lineOpen = false;
44971
+ const draw = (text) => {
44972
+ if (tty) {
44973
+ process.stdout.write(`\r ${muted(text)}\x1B[K`);
44974
+ lineOpen = true;
44975
+ } else if (text !== last) {
44976
+ say(` ${text}`);
44977
+ }
44978
+ last = text;
44979
+ };
44980
+ const closeLine = () => {
44981
+ if (lineOpen) {
44982
+ process.stdout.write("\r\x1B[K");
44983
+ lineOpen = false;
44984
+ }
44985
+ };
44986
+ let interrupted = false;
44987
+ const onSigint = () => {
44988
+ interrupted = true;
44989
+ };
44990
+ process.on("SIGINT", onSigint);
44991
+ try {
44992
+ draw(combinedText(gens));
44993
+ while (!gens.every((g) => TERMINAL.has(g.status))) {
44994
+ await sleepUnlessInterrupted(pollMs(), () => interrupted);
44995
+ if (interrupted) break;
44996
+ gens = await fetchGenerations(projectGuid2, ids);
44997
+ draw(combinedText(gens));
44998
+ }
44999
+ } finally {
45000
+ process.off("SIGINT", onSigint);
45001
+ closeLine();
45002
+ }
45003
+ if (interrupted) {
45004
+ const open = gens.filter((g) => !TERMINAL.has(g.status)).map((g) => g.id);
45005
+ 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" })) {
45006
+ for (const id2 of open) await post(`${gensPath(projectGuid2)}/${encodeURIComponent(id2)}/cancel`);
45007
+ console.log(muted(`Cancelled ${open.join(" ")} (not charged).`));
45008
+ } else {
45009
+ console.error(muted(`Left queued. Check later with: gipity generate status ${open.join(" ")}`));
45010
+ }
45011
+ process.exit(130);
45012
+ }
45013
+ return gens;
45014
+ }
45015
+ function sleepUnlessInterrupted(ms2, stop) {
45016
+ return new Promise((resolve20) => {
45017
+ const started = Date.now();
45018
+ const tick = () => {
45019
+ if (stop() || Date.now() - started >= ms2) return resolve20();
45020
+ setTimeout(tick, Math.min(100, ms2));
45021
+ };
45022
+ tick();
45023
+ });
45024
+ }
45025
+ function printGeneration(g) {
45026
+ const head = g.status === "succeeded" ? success(g.id) : g.status === "failed" || g.status === "expired" ? error(g.id) : g.id;
45027
+ console.log(`${head} ${muted(g.model)} ${statusText(g)}`);
45028
+ if (g.status === "succeeded" && g.outputs?.full?.url) console.log(` ${muted("url:")} ${g.outputs.full.url}`);
45029
+ if (g.credits_charged != null && g.credits_charged > 0) console.log(` ${muted("credits:")} ${g.credits_charged}`);
45030
+ }
45031
+ 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 () => {
45032
+ const { config } = await resolveProjectContext();
45033
+ const gens = await fetchGenerations(config.projectGuid, ids);
45034
+ if (opts.json) {
45035
+ console.log(JSON.stringify(gens));
45036
+ return;
45037
+ }
45038
+ const found = new Set(gens.map((g) => g.id));
45039
+ for (const g of gens) printGeneration(g);
45040
+ for (const id2 of ids.filter((i) => !found.has(i))) console.log(`${error(id2)} not found`);
45041
+ }));
45042
+ 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 () => {
45043
+ const { config } = await resolveProjectContext();
45044
+ const out = [];
45045
+ for (const id2 of ids) {
45046
+ const res = await post(`${gensPath(config.projectGuid)}/${encodeURIComponent(id2)}/cancel`);
45047
+ out.push(res.data);
45048
+ }
45049
+ if (opts.json) {
45050
+ console.log(JSON.stringify(out));
45051
+ return;
45052
+ }
45053
+ for (const g of out) printGeneration(g);
45054
+ }));
45055
+ 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 () => {
45056
+ const { config } = await resolveProjectContext();
45057
+ const qs = opts.open ? "status=open" : `limit=${Number.isFinite(opts.limit) ? opts.limit : 20}`;
45058
+ const res = await get(`${gensPath(config.projectGuid)}?${qs}`);
45059
+ if (opts.json) {
45060
+ console.log(JSON.stringify(res.data));
45061
+ return;
45062
+ }
45063
+ if (!res.data.length) {
45064
+ console.log(muted(opts.open ? "Nothing queued or running." : "No generations yet."));
45065
+ return;
45066
+ }
45067
+ for (const g of res.data) printGeneration(g);
45068
+ }));
45069
+ function fmtWait(s) {
45070
+ return s === void 0 ? "?" : fmtEta(s * 1e3) ?? "?";
45071
+ }
45072
+ 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 () => {
45073
+ const { config } = await resolveProjectContext();
45074
+ const res = await get(
45075
+ `/projects/${config.projectGuid}/generate/image/models`
45076
+ );
45077
+ if (opts.json) {
45078
+ console.log(JSON.stringify(res.data));
45079
+ return;
45080
+ }
45081
+ const { models, gipity_gpu: gpu } = res.data;
45082
+ const cloud = models.filter((m) => !isQueuedModel(m.id));
45083
+ const queued = models.filter((m) => isQueuedModel(m.id));
45084
+ if (cloud.length) {
45085
+ console.log("Cloud models (one request, immediate):");
45086
+ for (const m of cloud) console.log(` ${m.id.padEnd(30)} ${muted(m.provider)}`);
45087
+ }
45088
+ if (queued.length) {
45089
+ if (cloud.length) console.log("");
45090
+ console.log("Gipity GPU models (queued, half the usual price):");
45091
+ if (gpu) {
45092
+ 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"));
45093
+ }
45094
+ const width = Math.max(...queued.map((m) => m.id.length));
45095
+ for (const m of queued) {
45096
+ const price = m.price_credits != null ? `${m.price_credits} credits` : "not priced yet";
45097
+ const tags = [m.nsfw ? warning("NSFW") : "", m.max_references ? muted(`refs:${m.max_references}`) : ""].filter(Boolean).join(" ");
45098
+ const state = m.available === false ? error(`unavailable${m.unavailable_reason ? `: ${m.unavailable_reason}` : ""}`) : "";
45099
+ console.log(` ${m.id.padEnd(width)} ${price.padEnd(16)} ${[tags, state].filter(Boolean).join(" ")}`.trimEnd());
45100
+ if (m.label || m.description) console.log(muted(` ${"".padEnd(width)} ${[m.label, m.description].filter(Boolean).join(": ")}`));
45101
+ }
45102
+ }
45103
+ }));
45104
+ function addGenerationSubcommands(parent) {
45105
+ return parent.addCommand(statusCommand2).addCommand(cancelCommand).addCommand(listCommand).addCommand(modelsCommand);
45106
+ }
44570
45107
 
44571
45108
  // src/provider-docs.ts
44572
45109
  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`;
@@ -44667,7 +45204,7 @@ async function downloadFile(url, filename, explicit) {
44667
45204
  const outPath = explicit ? filename : correctExtension(filename, buffer);
44668
45205
  if (explicit) noteFormatMismatch(filename, buffer);
44669
45206
  ensureOutputDir(outPath);
44670
- writeFileSync15(outPath, buffer);
45207
+ writeFileSync16(outPath, buffer);
44671
45208
  const savedPath = resolvePath2(outPath);
44672
45209
  await pushGenerated(savedPath);
44673
45210
  return savedPath;
@@ -44722,7 +45259,7 @@ async function pushGenerated(savedPath) {
44722
45259
  const configPath = getConfigPath();
44723
45260
  if (!configPath) return;
44724
45261
  const rel2 = relative5(dirname13(configPath), savedPath);
44725
- if (rel2.startsWith("..") || isAbsolute(rel2)) return;
45262
+ if (rel2.startsWith("..") || isAbsolute2(rel2)) return;
44726
45263
  try {
44727
45264
  await pushFile(savedPath);
44728
45265
  } catch (err) {
@@ -44733,7 +45270,7 @@ function readInputImages(paths) {
44733
45270
  return paths.map((p) => {
44734
45271
  let buf;
44735
45272
  try {
44736
- buf = readFileSync20(p);
45273
+ buf = readFileSync22(p);
44737
45274
  } catch (e) {
44738
45275
  throw new Error(`can't read --input image ${p} (${e.code || e.message}).`);
44739
45276
  }
@@ -44751,6 +45288,13 @@ ${IMAGE_MODELS_TABLE}
44751
45288
  Tier aliases (pass to --model instead of an id; each names a provider+model):
44752
45289
  ${IMAGE_TIER_ALIASES_DOC}
44753
45290
 
45291
+ Gipity GPU models (--model gipity-...; list them with \`gipity generate models\`):
45292
+ half the usual price for the same model, but queued: paid plans go first, and a
45293
+ job may wait a while. The CLI waits and shows the queue position, then saves the
45294
+ image. --no-wait queues it and prints the id instead (check it with
45295
+ \`gipity generate status <id>\`). GPU-only options: --aspect, --n, --ref, --avoid,
45296
+ --nsfw, --format. NSFW models need "Allow NSFW services" on your account.
45297
+
44754
45298
  Editing (--input): pass one or more source images and the prompt becomes an edit
44755
45299
  instruction applied to them - "make it night time", "add a hat", "remove the car
44756
45300
  in the background", or compose several inputs together. Editing routes to Gemini
@@ -44763,10 +45307,17 @@ Examples:
44763
45307
  gipity generate image "landscape sunset" --provider gemini --aspect-ratio 16:9 --image-size 2K
44764
45308
  gipity generate image "product photo" --provider openai --model gpt-image-2 --size 1536x1024 --quality high
44765
45309
  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) => {
45310
+ gipity generate image "a red canoe at sunrise" --model gipity-krea2-realistic --aspect landscape
45311
+ gipity generate image "same canoe, now at night" --model gipity-qwen21-consistent --ref gen_abc12345
45312
+ gipity generate image "a lighthouse" --model gipity-krea2-realistic --n 4 --no-wait
45313
+ `).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
45314
  try {
44768
45315
  const { config } = await resolveProjectContext();
44769
45316
  if (opts.output) ensureOutputDir(opts.output);
45317
+ if (isQueuedModel(opts.model) || opts.wait === false) {
45318
+ await generateQueued(config.projectGuid, prompt2, opts);
45319
+ return;
45320
+ }
44770
45321
  const inputImages = opts.input ? readInputImages(opts.input) : void 0;
44771
45322
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/image`, {
44772
45323
  prompt: prompt2,
@@ -44792,8 +45343,10 @@ Examples:
44792
45343
  console.log(muted(`Generated with ${result.provider}/${result.model}`));
44793
45344
  printMetrics([
44794
45345
  ...generationMetrics(result, elapsed),
45346
+ result.width && result.height ? { label: "pixels", value: `${result.width}x${result.height}` } : null,
44795
45347
  result.seed !== void 0 ? { label: "seed", value: `${result.seed} ${muted(`(pass --seed ${result.seed} to keep the next image coherent)`)}` } : null
44796
45348
  ]);
45349
+ if (result.note) console.log(muted(result.note));
44797
45350
  console.log(success(`Saved to ${savedPath}`));
44798
45351
  }
44799
45352
  } catch (err) {
@@ -44801,6 +45354,72 @@ Examples:
44801
45354
  process.exit(1);
44802
45355
  }
44803
45356
  });
45357
+ function numberedPath(base, i, n) {
45358
+ if (n <= 1) return base;
45359
+ const dot = base.lastIndexOf(".");
45360
+ const slash = Math.max(base.lastIndexOf("/"), base.lastIndexOf("\\"));
45361
+ return dot > slash ? `${base.slice(0, dot)}-${i + 1}${base.slice(dot)}` : `${base}-${i + 1}`;
45362
+ }
45363
+ async function generateQueued(projectGuid2, prompt2, opts) {
45364
+ if (opts.input) throw new Error("--input editing is not available on queued generations; drop --input or pick a cloud model.");
45365
+ if (!opts.model || !String(opts.model).startsWith("gipity-")) {
45366
+ throw new Error("--no-wait is for Gipity GPU models (--model gipity-...; see `gipity generate models`). Cloud models render right away: drop --no-wait.");
45367
+ }
45368
+ const started = Date.now();
45369
+ const submitted = await submitGenerations(projectGuid2, {
45370
+ model: opts.model,
45371
+ prompt: prompt2,
45372
+ avoid: opts.avoid,
45373
+ aspect: opts.aspect,
45374
+ size: opts.size,
45375
+ seed: Number.isFinite(opts.seed) ? opts.seed : void 0,
45376
+ n: Number.isFinite(opts.n) ? opts.n : void 0,
45377
+ nsfw: opts.nsfw ? true : void 0,
45378
+ format: opts.format,
45379
+ references: opts.ref
45380
+ });
45381
+ if (opts.wait === false) {
45382
+ if (opts.json) {
45383
+ console.log(JSON.stringify(submitted));
45384
+ return;
45385
+ }
45386
+ for (const g of submitted) console.log(`${g.id} ${muted(statusText(g))}`);
45387
+ console.log(muted(`Check with: gipity generate status ${submitted.map((g) => g.id).join(" ")}`));
45388
+ return;
45389
+ }
45390
+ if (!opts.json) console.log(muted(`Queued ${submitted.length === 1 ? submitted[0].id : submitted.map((g) => g.id).join(", ")} on ${opts.model}`));
45391
+ const done = await waitForGenerations(projectGuid2, submitted, { json: !!opts.json });
45392
+ const elapsed = (Date.now() - started) / 1e3;
45393
+ const saved = [];
45394
+ for (let i = 0; i < done.length; i++) {
45395
+ const g = done[i];
45396
+ const url = g.status === "succeeded" ? g.outputs?.full?.url : void 0;
45397
+ if (!url) {
45398
+ saved.push({ gen: g, path: null });
45399
+ continue;
45400
+ }
45401
+ const ext = (g.outputs?.full?.mime ?? "").includes("png") ? "png" : "jpg";
45402
+ const target = numberedPath(opts.output || `generated.${ext}`, i, done.length);
45403
+ saved.push({ gen: g, path: await downloadFile(url, target, !!opts.output) });
45404
+ }
45405
+ const failed = saved.filter((s) => !s.path);
45406
+ if (opts.json) {
45407
+ console.log(JSON.stringify(saved.map((s) => ({ ...s.gen, saved: s.path })).map((r) => ({ ...r, generation_seconds: Math.round(elapsed * 10) / 10 }))));
45408
+ } else {
45409
+ const credits = done.reduce((sum, g) => sum + (g.credits_charged ?? 0), 0);
45410
+ console.log(muted(`Generated with gipity/${opts.model}`));
45411
+ const first = saved.find((s) => s.path)?.gen;
45412
+ printMetrics([
45413
+ { label: "time", value: fmtSeconds(elapsed) },
45414
+ first?.width && first?.height ? { label: "pixels", value: `${first.width}x${first.height}` } : null,
45415
+ first?.seed != null ? { label: "seed", value: `${first.seed} ${muted(`(pass --seed ${first.seed} to keep the next image coherent)`)}` } : null,
45416
+ credits > 0 ? { label: "credits", value: credits.toLocaleString("en-US") } : null
45417
+ ]);
45418
+ for (const s of failed) console.error(error(`${s.gen.id} ${statusText(s.gen)}`));
45419
+ for (const s of saved) if (s.path) console.log(success(`Saved ${s.gen.id} to ${s.path}`));
45420
+ }
45421
+ if (failed.length === done.length) process.exit(1);
45422
+ }
44804
45423
  var videoCommand = new Command("video").description("Generate a short video (3-10 seconds) from a text prompt").addHelpText("after", `
44805
45424
  Models (default: gemini-omni-1.1-flash):
44806
45425
  ${VIDEO_MODELS_TABLE}
@@ -44854,7 +45473,7 @@ voice ids: gipity service call "tts/voices?provider=elevenlabs" --get
44854
45473
 
44855
45474
  Gemini voices: ${GEMINI_TTS_VOICES_DOC}
44856
45475
 
44857
- Multi-speaker (--speakers, Gemini only): JSON array like
45476
+ Multi-speaker (--speakers, Gemini only): JSON array of exactly 2 speakers like
44858
45477
  [{"name":"Joe","voice":"Kore"},{"name":"Jane","voice":"Puck"}]; format the
44859
45478
  text as "Name: dialogue" on each line.
44860
45479
 
@@ -44863,7 +45482,7 @@ Examples:
44863
45482
  gipity generate speech "\u3053\u3093\u306B\u3061\u306F\u4E16\u754C" --provider gemini --voice Kore --language ja-JP
44864
45483
  gipity generate speech "Bonjour le monde" --provider gemini --language fr-FR
44865
45484
  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) => {
45485
+ `).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
45486
  try {
44868
45487
  const { config } = await resolveProjectContext();
44869
45488
  if (opts.output) ensureOutputDir(opts.output);
@@ -44926,7 +45545,7 @@ Examples:
44926
45545
  console.error(error("Pass --lyrics or --lyrics-file, not both."));
44927
45546
  process.exit(1);
44928
45547
  }
44929
- const lyrics = opts.lyricsFile ? readFileSync20(opts.lyricsFile, "utf8").trim() : opts.lyrics;
45548
+ const lyrics = opts.lyricsFile ? readFileSync22(opts.lyricsFile, "utf8").trim() : opts.lyrics;
44930
45549
  const doGenerate = () => post(`/projects/${config.projectGuid}/generate/music`, {
44931
45550
  prompt: prompt2,
44932
45551
  duration_seconds: opts.duration,
@@ -44992,14 +45611,26 @@ Examples:
44992
45611
  process.exit(1);
44993
45612
  }
44994
45613
  });
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);
45614
+ 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
45615
 
44997
45616
  // src/commands/ask.ts
44998
45617
  init_api();
44999
45618
  init_config();
45000
- import { readFileSync as readFileSync21, fstatSync } from "fs";
45619
+ import { readFileSync as readFileSync23, fstatSync } from "fs";
45001
45620
  init_colors();
45002
45621
  var IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
45622
+ var MAX_WARM_WAIT_S = 90;
45623
+ async function askWithWarmRetry(call, onWarming) {
45624
+ try {
45625
+ return await call();
45626
+ } catch (e) {
45627
+ if (!(e instanceof ApiError) || e.code !== "MODEL_WARMING") throw e;
45628
+ const waitS = Math.min(Number(e.data?.retry_after_s ?? 45), MAX_WARM_WAIT_S);
45629
+ onWarming(waitS);
45630
+ await new Promise((r) => setTimeout(r, waitS * 1e3));
45631
+ return call();
45632
+ }
45633
+ }
45003
45634
  function stdinIsPiped() {
45004
45635
  try {
45005
45636
  const st2 = fstatSync(0);
@@ -45010,7 +45641,7 @@ function stdinIsPiped() {
45010
45641
  }
45011
45642
  function readTextFile(path5) {
45012
45643
  try {
45013
- return readFileSync21(path5 === "-" ? 0 : path5, "utf8");
45644
+ return readFileSync23(path5 === "-" ? 0 : path5, "utf8");
45014
45645
  } catch (e) {
45015
45646
  throw new Error(`can't read --file ${path5} (${e.code || e.message}).`);
45016
45647
  }
@@ -45020,7 +45651,7 @@ function readImage(path5) {
45020
45651
  if (!IMAGE_TYPES.has(mime)) throw new Error(`--image ${path5} is ${mime}; use a png, jpg, gif or webp.`);
45021
45652
  let buf;
45022
45653
  try {
45023
- buf = readFileSync21(path5);
45654
+ buf = readFileSync23(path5);
45024
45655
  } catch (e) {
45025
45656
  throw new Error(`can't read --image ${path5} (${e.code || e.message}).`);
45026
45657
  }
@@ -45033,7 +45664,7 @@ function buildAskPrompt(words, files) {
45033
45664
  ${f.content.trimEnd()}`);
45034
45665
  return parts.join("\n\n");
45035
45666
  }
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", `
45667
+ 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
45668
  Examples:
45038
45669
  gipity ask "what does HTTP 425 mean?"
45039
45670
  cat errors.log | gipity ask "group these by root cause" --file -
@@ -45062,7 +45693,8 @@ Examples:
45062
45693
  if (images.length) body.images = images;
45063
45694
  if (schema !== void 0) body.schema = schema;
45064
45695
  if (opts.maxTokens) body.max_tokens = opts.maxTokens;
45065
- const call = () => post(`/projects/${config.projectGuid}/generate/text`, body);
45696
+ const once = () => post(`/projects/${config.projectGuid}/generate/text`, body);
45697
+ const call = () => askWithWarmRetry(once, (s) => console.error(`The model is loading; retrying in ${s}s...`));
45066
45698
  const result = opts.json || !process.stderr.isTTY ? await call() : await withSpinner("Thinking...", call, { done: null });
45067
45699
  if (opts.json) {
45068
45700
  console.log(JSON.stringify(result));
@@ -45076,14 +45708,14 @@ Examples:
45076
45708
  init_api();
45077
45709
  init_config();
45078
45710
  init_colors();
45079
- import { existsSync as existsSync18, readFileSync as readFileSync22 } from "fs";
45711
+ import { existsSync as existsSync18, readFileSync as readFileSync24 } from "fs";
45080
45712
  import { join as join23 } from "path";
45081
45713
  function readInstalledKitReadme(name) {
45082
45714
  const root = getProjectRoot() ?? process.cwd();
45083
45715
  const kitDir = join23(root, "src", "packages", name);
45084
45716
  if (!existsSync18(join23(kitDir, "package.json"))) return null;
45085
45717
  const readme = join23(kitDir, "README.md");
45086
- return existsSync18(readme) ? readFileSync22(readme, "utf-8") : null;
45718
+ return existsSync18(readme) ? readFileSync24(readme, "utf-8") : null;
45087
45719
  }
45088
45720
  function slugify2(title) {
45089
45721
  return title.toLowerCase().replace(/[`*_]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -45147,17 +45779,23 @@ function filterContent(content, sections, opts) {
45147
45779
  if (opts.toc) return { text: tocText(sections) };
45148
45780
  let hits = [];
45149
45781
  let note;
45150
- if (opts.section) {
45151
- const want = slugify2(opts.section);
45152
- hits = sections.filter((s) => s.slug === want);
45153
- if (hits.length === 0) hits = sections.filter((s) => s.slug.includes(want));
45154
- if (hits.length === 0) {
45155
- const closest = closestSection(sections, want);
45156
- if (closest) {
45157
- hits = [closest];
45158
- note = `No section "${opts.section}"; showing the closest match "${closest.slug}" (all slugs: --toc).`;
45782
+ if (opts.section?.length) {
45783
+ const notes = [];
45784
+ for (const asked of opts.section) {
45785
+ const want = slugify2(asked);
45786
+ let found = sections.filter((s) => s.slug === want);
45787
+ if (found.length === 0) found = sections.filter((s) => s.slug.includes(want));
45788
+ if (found.length === 0) {
45789
+ const closest = closestSection(sections, want);
45790
+ if (closest) {
45791
+ found = [closest];
45792
+ notes.push(`No section "${asked}"; showing the closest match "${closest.slug}" (all slugs: --toc).`);
45793
+ }
45159
45794
  }
45795
+ if (found.length === 0) notes.push(`No section "${asked}" (all slugs: --toc).`);
45796
+ for (const f of found) if (!hits.includes(f)) hits.push(f);
45160
45797
  }
45798
+ if (notes.length) note = notes.join(" ");
45161
45799
  } else if (opts.grep) {
45162
45800
  let re2;
45163
45801
  try {
@@ -45192,7 +45830,7 @@ skillCommand.command("list").description("List skills").option("--json", "Output
45192
45830
  "Read with `gipity skill read <name> [<name>...]` (one turn, many docs; `--toc`, `--section <slug>` or `--grep <term>` for one part):"
45193
45831
  );
45194
45832
  }));
45195
- skillCommand.command("read <names...>").description("Read one or more skills (whole doc, or one part with --toc/--section/--grep)").option("--toc", "Print the doc outline (section slugs + line numbers) instead of the content").option("--section <slug>", "Print only this section (slug or heading text; subsections included). A guess that clearly matches one section by its words prints that section").option("--grep <term>", "Print only the sections matching this term (case-insensitive regex)").option("--json", "Output as JSON").action((names, opts) => run("Read", async () => {
45833
+ skillCommand.command("read <names...>").description("Read one or more skills (whole doc, or one part with --toc/--section/--grep)").option("--toc", "Print the doc outline (section slugs + line numbers) instead of the content").option("--section <slug>", "Print only this section (slug or heading text; subsections included). Repeat for several. A guess that clearly matches one section by its words prints that section", (v7, prev = []) => [...prev, v7]).option("--grep <term>", "Print only the sections matching this term (case-insensitive regex)").option("--json", "Output as JSON").action((names, opts) => run("Read", async () => {
45196
45834
  const listRes = await get("/skills");
45197
45835
  const jsonDocs = [];
45198
45836
  let failed = false;
@@ -45221,7 +45859,7 @@ skillCommand.command("read <names...>").description("Read one or more skills (wh
45221
45859
  const sections = parseSections(lines);
45222
45860
  const filtered = filterContent(content, sections, opts);
45223
45861
  if (filtered === null) {
45224
- const what = opts.section ? `section "${opts.section}"` : `match for "${opts.grep}"`;
45862
+ const what = opts.section?.length ? `section ${opts.section.map((x) => `"${x}"`).join(" / ")}` : `match for "${opts.grep}"`;
45225
45863
  console.error(error(`No ${what} in "${name}". Sections: ${sections.map((s) => s.slug).join(", ") || "(none)"}`));
45226
45864
  failed = true;
45227
45865
  continue;
@@ -45373,7 +46011,7 @@ var domainCommand = new Command("domain").description("Manage custom domains").a
45373
46011
 
45374
46012
  // src/commands/realtime.ts
45375
46013
  import { existsSync as existsSync19 } from "fs";
45376
- import { dirname as dirname14, resolve as resolve14 } from "path";
46014
+ import { dirname as dirname14, resolve as resolve15 } from "path";
45377
46015
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
45378
46016
  init_api();
45379
46017
  init_config();
@@ -45381,7 +46019,7 @@ init_colors();
45381
46019
  function hasDeployManifest() {
45382
46020
  const cfgPath = getConfigPath();
45383
46021
  if (!cfgPath) return false;
45384
- return existsSync19(resolve14(dirname14(cfgPath), "gipity.yaml"));
46022
+ return existsSync19(resolve15(dirname14(cfgPath), "gipity.yaml"));
45385
46023
  }
45386
46024
  var roomCommand = new Command("room").description("Manage realtime rooms").argument("[action]", "list | create | delete | info", "list").argument("[name]", "room name (for create | delete | info)").addOption(new Option("--type <type>", "Room type for create").choices(["state", "relay"]).default("state")).addOption(new Option("--auth <level>", "Auth level for create").choices(["public", "user"]).default("public")).option("--max-clients <n>", "max clients for create (1-200)").option("--seat-hold <seconds>", "create: how long a dropped client keeps its seat (0-300, default 30)").option("--host-hold <seconds>", "create: how long the host role waits for a dropped or reloading host (0-600, default 60)").option("--host-handoff", "create: move the host role to another player when the host is gone").option("--host-grace <seconds>", "create: with handoff, how long the host may be unreachable before the role moves (1-60, default 5)").option("--server-channels <names>", "create: comma-separated channels only the app's functions may publish on (realtime.publish)").option("--json", "Output as JSON").action((action, name, opts) => run("Realtime room", async () => {
45387
46025
  const config = requireConfig2();
@@ -45471,7 +46109,7 @@ var roomCommand = new Command("room").description("Manage realtime rooms").argum
45471
46109
  }));
45472
46110
  function benchModulePath() {
45473
46111
  const here = dirname14(fileURLToPath3(import.meta.url));
45474
- for (const candidate of [resolve14(here, "realtime-bench.js"), resolve14(here, "..", "realtime-bench.js")]) {
46112
+ for (const candidate of [resolve15(here, "realtime-bench.js"), resolve15(here, "..", "realtime-bench.js")]) {
45475
46113
  if (existsSync19(candidate)) return pathToFileURL(candidate).href;
45476
46114
  }
45477
46115
  throw new Error("realtime-bench.js is missing from this CLI build; reinstall the gipity CLI");
@@ -45633,7 +46271,7 @@ async function pollTestStatus(projectGuid2, runGuid, opts) {
45633
46271
  }
45634
46272
  }
45635
46273
  }
45636
- await new Promise((resolve19) => setTimeout(resolve19, getPollInterval()));
46274
+ await new Promise((resolve20) => setTimeout(resolve20, getPollInterval()));
45637
46275
  }
45638
46276
  }
45639
46277
  var testCommand = new Command("test").description("Run tests").argument("[path]", 'Test path filter (e.g. "api", "e2e/portal")').option("--filter <path>", "Alias for the positional test path filter").option("--timeout <ms>", "Per-test timeout in ms", "30000").option("--retry <n>", "Retry failed tests N times", "0").option("--no-sync", "Skip sync-up before tests").option("--json", "Output as JSON").action((pathFilter, opts) => run("Test", async () => {
@@ -45861,12 +46499,12 @@ var locationCommand = new Command("location").description("Show location").argum
45861
46499
  }));
45862
46500
 
45863
46501
  // src/commands/doctor.ts
45864
- import { existsSync as existsSync21, readFileSync as readFileSync24, statSync as statSync9 } from "fs";
45865
- import { join as join25, resolve as resolve15 } from "path";
46502
+ import { existsSync as existsSync21, readFileSync as readFileSync26, statSync as statSync9 } from "fs";
46503
+ import { join as join25, resolve as resolve16 } from "path";
45866
46504
  import { homedir as homedir17 } from "os";
45867
46505
 
45868
46506
  // src/updater/state.ts
45869
- import { readFileSync as readFileSync23, writeFileSync as writeFileSync16, mkdirSync as mkdirSync16, existsSync as existsSync20 } from "fs";
46507
+ import { readFileSync as readFileSync25, writeFileSync as writeFileSync17, mkdirSync as mkdirSync16, existsSync as existsSync20 } from "fs";
45870
46508
  import { join as join24 } from "path";
45871
46509
  import { homedir as homedir16 } from "os";
45872
46510
  var GIPITY_DIR = join24(homedir16(), ".gipity");
@@ -45891,19 +46529,19 @@ function ensureDir() {
45891
46529
  function readState() {
45892
46530
  if (!existsSync20(STATE_FILE)) return { ...DEFAULT_STATE };
45893
46531
  try {
45894
- return { ...DEFAULT_STATE, ...JSON.parse(readFileSync23(STATE_FILE, "utf-8")) };
46532
+ return { ...DEFAULT_STATE, ...JSON.parse(readFileSync25(STATE_FILE, "utf-8")) };
45895
46533
  } catch {
45896
46534
  return { ...DEFAULT_STATE };
45897
46535
  }
45898
46536
  }
45899
46537
  function writeState(state) {
45900
46538
  ensureDir();
45901
- writeFileSync16(STATE_FILE, JSON.stringify(state, null, 2));
46539
+ writeFileSync17(STATE_FILE, JSON.stringify(state, null, 2));
45902
46540
  }
45903
46541
  function readSettings() {
45904
46542
  if (!existsSync20(SETTINGS_FILE)) return { ...DEFAULT_SETTINGS };
45905
46543
  try {
45906
- return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync23(SETTINGS_FILE, "utf-8")) };
46544
+ return { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync25(SETTINGS_FILE, "utf-8")) };
45907
46545
  } catch {
45908
46546
  return { ...DEFAULT_SETTINGS };
45909
46547
  }
@@ -45940,7 +46578,7 @@ function localVersion() {
45940
46578
  const pkgPath = join25(LOCAL_PKG_DIR, "package.json");
45941
46579
  if (!existsSync21(pkgPath)) return null;
45942
46580
  try {
45943
- return JSON.parse(readFileSync24(pkgPath, "utf-8")).version ?? null;
46581
+ return JSON.parse(readFileSync26(pkgPath, "utf-8")).version ?? null;
45944
46582
  } catch {
45945
46583
  return null;
45946
46584
  }
@@ -45948,7 +46586,7 @@ function localVersion() {
45948
46586
  function shimVersion() {
45949
46587
  try {
45950
46588
  const url = new URL("../../package.json", import.meta.url);
45951
- return JSON.parse(readFileSync24(url, "utf-8")).version;
46589
+ return JSON.parse(readFileSync26(url, "utf-8")).version;
45952
46590
  } catch {
45953
46591
  return "unknown";
45954
46592
  }
@@ -46038,7 +46676,7 @@ var doctorCommand = new Command("doctor").description("Check install + environme
46038
46676
  if (env.claude.installed && !env.claude.authenticated) {
46039
46677
  console.log(`${muted(" ")} ${warning("Claude Code is not logged in. Run `claude auth login` and sign in.")}`);
46040
46678
  }
46041
- if (existsSync21(resolve15(process.cwd(), ".codex", "hooks.json"))) {
46679
+ if (existsSync21(resolve16(process.cwd(), ".codex", "hooks.json"))) {
46042
46680
  console.log(`${muted("codex hooks ")} ${warning("written")} - session capture needs a one-time approval: run /hooks inside Codex in this project`);
46043
46681
  }
46044
46682
  const buildReady = env.node.ok && env.gipity.logged_in;
@@ -46068,7 +46706,7 @@ var doctorCommand = new Command("doctor").description("Check install + environme
46068
46706
  import { appendFileSync } from "fs";
46069
46707
 
46070
46708
  // 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";
46709
+ import { existsSync as existsSync22, mkdirSync as mkdirSync17, rmSync as rmSync2, statSync as statSync10, unlinkSync as unlinkSync6, writeFileSync as writeFileSync18 } from "fs";
46072
46710
  import { dirname as dirname15, join as join26 } from "path";
46073
46711
  init_platform();
46074
46712
  var UPDATE_LOCK = join26(GIPITY_DIR, "update.lock");
@@ -46094,18 +46732,18 @@ function resetLocalTree(dir = LOCAL_DIR) {
46094
46732
  mkdirSync17(dir, { recursive: true });
46095
46733
  rmSync2(join26(dir, "node_modules"), { recursive: true, force: true });
46096
46734
  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));
46735
+ writeFileSync18(join26(dir, "package.json"), JSON.stringify({ name: "gipity-local", private: true, version: "0.0.0" }, null, 2));
46098
46736
  }
46099
46737
  function acquireUpdateLock(lockPath2 = UPDATE_LOCK) {
46100
46738
  mkdirSync17(dirname15(lockPath2), { recursive: true });
46101
46739
  try {
46102
- writeFileSync17(lockPath2, String(process.pid), { flag: "wx" });
46740
+ writeFileSync18(lockPath2, String(process.pid), { flag: "wx" });
46103
46741
  return true;
46104
46742
  } catch {
46105
46743
  try {
46106
46744
  if (Date.now() - statSync10(lockPath2).mtimeMs > LOCK_STALE_MS2) {
46107
46745
  unlinkSync6(lockPath2);
46108
- writeFileSync17(lockPath2, String(process.pid), { flag: "wx" });
46746
+ writeFileSync18(lockPath2, String(process.pid), { flag: "wx" });
46109
46747
  return true;
46110
46748
  }
46111
46749
  } catch {
@@ -46265,13 +46903,13 @@ var updateCommand = new Command("update").description("Update the CLI").option("
46265
46903
  init_api();
46266
46904
  init_utils();
46267
46905
  init_colors();
46268
- import { existsSync as existsSync25, readFileSync as readFileSync27, unlinkSync as unlinkSync9 } from "fs";
46906
+ import { existsSync as existsSync25, readFileSync as readFileSync29, unlinkSync as unlinkSync9 } from "fs";
46269
46907
  import { spawn as spawn2 } from "child_process";
46270
46908
 
46271
46909
  // src/relay/daemon.ts
46272
46910
  init_platform();
46273
46911
  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";
46912
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync19, existsSync as existsSync24, readFileSync as readFileSync28, writeFileSync as writeFileSync19, chmodSync as chmodSync4, closeSync as closeSync4, openSync as openSync4, unlinkSync as unlinkSync8 } from "fs";
46275
46913
  import { stat, readFile } from "fs/promises";
46276
46914
  import { createInterface as createInterface2 } from "readline";
46277
46915
  import { homedir as homedir19, hostname as hostname6, platform as osPlatform3, loadavg as loadavg2, freemem as freemem2, totalmem as totalmem2, cpus as cpus2 } from "os";
@@ -47042,13 +47680,13 @@ function parseVersion(out) {
47042
47680
  return m ? m[0] : void 0;
47043
47681
  }
47044
47682
  function runProbe(cmd, args) {
47045
- return new Promise((resolve19) => {
47683
+ return new Promise((resolve20) => {
47046
47684
  let out = "";
47047
47685
  let settled = false;
47048
47686
  const done = (s) => {
47049
47687
  if (!settled) {
47050
47688
  settled = true;
47051
- resolve19(s);
47689
+ resolve20(s);
47052
47690
  }
47053
47691
  };
47054
47692
  let child;
@@ -47187,13 +47825,13 @@ function agentUpdateInProgress() {
47187
47825
  return inProgress;
47188
47826
  }
47189
47827
  function execCapture(argv2, timeoutMs, signal) {
47190
- return new Promise((resolve19) => {
47828
+ return new Promise((resolve20) => {
47191
47829
  let output = "";
47192
47830
  let settled = false;
47193
47831
  const done = (ok) => {
47194
47832
  if (!settled) {
47195
47833
  settled = true;
47196
- resolve19({ ok, output });
47834
+ resolve20({ ok, output });
47197
47835
  }
47198
47836
  };
47199
47837
  let child;
@@ -47394,8 +48032,8 @@ var SessionPool = class {
47394
48032
  const done = new Promise((r) => {
47395
48033
  markDone = r;
47396
48034
  });
47397
- return new Promise((resolve19, reject) => {
47398
- const turn = { onMessage: p.onMessage, resolve: resolve19, reject, interruptRequested: false, wasHot, done, markDone };
48035
+ return new Promise((resolve20, reject) => {
48036
+ const turn = { onMessage: p.onMessage, resolve: resolve20, reject, interruptRequested: false, wasHot, done, markDone };
47399
48037
  session.current = turn;
47400
48038
  session.state = "running";
47401
48039
  session.lastActivityAt = Date.now();
@@ -47850,10 +48488,10 @@ async function heartbeatLoop(ctx) {
47850
48488
  }
47851
48489
  await Promise.race([
47852
48490
  sleep4(HEARTBEAT_INTERVAL_MS, ctx.abort.signal),
47853
- new Promise((resolve19) => {
48491
+ new Promise((resolve20) => {
47854
48492
  heartbeatPoke = () => {
47855
48493
  heartbeatPoke = null;
47856
- resolve19();
48494
+ resolve20();
47857
48495
  };
47858
48496
  })
47859
48497
  ]);
@@ -47897,9 +48535,9 @@ async function dispatchLoop(ctx, opts) {
47897
48535
  while (inflight.size >= MAX_CONCURRENT_DISPATCHES && !ctx.abort.signal.aborted) {
47898
48536
  await Promise.race([
47899
48537
  ...inflight,
47900
- new Promise((resolve19) => {
47901
- if (ctx.abort.signal.aborted) return resolve19();
47902
- ctx.abort.signal.addEventListener("abort", () => resolve19(), { once: true });
48538
+ new Promise((resolve20) => {
48539
+ if (ctx.abort.signal.aborted) return resolve20();
48540
+ ctx.abort.signal.addEventListener("abort", () => resolve20(), { once: true });
47903
48541
  })
47904
48542
  ]);
47905
48543
  }
@@ -48598,7 +49236,7 @@ async function resolveCwdForProject(d) {
48598
49236
  const configPath = join29(path5, ".gipity.json");
48599
49237
  if (existsSync24(configPath)) {
48600
49238
  try {
48601
- const cfg = JSON.parse(readFileSync26(configPath, "utf-8"));
49239
+ const cfg = JSON.parse(readFileSync28(configPath, "utf-8"));
48602
49240
  if (cfg.projectGuid === d.project_guid) return { cwd: path5, bootstrapped: false };
48603
49241
  log2("warn", "project dir exists but guid mismatch - using it anyway", {
48604
49242
  path: path5,
@@ -48612,7 +49250,7 @@ async function resolveCwdForProject(d) {
48612
49250
  log2("info", "bootstrapping new project dir", { slug: d.project_slug, path: path5 });
48613
49251
  mkdirSync19(path5, { recursive: true });
48614
49252
  const apiBase2 = getApiBaseOverride() || DEFAULT_API_BASE;
48615
- writeFileSync18(configPath, JSON.stringify({
49253
+ writeFileSync19(configPath, JSON.stringify({
48616
49254
  projectGuid: d.project_guid,
48617
49255
  projectSlug: d.project_slug,
48618
49256
  accountSlug: d.account_slug,
@@ -48688,7 +49326,7 @@ async function killRunningForConv(convGuid) {
48688
49326
  }
48689
49327
  }
48690
49328
  const graceTimers = [];
48691
- const escalate = new Promise((resolve19) => {
49329
+ const escalate = new Promise((resolve20) => {
48692
49330
  const t = setTimeout(() => {
48693
49331
  for (const e of matches) {
48694
49332
  log2("warn", "previous dispatch ignored SIGTERM - escalating to SIGKILL", { conv: convGuid });
@@ -48697,7 +49335,7 @@ async function killRunningForConv(convGuid) {
48697
49335
  } catch {
48698
49336
  }
48699
49337
  }
48700
- resolve19();
49338
+ resolve20();
48701
49339
  }, KILL_GRACE_MS);
48702
49340
  graceTimers.push(t);
48703
49341
  });
@@ -48708,7 +49346,7 @@ async function killRunningForConv(convGuid) {
48708
49346
  }
48709
49347
  async function spawnSync2(cwd, timeoutMs, onSpawn) {
48710
49348
  const cmd = process.env.GIPITY_RELAY_CLAUDE_CMD || resolveCommand("gipity");
48711
- return new Promise((resolve19, reject) => {
49349
+ return new Promise((resolve20, reject) => {
48712
49350
  const child = spawnCommand(cmd, ["sync", "--json"], {
48713
49351
  cwd,
48714
49352
  env: childEnv(),
@@ -48748,7 +49386,7 @@ async function spawnSync2(cwd, timeoutMs, onSpawn) {
48748
49386
  child.on("exit", (code) => finish(() => {
48749
49387
  if (code === 0) {
48750
49388
  log2("info", "sync done", { cwd, stdoutLen });
48751
- resolve19();
49389
+ resolve20();
48752
49390
  } else {
48753
49391
  reject(new Error(`gipity sync exited ${code}${stderrBuf ? `: ${stderrBuf.trim().slice(0, 300)}` : ""}`));
48754
49392
  }
@@ -48760,7 +49398,7 @@ async function spawnGipityClaude(args, cwd, d, queue, meta) {
48760
49398
  const cmd = process.env.GIPITY_RELAY_CLAUDE_CMD || resolveCommand("gipity");
48761
49399
  const fullArgs = streamJson ? [...args, "--output-format", "stream-json", "--verbose", "--include-partial-messages"] : [...args];
48762
49400
  const env = streamJson ? childEnv({ GIPITY_CONVERSATION_GUID: d.conversation_guid, GIPITY_CAPTURE: "off" }) : childEnv({ GIPITY_CONVERSATION_GUID: d.conversation_guid });
48763
- return new Promise((resolve19, reject) => {
49401
+ return new Promise((resolve20, reject) => {
48764
49402
  const child = spawnCommand(cmd, fullArgs, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
48765
49403
  let resolveExited = () => {
48766
49404
  };
@@ -48947,7 +49585,7 @@ async function spawnGipityClaude(args, cwd, d, queue, meta) {
48947
49585
  void postProgress(d.conversation_guid, buildProgressPayload(false));
48948
49586
  if (ownQueue) await q.close();
48949
49587
  cleanup();
48950
- resolve19({
49588
+ resolve20({
48951
49589
  exitCode: code ?? 1,
48952
49590
  killed,
48953
49591
  runtimeLimit,
@@ -48962,10 +49600,10 @@ async function runDispatchSync(d, cwd) {
48962
49600
  let killed = false;
48963
49601
  try {
48964
49602
  await spawnSync2(cwd, PROJECT_SYNC_TIMEOUT_MS, (child) => {
48965
- const exited = new Promise((resolve19) => {
49603
+ const exited = new Promise((resolve20) => {
48966
49604
  child.once("exit", (_code, signal) => {
48967
49605
  if (signal === "SIGTERM") killed = true;
48968
- resolve19();
49606
+ resolve20();
48969
49607
  });
48970
49608
  });
48971
49609
  running.set(d.short_guid, { child, convGuid: d.conversation_guid, exited });
@@ -48996,18 +49634,18 @@ function killDispatch(shortGuid) {
48996
49634
  return false;
48997
49635
  }
48998
49636
  function sleep4(ms2, signal) {
48999
- return new Promise((resolve19) => {
49000
- if (signal?.aborted) return resolve19();
49637
+ return new Promise((resolve20) => {
49638
+ if (signal?.aborted) return resolve20();
49001
49639
  let onAbort = null;
49002
49640
  const t = setTimeout(() => {
49003
49641
  if (onAbort && signal) signal.removeEventListener("abort", onAbort);
49004
- resolve19();
49642
+ resolve20();
49005
49643
  }, ms2);
49006
49644
  if (signal) {
49007
49645
  onAbort = () => {
49008
49646
  clearTimeout(t);
49009
49647
  signal.removeEventListener("abort", onAbort);
49010
- resolve19();
49648
+ resolve20();
49011
49649
  };
49012
49650
  signal.addEventListener("abort", onAbort, { once: true });
49013
49651
  }
@@ -49094,7 +49732,7 @@ function registerInstallCommands(relayCommand2) {
49094
49732
  // src/commands/relay.ts
49095
49733
  var relayCommand = new Command("relay").description("Pair with the web CLI");
49096
49734
  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) => {
49735
+ const fail3 = (code, message) => {
49098
49736
  if (opts.json) {
49099
49737
  console.log(JSON.stringify({ ok: false, code, error: message }));
49100
49738
  } else {
@@ -49108,9 +49746,9 @@ relayCommand.command("setup").description("Pair this machine and start the relay
49108
49746
  device = await pairDevice({ name: opts.name, force: opts.force });
49109
49747
  } catch (err) {
49110
49748
  if (err instanceof ApiError && err.statusCode === 401) {
49111
- return fail("not_authenticated", "Not logged in - cannot pair this machine.");
49749
+ return fail3("not_authenticated", "Not logged in - cannot pair this machine.");
49112
49750
  }
49113
- return fail("pair_failed", `Could not pair: ${err?.message || err}`);
49751
+ return fail3("pair_failed", `Could not pair: ${err?.message || err}`);
49114
49752
  }
49115
49753
  let daemonStarted = false;
49116
49754
  if (opts.start) {
@@ -49127,7 +49765,7 @@ relayCommand.command("setup").description("Pair this machine and start the relay
49127
49765
  if (err instanceof UnsupportedPlatformError) {
49128
49766
  autostart.supported = false;
49129
49767
  } else {
49130
- return fail("autostart_failed", `Autostart install failed: ${err?.message || err}`);
49768
+ return fail3("autostart_failed", `Autostart install failed: ${err?.message || err}`);
49131
49769
  }
49132
49770
  }
49133
49771
  }
@@ -49181,7 +49819,7 @@ relayCommand.command("stop").description("Stop the background service").option("
49181
49819
  console.log(muted("Background service isn't running."));
49182
49820
  return;
49183
49821
  }
49184
- const pid = parseInt(readFileSync27(pidPath, "utf-8").trim(), 10);
49822
+ const pid = parseInt(readFileSync29(pidPath, "utf-8").trim(), 10);
49185
49823
  if (!pid || isNaN(pid)) {
49186
49824
  console.error(error("PID file is empty or malformed."));
49187
49825
  process.exit(1);
@@ -49330,7 +49968,7 @@ relayCommand.command("revoke").description("Revoke and forget this device").acti
49330
49968
  }
49331
49969
  const pidPath = getDaemonPidPath();
49332
49970
  if (existsSync25(pidPath)) {
49333
- const pid = parseInt(readFileSync27(pidPath, "utf-8").trim(), 10);
49971
+ const pid = parseInt(readFileSync29(pidPath, "utf-8").trim(), 10);
49334
49972
  if (pid && !isNaN(pid)) {
49335
49973
  try {
49336
49974
  process.kill(pid, "SIGTERM");
@@ -49349,7 +49987,7 @@ relayCommand.command("log").description("Tail the service log").option("-n, --li
49349
49987
  }
49350
49988
  const lines = parseInt(opts.lines, 10) || 100;
49351
49989
  try {
49352
- const all = readFileSync27(path5, "utf-8").split("\n");
49990
+ const all = readFileSync29(path5, "utf-8").split("\n");
49353
49991
  const tail2 = all.slice(-lines - 1).join("\n");
49354
49992
  process.stdout.write(tail2);
49355
49993
  } catch (err) {
@@ -49525,9 +50163,9 @@ init_api();
49525
50163
  init_auth();
49526
50164
  init_utils();
49527
50165
  init_colors();
49528
- import { existsSync as existsSync26, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync28, writeFileSync as writeFileSync19 } from "fs";
50166
+ import { existsSync as existsSync26, rmSync as rmSync4, unlinkSync as unlinkSync10, readFileSync as readFileSync30, writeFileSync as writeFileSync20 } from "fs";
49529
50167
  import { homedir as homedir20, platform as osPlatform4 } from "os";
49530
- import { join as join30, resolve as resolve17 } from "path";
50168
+ import { join as join30, resolve as resolve18 } from "path";
49531
50169
  init_agents();
49532
50170
  function removeInstallerPathLines() {
49533
50171
  if (osPlatform4() === "win32") return [];
@@ -49538,7 +50176,7 @@ function removeInstallerPathLines() {
49538
50176
  if (!existsSync26(rc2)) continue;
49539
50177
  let text;
49540
50178
  try {
49541
- text = readFileSync28(rc2, "utf-8");
50179
+ text = readFileSync30(rc2, "utf-8");
49542
50180
  } catch {
49543
50181
  continue;
49544
50182
  }
@@ -49548,7 +50186,7 @@ function removeInstallerPathLines() {
49548
50186
  );
49549
50187
  if (kept.length === lines.length) continue;
49550
50188
  try {
49551
- writeFileSync19(rc2, kept.join("\n"));
50189
+ writeFileSync20(rc2, kept.join("\n"));
49552
50190
  touched.push(rc2);
49553
50191
  } catch {
49554
50192
  }
@@ -49560,7 +50198,7 @@ function tildify2(p) {
49560
50198
  return p === home || p.startsWith(home + "/") ? "~" + p.slice(home.length) : p;
49561
50199
  }
49562
50200
  function resolveCliPath2() {
49563
- return resolve17(process.argv[1] ?? "gipity");
50201
+ return resolve18(process.argv[1] ?? "gipity");
49564
50202
  }
49565
50203
  async function stopDaemon() {
49566
50204
  if (!isDaemonRunning()) return;
@@ -49844,7 +50482,7 @@ gmailCommand.command("reply").description("Reply to a Gmail thread. Get thread-i
49844
50482
  }));
49845
50483
 
49846
50484
  // src/commands/text.ts
49847
- import { readFileSync as readFileSync29 } from "fs";
50485
+ import { readFileSync as readFileSync31 } from "fs";
49848
50486
  init_colors();
49849
50487
 
49850
50488
  // src/helpers/text-analysis.ts
@@ -49999,10 +50637,10 @@ function areAnagrams(a, b7) {
49999
50637
 
50000
50638
  // src/commands/text.ts
50001
50639
  function resolveInput(args, opts) {
50002
- if (opts.file) return readFileSync29(opts.file, "utf-8");
50640
+ if (opts.file) return readFileSync31(opts.file, "utf-8");
50003
50641
  if (args.length) return args.join(" ");
50004
50642
  try {
50005
- return readFileSync29(0, "utf-8");
50643
+ return readFileSync31(0, "utf-8");
50006
50644
  } catch {
50007
50645
  return "";
50008
50646
  }
@@ -50298,11 +50936,11 @@ function installOutputTrace(label2) {
50298
50936
  installOutputTrace("index");
50299
50937
  var __dirname = dirname16(fileURLToPath4(import.meta.url));
50300
50938
  installNetworking();
50301
- var pkg = JSON.parse(readFileSync30(resolve18(__dirname, "../package.json"), "utf-8"));
50939
+ var pkg = JSON.parse(readFileSync32(resolve19(__dirname, "../package.json"), "utf-8"));
50302
50940
  function versionLabel() {
50303
50941
  const base = `v${pkg.version}`;
50304
50942
  try {
50305
- const info2 = JSON.parse(readFileSync30(resolve18(__dirname, "build-info.json"), "utf-8"));
50943
+ const info2 = JSON.parse(readFileSync32(resolve19(__dirname, "build-info.json"), "utf-8"));
50306
50944
  if (info2?.sha) return `${base} (dev ${info2.sha}${info2.dirty ? ", modified" : ""})`;
50307
50945
  } catch {
50308
50946
  }
@@ -50343,7 +50981,7 @@ var backendGroup = [dbCommand, fnCommand, secretsCommand, keyCommand, logsComman
50343
50981
  var servicesGroup = [serviceCommand, generateCommand, askCommand, notifyCommand, paymentsCommand, realtimeCommand, recordsCommand, rbacCommand, auditCommand, domainCommand, tokenCommand];
50344
50982
  var filesGroup = [syncCommand, fileCommand, pushCommand, uploadCommand, storageCommand];
50345
50983
  var utilitiesGroup = [sandboxCommand, emailCommand, gmailCommand, locationCommand, textCommand, bugCommand];
50346
- var connectGroup = [loginCommand, logoutCommand, buildCommand, githubCommand, creditsCommand, doctorCommand, updateCommand, uninstallCommand];
50984
+ var connectGroup = [loginCommand, logoutCommand, buildCommand, githubCommand, creditsCommand, accountCommand, doctorCommand, updateCommand, uninstallCommand];
50347
50985
  var HELP_SECTIONS = [
50348
50986
  { title: "Start here", cmds: startGroup },
50349
50987
  { title: "App build & ship", cmds: buildGroup },
@@ -50365,8 +51003,10 @@ var SKILL_DOCS = {
50365
51003
  fn: "app-development",
50366
51004
  notify: "app-notify",
50367
51005
  payments: "app-payments",
51006
+ account: "plans",
50368
51007
  records: "app-records",
50369
51008
  key: "app-auth",
51009
+ secrets: "app-function-services",
50370
51010
  realtime: "app-realtime",
50371
51011
  job: "jobs",
50372
51012
  workflow: "workflow",