gipity 1.1.37 → 1.1.39

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.
@@ -13,7 +13,7 @@ export const emailCommand = new Command('email')
13
13
  emailCommand
14
14
  .command('test')
15
15
  .description("Send a test email through your app's email() path (owner-billed)")
16
- .argument('<to>', 'Recipient address')
16
+ .argument('<to>', "Recipient address, or 'owner' for the app owner's own account email")
17
17
  .option('--subject <text>', 'Subject', 'Test email from Gipity')
18
18
  .option('--text <text>', 'Body text', 'This is a test email sent through your app\'s email() service. ✉️')
19
19
  .option('--reply-to <email>', 'Reply-To address')
@@ -5,7 +5,9 @@ import { bold, muted, success, warning } from '../colors.js';
5
5
  import { run, printList } from '../helpers/index.js';
6
6
  /**
7
7
  * Project API keys - the revocable secret a script, cron, or agent sends as
8
- * `X-Api-Key` to write to YOUR app without a browser login.
8
+ * `X-Api-Key` (or `Authorization: Bearer`) to write to YOUR app without a
9
+ * browser login. Optional scopes limit a key to named functions, tables,
10
+ * files access and source IPs.
9
11
  *
10
12
  * These are per-project and app-facing; `gipity token` mints account-level
11
13
  * agent tokens (gip_at_*) that drive the CLI itself. Without this command the
@@ -20,6 +22,19 @@ Give a script, cron, or agent write access to your app without a login:
20
22
  gipity key create "laptop importer" --role editor
21
23
  # the script sends: X-Api-Key: <the key printed once above>
22
24
 
25
+ The key also works as Authorization: Bearer <key>, and only on this app
26
+ (and environment: add --env dev for a dev key).
27
+
28
+ Scope a key that lives on a device or anywhere you don't fully control, so a
29
+ leaked key can only do its one job:
30
+
31
+ gipity key create "front door" --role editor \\
32
+ --functions send-command,heartbeat --tables commands:write,logs:read \\
33
+ --files read --ip 203.0.113.7/32
34
+
35
+ Any of --functions / --tables / --files limits the key to exactly what is
36
+ listed (nothing else on the app API); --ip alone only pins the source address.
37
+
23
38
  Inside a function the caller shows up as ctx.auth.via === 'api_key' with
24
39
  ctx.auth.apiKeyName set to the key's name - stamp that on rows to tell
25
40
  script-written entries from hand-entered ones. Never build your own key table.
@@ -27,6 +42,55 @@ script-written entries from hand-entered ones. Never build your own key table.
27
42
  Account-level tokens that run the CLI headlessly are a different thing: see
28
43
  gipity token --help.`);
29
44
  const fmtDate = (d) => (d ? new Date(d).toLocaleDateString() : 'never');
45
+ const splitList = (v) => v.split(',').map(x => x.trim()).filter(Boolean);
46
+ /** Build the scopes body from the create flags; null when none were given.
47
+ * The server validates names, access levels and addresses. */
48
+ export function scopesFromFlags(opts) {
49
+ const scopes = {};
50
+ if (opts.functions !== undefined) {
51
+ const fns = splitList(opts.functions);
52
+ if (!fns.length)
53
+ throw new Error('--functions needs at least one function name');
54
+ scopes.functions = fns;
55
+ }
56
+ if (opts.tables !== undefined) {
57
+ const entries = splitList(opts.tables);
58
+ if (!entries.length)
59
+ throw new Error('--tables needs at least one table:read or table:write');
60
+ scopes.tables = {};
61
+ for (const entry of entries) {
62
+ const [table, access, ...rest] = entry.split(':');
63
+ if (!table || (access !== 'read' && access !== 'write') || rest.length) {
64
+ throw new Error(`--tables entry "${entry}" must be table:read or table:write`);
65
+ }
66
+ scopes.tables[table] = access;
67
+ }
68
+ }
69
+ if (opts.files !== undefined)
70
+ scopes.files = opts.files;
71
+ if (opts.ip !== undefined) {
72
+ const ips = splitList(opts.ip);
73
+ if (!ips.length)
74
+ throw new Error('--ip needs at least one address or CIDR range');
75
+ scopes.ip = ips;
76
+ }
77
+ return Object.keys(scopes).length ? scopes : null;
78
+ }
79
+ /** One-line scope summary for listings. */
80
+ export function describeScopes(scopes) {
81
+ if (!scopes)
82
+ return 'all access';
83
+ const parts = [];
84
+ if (scopes.functions)
85
+ parts.push(`fn: ${scopes.functions.join(',')}`);
86
+ if (scopes.tables)
87
+ parts.push(`tables: ${Object.entries(scopes.tables).map(([t, a]) => `${t}:${a}`).join(',')}`);
88
+ if (scopes.files)
89
+ parts.push(`files: ${scopes.files}`);
90
+ if (scopes.ip)
91
+ parts.push(`ip: ${scopes.ip.join(',')}`);
92
+ return parts.join(' ');
93
+ }
30
94
  const projectOpt = ['--project <guid-or-slug>', 'Target a specific project instead of cwd / Home'];
31
95
  async function projectGuid(opts) {
32
96
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
@@ -37,10 +101,17 @@ keyCommand
37
101
  .description('Mint a project API key (shown once). Give it a name you will recognize later')
38
102
  .addOption(new Option('--role <role>', 'Access role for the key').choices(['viewer', 'editor', 'owner']).default('viewer'))
39
103
  .option('--expires-days <n>', 'Days until the key expires (default: never)')
104
+ .option('--functions <names>', 'Scope: only these functions (comma-separated)')
105
+ .option('--tables <list>', 'Scope: only these Records tables, e.g. commands:write,logs:read')
106
+ .addOption(new Option('--files <access>', 'Scope: app files access').choices(['read', 'write']))
107
+ .option('--ip <list>', 'Scope: only from these IPs / CIDR ranges (comma-separated)')
40
108
  .option(...projectOpt)
41
109
  .option('--json', 'Output as JSON')
42
110
  .action((name, opts) => run('Create', async () => {
43
111
  const body = { name, role: opts.role };
112
+ const scopes = scopesFromFlags(opts);
113
+ if (scopes)
114
+ body.scopes = scopes;
44
115
  if (opts.expiresDays !== undefined) {
45
116
  const days = parseInt(opts.expiresDays, 10);
46
117
  if (!Number.isFinite(days) || days <= 0)
@@ -55,11 +126,13 @@ keyCommand
55
126
  }
56
127
  const expNote = k.expires_at ? ` (expires ${fmtDate(k.expires_at)})` : ' (never expires)';
57
128
  console.log(success(`Created API key ${bold(k.short_guid)} "${k.name}" as ${k.role}${muted(expNote)}.`));
129
+ if (k.scopes)
130
+ console.log(muted(`Scopes: ${describeScopes(k.scopes)}`));
58
131
  console.log('');
59
132
  console.log(k.key);
60
133
  console.log('');
61
134
  console.log(muted('Send it from your script on every request:'));
62
- console.log(muted(` curl -H "X-Api-Key: ${k.key}" ...`));
135
+ console.log(muted(` curl -H "X-Api-Key: ${k.key}" ... (or Authorization: Bearer <key>)`));
63
136
  console.log(muted(`Revoke it any time: gipity key revoke ${k.short_guid}`));
64
137
  console.log('');
65
138
  console.log(warning('Copy it now - it will not be shown again.'));
@@ -72,7 +145,7 @@ keyCommand
72
145
  .option('--json', 'Output as JSON')
73
146
  .action((opts) => run('List', async () => {
74
147
  const res = await get(`/projects/${await projectGuid(opts)}/api-keys`);
75
- printList(res.data, opts, 'No API keys. Mint one with: gipity key create "my script" --role editor', (k) => `${bold(k.short_guid)} ${k.name} ${muted(`${k.role} ${k.prefix}... last used ${fmtDate(k.last_used_at)} expires ${fmtDate(k.expires_at)}`)}`);
148
+ printList(res.data, opts, 'No API keys. Mint one with: gipity key create "my script" --role editor', (k) => `${bold(k.short_guid)} ${k.name} ${muted(`${k.role} ${describeScopes(k.scopes)} ${k.prefix}... last used ${fmtDate(k.last_used_at)} expires ${fmtDate(k.expires_at)}`)}`);
76
149
  }));
77
150
  keyCommand
78
151
  .command('revoke <short_guid>')
@@ -132,6 +132,12 @@ Examples:
132
132
  const dur = d.duration_ms;
133
133
  console.log(` ${muted(`${d.trigger_type} • ${dur ?? '?'}ms`)}${d.error_message ? muted(' • ') + clrError(String(d.error_message).slice(0, 200)) : ''}`);
134
134
  }
135
+ if (e.kind === 'traffic') {
136
+ const where = [d.city, d.region, d.country].filter(Boolean).join(', ');
137
+ const bits = [where, d.referrer ? `from ${d.referrer}` : ''].filter(Boolean).join(' • ');
138
+ if (bits)
139
+ console.log(` ${muted(bits)}`);
140
+ }
135
141
  if (e.kind === 'service') {
136
142
  const dur = d.latency_ms;
137
143
  console.log(` ${muted(`${d.service} (${d.provider ?? '?'}/${d.model ?? '?'}) • ${dur ?? '?'}ms`)}${d.error_message ? muted(' • ') + clrError(String(d.error_message).slice(0, 200)) : ''}`);
@@ -141,4 +147,89 @@ Examples:
141
147
  console.log(`\n${muted(`(truncated at ${limit} entries: bump --limit or narrow --filter)`)}`);
142
148
  }
143
149
  }));
150
+ const TRAFFIC_RANGES = ['1h', '24h', '7d', '30d'];
151
+ logsCommand
152
+ .command('traffic')
153
+ .description('Visitor summary for this app: page views, sessions, and the top countries, cities, pages and referring sites')
154
+ .addOption(new Option('--range <window>', 'Time window').choices(TRAFFIC_RANGES).default('7d'))
155
+ .option('--country <code>', 'Only visitors from one country (ISO code, e.g. US)')
156
+ .option('--limit <n>', 'Rows per list', '10')
157
+ .option('--json', 'Output as JSON (parseable by agents / pipes)')
158
+ .addHelpText('after', `
159
+ Counts page views recorded by the Gipity tracker (gipity.js), on a Gipity app or
160
+ on any other site that loads it with this project's data-app. Country and city
161
+ come from each visitor's IP address when the view arrives; the address itself is
162
+ not stored.
163
+
164
+ Examples:
165
+ $ gipity logs traffic Last 7 days
166
+ $ gipity logs traffic --range 24h Last 24 hours
167
+ $ gipity logs traffic --country US US visitors only: their pages and cities
168
+ $ gipity logs traffic --json { pageviews, sessions, countries, cities, pages, referrers }
169
+
170
+ Page-by-page rows: gipity logs app --type traffic --since 1h
171
+ `)
172
+ .action((opts) => run('Traffic', async () => {
173
+ const config = requireConfig();
174
+ const limit = Math.min(Math.max(parseInt(opts.limit, 10) || 10, 1), 50);
175
+ const country = opts.country ? String(opts.country).trim().toUpperCase() : undefined;
176
+ if (country !== undefined && !/^[A-Z]{2}$/.test(country)) {
177
+ throw new Error(`--country takes a two-letter country code (e.g. US), not "${opts.country}"`);
178
+ }
179
+ const base = new URLSearchParams({ range: String(opts.range), app_guid: config.projectGuid });
180
+ const top = (signal) => {
181
+ const qs = new URLSearchParams(base);
182
+ qs.set('signal', signal);
183
+ qs.set('limit', String(limit));
184
+ if (country)
185
+ qs.set('country', country);
186
+ return get(`/account/logs/top?${qs.toString()}`).then((r) => r.data.items);
187
+ };
188
+ const [stats, sessions, countries, cities, pages, referrers] = await Promise.all([
189
+ get(`/account/logs/stats?${base.toString()}`),
190
+ get(`/account/logs/stats/sessions?${base.toString()}`),
191
+ top('country'), top('city'), top('path'), top('referrer_host'),
192
+ ]);
193
+ const summary = {
194
+ range: String(opts.range),
195
+ country: country ?? null,
196
+ pageviews: stats.data.cards.traffic,
197
+ sessions: sessions.data.sessions,
198
+ live: sessions.data.live,
199
+ countries, cities, pages, referrers,
200
+ };
201
+ if (opts.json) {
202
+ console.log(JSON.stringify(summary));
203
+ return;
204
+ }
205
+ const scope = country ? `, visitors from ${country}` : '';
206
+ if (country) {
207
+ console.log(`${bold('Traffic')} ${muted(`(last ${summary.range}${scope})`)}\n`);
208
+ }
209
+ else {
210
+ console.log(`${bold('Traffic')} ${muted(`(last ${summary.range})`)}: ${summary.pageviews} page views, ${summary.sessions} sessions, ${summary.live} live now\n`);
211
+ }
212
+ const section = (title, items, label) => {
213
+ console.log(bold(title));
214
+ if (items.length === 0) {
215
+ console.log(` ${muted('none in this window')}\n`);
216
+ return;
217
+ }
218
+ const width = Math.min(Math.max(...items.map((i) => label(i).length)), 48);
219
+ for (const i of items) {
220
+ const name = label(i);
221
+ const shown = name.length > 48 ? name.slice(0, 45) + '...' : name.padEnd(width);
222
+ const sess = typeof i.sessions === 'number' ? muted(` ${i.sessions} sessions`) : '';
223
+ console.log(` ${shown} ${String(i.count).padStart(6)} views${sess}`);
224
+ }
225
+ console.log('');
226
+ };
227
+ section('Countries', countries, (i) => i.key);
228
+ section('Cities', cities, (i) => [i.key, i.region, i.country].filter(Boolean).join(', '));
229
+ section('Pages', pages, (i) => i.key);
230
+ section('Referring sites', referrers, (i) => i.key);
231
+ if (countries.length === 0 && pages.length === 0) {
232
+ console.log(muted('No page views yet. Load gipity.js on the site with data-app="' + config.projectGuid + '" (gipity skill read app-debugging).'));
233
+ }
234
+ }));
144
235
  //# sourceMappingURL=logs.js.map
@@ -326,28 +326,51 @@ export function slowRenderMessage(fps, o) {
326
326
  + `2D/Phaser template: ${bold("(await import('./js/config.js')).advance(seconds)")}).`;
327
327
  }
328
328
  /** A slow eval should say which leg was slow, instead of leaving the caller to
329
- * guess a longer --wait. Silent under SLOW_EVAL_MS. Exported for tests. */
330
- const SLOW_EVAL_MS = 20_000;
329
+ * guess a longer --wait. Silent under SLOW_EVAL_MS. Uses the server's phase
330
+ * breakdown when it has one. Exported for tests. */
331
+ const SLOW_EVAL_MS = 10_000;
332
+ // Above this, say before waiting that the call may run long.
333
+ const LONG_EVAL_WARN_MS = 100_000;
331
334
  export function evalTimingLine(t) {
332
335
  const total = t.hostMs + t.submitMs + t.pollMs;
333
336
  if (total < SLOW_EVAL_MS)
334
337
  return null;
335
338
  const s = (ms) => `${(ms / 1000).toFixed(1)}s`;
336
- const parts = [
337
- t.hostMs >= 500 ? `hosting files ${s(t.hostMs)}` : null,
338
- t.submitMs >= 500 ? `camera/feed setup ${s(t.submitMs)}` : null,
339
- t.browserMs !== undefined ? `browser ${s(t.browserMs)} (launch, page load, waits, script)` : `browser ${s(t.pollMs)}`,
340
- t.browserMs !== undefined && t.pollMs - t.browserMs >= 2000 ? `queue + cleanup ${s(t.pollMs - t.browserMs)}` : null,
341
- ].filter(Boolean);
342
- return `timing: ${s(total)} = ${parts.join(' + ')}`;
339
+ const some = (label, ms, min = 500) => (ms !== undefined && ms >= min ? `${label} ${s(ms)}` : null);
340
+ const head = [
341
+ some('hosting files', t.hostMs),
342
+ some('camera/feed setup', t.submitMs),
343
+ ];
344
+ const tm = t.timing;
345
+ const browser = tm
346
+ ? [
347
+ some('sandbox queue', tm.queueMs),
348
+ some('browser start', tm.browserStartMs, 0),
349
+ some('page load', tm.pageLoadMs, 0),
350
+ some('wait/wait-for', tm.settleMs),
351
+ ...tm.scriptMs.map((ms, i) => `${i === 0 ? 'script' : `step ${i}`} ${s(ms)}`),
352
+ some('reload', tm.reloadMs),
353
+ some('cleanup', tm.cleanupMs),
354
+ // Result pickup: the client polls the finished job.
355
+ some('result pickup', t.pollMs - tm.totalMs, 1000),
356
+ ]
357
+ : [
358
+ t.browserMs !== undefined ? `browser ${s(t.browserMs)}` : `browser ${s(t.pollMs)}`,
359
+ t.browserMs !== undefined && t.pollMs - t.browserMs >= 2000 ? `queue + cleanup ${s(t.pollMs - t.browserMs)}` : null,
360
+ ];
361
+ return `timing: ${s(total)} = ${[...head, ...browser].filter(Boolean).join(' + ')}`;
343
362
  }
344
363
  /** Poll the async eval job until it finishes. Eval runs server-side as a
345
364
  * short-lived job (so a long --wait can't trip the gateway idle timeout);
346
365
  * we submit, then poll the result out of the job store. `expectedWorkMs` is
347
366
  * the time the server-side work is expected to take (see evalWorkBudgetMs);
348
367
  * the client budget is that plus 60s of headroom for browser open/cold start. */
349
- export async function pollEvalResult(evalJobId, expectedWorkMs) {
350
- const deadline = Date.now() + expectedWorkMs + 60_000;
368
+ export async function pollEvalResult(evalJobId, expectedWorkMs, serverMaxMs) {
369
+ // The server states the job's real upper bound (every leg ends on its own
370
+ // wall-clock deadline); wait that plus a little for the result to land.
371
+ // Without it, fall back to our own estimate plus flat headroom.
372
+ const budgetMs = serverMaxMs !== undefined ? serverMaxMs + 10_000 : expectedWorkMs + 60_000;
373
+ const deadline = Date.now() + budgetMs;
351
374
  let missCount = 0;
352
375
  while (Date.now() < deadline) {
353
376
  let rec;
@@ -367,14 +390,16 @@ export async function pollEvalResult(evalJobId, expectedWorkMs) {
367
390
  return rec;
368
391
  if (rec.status === 'error')
369
392
  throw new ApiError(rec.httpStatus, rec.code, rec.reason);
370
- await sleep(1000);
393
+ // A finished job sits in Redis until picked up; a short interval keeps that
394
+ // pickup from adding up to a second to every call.
395
+ await sleep(250);
371
396
  }
372
397
  // This is the CLIENT giving up, not the page failing — and the budget above
373
398
  // already covers everything the caller asked for, so "your expression is too
374
399
  // big" is the one thing it is NOT. Never advise lowering --wait: on a camera /
375
400
  // vision run the wait is what lets the model load, so that "fix" swaps a
376
401
  // timeout for a silently empty read, which is worse.
377
- throw new ApiError(504, 'EVAL_TIMEOUT', `the browser did not report back within ${Math.round((expectedWorkMs + 60_000) / 1000)}s: that budget already ` +
402
+ throw new ApiError(504, 'EVAL_TIMEOUT', `the browser did not report back within ${Math.round(budgetMs / 1000)}s: that budget already ` +
378
403
  `covers --wait, --wait-for, the eval body and any --camera setup, so this is the browser itself being slow or ` +
379
404
  `stuck (a cold sandbox, a heavy page), not your expression being too big. Lowering --wait does NOT help and on ` +
380
405
  `a --camera run actively hurts (the wait is what lets the vision model load: cut it and the eval reads an ` +
@@ -653,6 +678,13 @@ export const pageEvalCommand = new Command('eval')
653
678
  cameraUrl: camera?.url,
654
679
  });
655
680
  const pollStart = Date.now();
681
+ // Say up front when this call can outlast a typical 120s agent tool cap,
682
+ // so a long run is a choice, not a surprise background task.
683
+ const maxMs = kickoff.data.maxMs;
684
+ if (maxMs !== undefined && maxMs > LONG_EVAL_WARN_MS) {
685
+ console.error(muted(`This eval can take up to ${Math.round(maxMs / 1000)}s (page load + --wait/--wait-for + --timeout per script, ` +
686
+ `each a hard limit). Lower --timeout or --wait-timeout to keep it shorter.`));
687
+ }
656
688
  let d;
657
689
  try {
658
690
  d = await pollEvalResult(kickoff.data.evalJobId, evalWorkBudgetMs({
@@ -662,7 +694,7 @@ export const pageEvalCommand = new Command('eval')
662
694
  hasCamera: !!camera,
663
695
  scriptBudgetMs: sentScriptBudgetMs,
664
696
  legs: 1 + sentSteps.length,
665
- }));
697
+ }), maxMs);
666
698
  }
667
699
  catch (err) {
668
700
  // The server's overrun message names the budget but not the flag that
@@ -679,7 +711,7 @@ export const pageEvalCommand = new Command('eval')
679
711
  }
680
712
  const timing = evalTimingLine({
681
713
  hostMs: submitStart - hostStart, submitMs: pollStart - submitStart,
682
- pollMs: Date.now() - pollStart, browserMs: d.browserMs,
714
+ pollMs: Date.now() - pollStart, browserMs: d.browserMs, timing: d.timing,
683
715
  });
684
716
  if (timing)
685
717
  console.error(muted(timing));
@@ -900,6 +932,9 @@ Which one:
900
932
  calls; every call re-loads the page and re-pays it. Start that work on page load and
901
933
  absorb it in the pre-eval window: --wait <ms> (max ${MAX_WAIT_MS}) or, better,
902
934
  --wait-for '<ready-selector>' --wait-timeout ${WAIT_FOR_MAX_MS}.
935
+ Every one of these is a hard limit: a call takes at most page load (~20s) + the wait
936
+ + --timeout per script, plus a few seconds of browser start/close. Calls over 10s print
937
+ a 'timing:' line naming where the time went (--json: the 'timing' field).
903
938
 
904
939
  Several things to check on one page? Pass --step (max ${MAX_EVAL_STEPS}) instead of running
905
940
  'page eval' N times: the steps run in order against the ONE loaded page, so a slow
@@ -223,11 +223,18 @@ export function looksLikeImagePath(p) {
223
223
  * picture of the wrong moment. Exported for tests. */
224
224
  export function buildWaitForGate(selector, timeoutMs) {
225
225
  const sel = JSON.stringify(selector);
226
- return (`await (async () => { const __t0 = Date.now(); ` +
227
- `while (Date.now() - __t0 < ${timeoutMs}) { ` +
228
- `try { if (document.querySelector(${sel})) return; } catch (e) { throw new Error('wait-for: invalid selector ' + ${sel}); } ` +
229
- `await new Promise((r) => setTimeout(r, 100)); } ` +
230
- `throw new Error('wait-for: nothing matched ' + ${sel} + ' within ${timeoutMs}ms: the page never reached that state (raise --wait-timeout, fix the selector, or check the app actually gets there headlessly)'); })();`);
226
+ // Checked on every DOM mutation (a microtask, so the gate opens the moment the
227
+ // app sets its ready attribute) with a slow timer as backstop: a timer-only
228
+ // poll lagged by seconds on a vision page busy inferring every frame.
229
+ return (`await (async () => { const __q = ${sel}; ` +
230
+ `try { document.querySelector(__q); } catch (e) { throw new Error('wait-for: invalid selector ' + __q); } ` +
231
+ `if (document.querySelector(__q)) return; ` +
232
+ `const __ok = await new Promise((res) => { let o; const end = (v) => { clearTimeout(t); clearInterval(iv); if (o) o.disconnect(); res(v); }; ` +
233
+ `try { o = new MutationObserver(() => { if (document.querySelector(__q)) end(true); }); ` +
234
+ `o.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }); } catch (e) {} ` +
235
+ `const iv = setInterval(() => { if (document.querySelector(__q)) end(true); }, 100); ` +
236
+ `const t = setTimeout(() => end(!!document.querySelector(__q)), ${timeoutMs}); }); ` +
237
+ `if (!__ok) throw new Error('wait-for: nothing matched ' + __q + ' within ${timeoutMs}ms: the page never reached that state (raise --wait-timeout, fix the selector, or check the app actually gets there headlessly)'); })();`);
231
238
  }
232
239
  /** Max ms the selector gate may wait. The gate runs inside the capture's sandbox
233
240
  * exec budget (page load + delay + script + settle + render), and 15s is what
@@ -189,8 +189,8 @@ async function observeClient(url, expr, i, label, settleMs, holdMs, waitForSelec
189
189
  // anything still applied at the end of the hold so the harness finishes.
190
190
  lifecycle: lifecycle?.length ? { steps: lifecycle, untilMs: holdMs } : undefined,
191
191
  });
192
- // Server work ≈ nav + settle + the in-page hold; pollEvalResult adds 60s headroom.
193
- const d = await pollEvalResult(kickoff.data.evalJobId, settleMs + holdMs + (barrier ? JOIN_ALLOWANCE_MS : 0));
192
+ // The server states the job's upper bound; the estimate is the fallback.
193
+ const d = await pollEvalResult(kickoff.data.evalJobId, settleMs + holdMs + (barrier ? JOIN_ALLOWANCE_MS : 0), kickoff.data.maxMs);
194
194
  const raw = d.result?.trim() ?? '';
195
195
  if (raw.startsWith('EvalError:') || raw.startsWith('ObserveError:')) {
196
196
  return { ...base, error: raw };
@@ -1,5 +1,6 @@
1
1
  import { Command, Option } from 'commander';
2
- import { get, post, put, patch, del, publicRequest, mintAppToken } from '../api.js';
2
+ import { pipeline } from 'stream/promises';
3
+ import { get, post, put, patch, del, publicRequest, mintAppToken, downloadStream } from '../api.js';
3
4
  import { getAuth } from '../auth.js';
4
5
  import { requireConfig } from '../config.js';
5
6
  import { bold, muted } from '../colors.js';
@@ -44,7 +45,7 @@ recordsCommand
44
45
  .action((opts) => run('Tables', async () => {
45
46
  const config = requireConfig();
46
47
  const res = await get(`/api/${config.projectGuid}/records-config`);
47
- printList(res.data, opts, 'No tables configured for Records API. Configure one with `gipity records config <table> --auth <level>`.', t => `${bold(t.table_name)} ${muted(t.auth_level)} ${muted(`pk=${t.primary_key_column}`)} ${muted(`db=${t.database_name}`)}`);
48
+ printList(res.data, opts, 'No tables configured for Records API. Configure one with `gipity records config <table> --auth <level>`.', t => `${bold(t.table_name)} ${muted(t.auth_level)} ${muted(`pk=${t.primary_key_column}`)} ${muted(`db=${t.database_name}`)}${t.append_only ? ` ${muted('append-only')}` : ''}`);
48
49
  }));
49
50
  recordsCommand
50
51
  .command('config <table>')
@@ -56,13 +57,14 @@ recordsCommand
56
57
  .option('--auto-number <prefix>', 'Number new records automatically, e.g. INC -> INC0001001 (pass "none" to turn off). Same as auto_number in gipity.yaml')
57
58
  .option('--auto-number-pad <n>', 'Zero-pad width of the auto-number (default 7)')
58
59
  .option('--auto-number-column <col>', 'Column the auto-number is written to (default: number)')
60
+ .option('--append-only', "Make the table inserts-only for good: updates, deletes and purges are refused for everyone, including raw SQL. Can't be undone. Same as append_only: true in gipity.yaml")
59
61
  .option('--json', 'Output as JSON')
60
62
  .action((table, opts) => run('Config', async () => {
61
63
  const config = requireConfig();
62
64
  const base = `/api/${config.projectGuid}/records/${table}/config`;
63
65
  // No setter flags → just show the current config.
64
66
  const setting = opts.auth || opts.searchable !== undefined || opts.primaryKey || opts.softDelete
65
- || opts.autoNumber || opts.autoNumberPad || opts.autoNumberColumn;
67
+ || opts.autoNumber || opts.autoNumberPad || opts.autoNumberColumn || opts.appendOnly;
66
68
  if (!setting) {
67
69
  const res = await get(base);
68
70
  printResult(JSON.stringify(res.data, null, 2), opts, res.data);
@@ -87,12 +89,14 @@ recordsCommand
87
89
  }
88
90
  if (opts.autoNumberColumn)
89
91
  body.auto_number_column = opts.autoNumberColumn;
92
+ if (opts.appendOnly)
93
+ body.append_only = true;
90
94
  const res = await patch(base, body);
91
95
  const d = res.data;
92
96
  const autoNumber = d.auto_number_prefix
93
97
  ? `${d.auto_number_prefix} (pad ${d.auto_number_pad}, column ${d.auto_number_column})`
94
98
  : 'off';
95
- printResult(`Configured "${table}": auth=${d.auth_level}, searchable=${d.searchable}, pk=${d.primary_key_column}, auto-number=${autoNumber}`, opts, d);
99
+ printResult(`Configured "${table}": auth=${d.auth_level}, searchable=${d.searchable}, pk=${d.primary_key_column}, auto-number=${autoNumber}${d.append_only ? ', append-only' : ''}`, opts, d);
96
100
  }));
97
101
  recordsCommand
98
102
  .command('list <table>')
@@ -154,9 +158,20 @@ recordsCommand
154
158
  .command('history <table> [id]')
155
159
  .description('Audit history (who/what changed it, with English summaries). Omit <id> for the whole table\'s feed.')
156
160
  .option('--limit <n>', 'Max events', '20')
161
+ .option('--jsonl', 'Export the WHOLE table history to stdout as JSON Lines, oldest first (owner/editor; ignores --limit)')
157
162
  .option(ANON_FLAG, ANON_HELP)
158
163
  .option('--json', 'Output as JSON')
159
164
  .action((table, id, opts) => run('History', async () => {
165
+ if (opts.jsonl) {
166
+ if (id)
167
+ throw new Error('--jsonl exports a whole table: drop the <id>');
168
+ if (opts.anon)
169
+ throw new Error('--jsonl needs the owner or an editor: drop --anon');
170
+ const config = requireConfig();
171
+ const body = await downloadStream(`/api/${config.projectGuid}/records/${encodeURIComponent(table)}/history?format=jsonl`);
172
+ await pipeline(body, process.stdout, { end: false });
173
+ return;
174
+ }
160
175
  const api = await recordsHttp(opts);
161
176
  // Table-wide feed when no id is given - the same endpoint an activity/history
162
177
  // view reads, so verifying it needs no hand-built HTTP call.
@@ -13,7 +13,7 @@ async function scopeQuery(opts) {
13
13
  }
14
14
  export const secretsCommand = new Command('secrets')
15
15
  .description('Manage app secrets')
16
- .addHelpText('after', '\nEncrypted API keys and tokens for your app, read in functions via secrets.get("NAME").');
16
+ .addHelpText('after', '\nEncrypted API keys and tokens for your app, read in functions via secrets.get("NAME").\nValues are write-only: no command prints a stored value back.');
17
17
  secretsCommand
18
18
  .command('list')
19
19
  .alias('ls')
@@ -38,6 +38,27 @@ secretsCommand
38
38
  console.log(` ${s.name} ${masked} ${muted(`updated ${new Date(s.updated_at).toLocaleDateString()}`)}`);
39
39
  }
40
40
  }));
41
+ // Secret values are write-only by design: they are decrypted only inside a
42
+ // running function (secrets.get), never returned to the CLI. `get` exists so an
43
+ // agent that reaches for it gets a clear refusal (stderr, exit 1) instead of an
44
+ // unknown-command line it might mistake for the value (platform#500).
45
+ secretsCommand
46
+ .command('get <name>')
47
+ .description('Secret values are write-only: confirms the secret exists, never prints its value')
48
+ .option('--account', 'Look in account-wide secrets')
49
+ .option('--project <guid-or-slug>', 'Target a specific project instead of cwd / Home')
50
+ .option('--json', 'Output raw JSON')
51
+ .action((name, opts) => run('Secrets', async () => {
52
+ const res = await get(`/secrets?${await scopeQuery(opts)}`);
53
+ const scope = opts.account ? 'account-wide' : 'project';
54
+ const found = res.data.find(s => s.name === name);
55
+ if (!found)
56
+ throw new Error(`No ${scope} secret named '${name}'. Values are write-only, so set it with: gipity secrets set ${name} VALUE${opts.account ? ' --account' : ''}`);
57
+ const ends = found.preview ? ` (ends in ...${found.preview})` : '';
58
+ throw new Error(`secret values are write-only and are never shown. '${name}' exists${ends}; only a deployed function can read it, with secrets.get('${name}'). `
59
+ + `To hand a value to another service too, generate it yourself, keep it, then store it: `
60
+ + `TOK=$(openssl rand -hex 24); gipity secrets set ${name} "$TOK"; echo "$TOK". Setting it again replaces the live value.`);
61
+ }));
41
62
  secretsCommand
42
63
  .command('set <name> <value>')
43
64
  .description('Create or update a secret (UPPER_SNAKE_CASE name). Encrypted at rest; never echoed back')
package/dist/index.js CHANGED
@@ -5606,13 +5606,13 @@ var require_streamx = __commonJS({
5606
5606
  }
5607
5607
  function pipelinePromise(...streams) {
5608
5608
  return new Promise((resolve21, reject) => {
5609
- return pipeline(...streams, (err) => {
5609
+ return pipeline2(...streams, (err) => {
5610
5610
  if (err) return reject(err);
5611
5611
  resolve21();
5612
5612
  });
5613
5613
  });
5614
5614
  }
5615
- function pipeline(stream, ...streams) {
5615
+ function pipeline2(stream, ...streams) {
5616
5616
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
5617
5617
  const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
5618
5618
  if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
@@ -5706,7 +5706,7 @@ var require_streamx = __commonJS({
5706
5706
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
5707
5707
  }
5708
5708
  module.exports = {
5709
- pipeline,
5709
+ pipeline: pipeline2,
5710
5710
  pipelinePromise,
5711
5711
  isStream,
5712
5712
  isStreamx,
@@ -6999,7 +6999,7 @@ You are the developer. Write files in this directory - Gipity's editor hooks (in
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), 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.
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; "email me when..." is \`email({ to: 'owner', ... })\`, which reaches the app owner with no address or secret; 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
 
@@ -7053,7 +7053,7 @@ mkdir -p ~/GipityProjects/<slug> && cd ~/GipityProjects/<slug> && gipity init <s
7053
7053
 
7054
7054
  ## CLI quick reference
7055
7055
 
7056
- Key commands: \`gipity add <template|kit>\`, \`gipity brand set --emoji <e>|--color <hex>\` (regenerate the app's icons + social share card), \`gipity deploy [prod|<env>]\`, \`gipity env\` (list/create/delete environments), \`gipity sandbox run\`, \`gipity page inspect <url>\`, \`gipity page screenshot <url>\`, \`gipity db query "SQL"\`, \`gipity fn call <name>\`, \`gipity logs fn <name>\`, \`gipity secrets set <NAME> <value> [--account]\` (store an API key/token encrypted; read in functions via \`secrets.get('NAME')\` - never hardcode keys), \`gipity skill read <name>\`.
7056
+ Key commands: \`gipity add <template|kit>\`, \`gipity brand set --emoji <e>|--color <hex>\` (regenerate the app's icons + social share card), \`gipity deploy [prod|<env>]\`, \`gipity env\` (list/create/delete environments), \`gipity sandbox run\`, \`gipity page inspect <url>\`, \`gipity page screenshot <url>\`, \`gipity db query "SQL"\`, \`gipity fn call <name>\`, \`gipity logs fn <name>\`, \`gipity secrets set <NAME> <value> [--account]\` (store an API key/token encrypted; read in functions via \`secrets.get('NAME')\`; write-only, so keep a copy of any value another service also needs - never hardcode keys), \`gipity skill read <name>\`.
7057
7057
  Rename for findability: \`gipity project rename <name>\` renames the current project's display name (the slug and deployed URLs never change); it's the label users scan in Monitor and \`gipity project\`, so keep it SHORT: 2-4 words, at most 40 characters, no trailing punctuation (e.g. "Stripe checkout", "Tetris game").
7058
7058
  Pull an existing remote project local (given its URL/slug): \`mkdir -p ~/GipityProjects/<slug> && cd ~/GipityProjects/<slug> && gipity init <slug>\` (adopts the matching project and syncs files down - this is the "clone").
7059
7059
  Move whole apps in/out: \`gipity save\` (export this project as a portable \`.gip\` bundle), \`gipity load <file.gip | github:owner/repo>\` (import as a NEW project; \`--inspect\` to preview), \`gipity github connect\` (1-2 click GitHub access for imports). Porting a Vercel/Replit/Lovable app? Load the \`app-import\` skill first.
@@ -7117,6 +7117,7 @@ Watch for **bulky output dirs dropped loose at the root** (e.g. \`out/\`, \`vsd_
7117
7117
  Run \`gipity skill list\` to see every skill. Run \`gipity skill read <name>\` to read one. Load the relevant skill before starting a task - they have the correct API patterns, code examples, and common mistakes.
7118
7118
 
7119
7119
  App services skills (load before calling \`/services/*\` endpoints):
7120
+ - \`app-api-keys\` - project API keys for scripts/devices: gipity key create, scopes (functions, tables, files, ip)
7120
7121
  - \`app-audio\` - sound effects, music, transcription
7121
7122
  - \`app-auth\` - sign in: Gipity accounts or app-owned users (Google, email code), popup vs redirect
7122
7123
  - \`app-files\` - uploads, then displaying files and the storage helper (ownership check, delete)
@@ -7152,7 +7153,7 @@ Kit skills (reusable building blocks - \`gipity add <kit>\`):
7152
7153
  - \`leaderboard\` - game leaderboards: high scores or times, daily/weekly/monthly/season boards, tiebreaks, replays, cheat checks, bans
7153
7154
 
7154
7155
  Other key skills:
7155
- - \`email\` - sending email from a deployed app with the email() service or a workflow notify step (no setup/keys), gipity email test/log, HTML formatting, images
7156
+ - \`email\` - sending email from a deployed app with the email() service or a workflow notify step (no setup/keys; to: 'owner' emails you, the app owner), gipity email test/log, HTML formatting, images
7156
7157
  - \`sandbox-tools\` - cloud sandbox capabilities and pre-installed tools`;
7157
7158
  DEFINITION_OF_DONE = `## Definition of done (build tasks)
7158
7159
  1. \`gipity deploy\` succeeds and you have a live URL.
@@ -36481,6 +36482,19 @@ Give a script, cron, or agent write access to your app without a login:
36481
36482
  gipity key create "laptop importer" --role editor
36482
36483
  # the script sends: X-Api-Key: <the key printed once above>
36483
36484
 
36485
+ The key also works as Authorization: Bearer <key>, and only on this app
36486
+ (and environment: add --env dev for a dev key).
36487
+
36488
+ Scope a key that lives on a device or anywhere you don't fully control, so a
36489
+ leaked key can only do its one job:
36490
+
36491
+ gipity key create "front door" --role editor \\
36492
+ --functions send-command,heartbeat --tables commands:write,logs:read \\
36493
+ --files read --ip 203.0.113.7/32
36494
+
36495
+ Any of --functions / --tables / --files limits the key to exactly what is
36496
+ listed (nothing else on the app API); --ip alone only pins the source address.
36497
+
36484
36498
  Inside a function the caller shows up as ctx.auth.via === 'api_key' with
36485
36499
  ctx.auth.apiKeyName set to the key's name - stamp that on rows to tell
36486
36500
  script-written entries from hand-entered ones. Never build your own key table.
@@ -36488,13 +36502,52 @@ script-written entries from hand-entered ones. Never build your own key table.
36488
36502
  Account-level tokens that run the CLI headlessly are a different thing: see
36489
36503
  gipity token --help.`);
36490
36504
  var fmtDate2 = (d) => d ? new Date(d).toLocaleDateString() : "never";
36505
+ var splitList = (v7) => v7.split(",").map((x) => x.trim()).filter(Boolean);
36506
+ function scopesFromFlags(opts) {
36507
+ const scopes = {};
36508
+ if (opts.functions !== void 0) {
36509
+ const fns = splitList(opts.functions);
36510
+ if (!fns.length) throw new Error("--functions needs at least one function name");
36511
+ scopes.functions = fns;
36512
+ }
36513
+ if (opts.tables !== void 0) {
36514
+ const entries = splitList(opts.tables);
36515
+ if (!entries.length) throw new Error("--tables needs at least one table:read or table:write");
36516
+ scopes.tables = {};
36517
+ for (const entry of entries) {
36518
+ const [table, access, ...rest] = entry.split(":");
36519
+ if (!table || access !== "read" && access !== "write" || rest.length) {
36520
+ throw new Error(`--tables entry "${entry}" must be table:read or table:write`);
36521
+ }
36522
+ scopes.tables[table] = access;
36523
+ }
36524
+ }
36525
+ if (opts.files !== void 0) scopes.files = opts.files;
36526
+ if (opts.ip !== void 0) {
36527
+ const ips = splitList(opts.ip);
36528
+ if (!ips.length) throw new Error("--ip needs at least one address or CIDR range");
36529
+ scopes.ip = ips;
36530
+ }
36531
+ return Object.keys(scopes).length ? scopes : null;
36532
+ }
36533
+ function describeScopes(scopes) {
36534
+ if (!scopes) return "all access";
36535
+ const parts = [];
36536
+ if (scopes.functions) parts.push(`fn: ${scopes.functions.join(",")}`);
36537
+ if (scopes.tables) parts.push(`tables: ${Object.entries(scopes.tables).map(([t, a]) => `${t}:${a}`).join(",")}`);
36538
+ if (scopes.files) parts.push(`files: ${scopes.files}`);
36539
+ if (scopes.ip) parts.push(`ip: ${scopes.ip.join(",")}`);
36540
+ return parts.join(" ");
36541
+ }
36491
36542
  var projectOpt = ["--project <guid-or-slug>", "Target a specific project instead of cwd / Home"];
36492
36543
  async function projectGuid(opts) {
36493
36544
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
36494
36545
  return config.projectGuid;
36495
36546
  }
36496
- keyCommand.command("create <name>").description("Mint a project API key (shown once). Give it a name you will recognize later").addOption(new Option("--role <role>", "Access role for the key").choices(["viewer", "editor", "owner"]).default("viewer")).option("--expires-days <n>", "Days until the key expires (default: never)").option(...projectOpt).option("--json", "Output as JSON").action((name, opts) => run("Create", async () => {
36547
+ keyCommand.command("create <name>").description("Mint a project API key (shown once). Give it a name you will recognize later").addOption(new Option("--role <role>", "Access role for the key").choices(["viewer", "editor", "owner"]).default("viewer")).option("--expires-days <n>", "Days until the key expires (default: never)").option("--functions <names>", "Scope: only these functions (comma-separated)").option("--tables <list>", "Scope: only these Records tables, e.g. commands:write,logs:read").addOption(new Option("--files <access>", "Scope: app files access").choices(["read", "write"])).option("--ip <list>", "Scope: only from these IPs / CIDR ranges (comma-separated)").option(...projectOpt).option("--json", "Output as JSON").action((name, opts) => run("Create", async () => {
36497
36548
  const body = { name, role: opts.role };
36549
+ const scopes = scopesFromFlags(opts);
36550
+ if (scopes) body.scopes = scopes;
36498
36551
  if (opts.expiresDays !== void 0) {
36499
36552
  const days = parseInt(opts.expiresDays, 10);
36500
36553
  if (!Number.isFinite(days) || days <= 0) throw new Error("--expires-days must be a positive number of days");
@@ -36511,11 +36564,12 @@ keyCommand.command("create <name>").description("Mint a project API key (shown o
36511
36564
  }
36512
36565
  const expNote = k7.expires_at ? ` (expires ${fmtDate2(k7.expires_at)})` : " (never expires)";
36513
36566
  console.log(success(`Created API key ${bold(k7.short_guid)} "${k7.name}" as ${k7.role}${muted(expNote)}.`));
36567
+ if (k7.scopes) console.log(muted(`Scopes: ${describeScopes(k7.scopes)}`));
36514
36568
  console.log("");
36515
36569
  console.log(k7.key);
36516
36570
  console.log("");
36517
36571
  console.log(muted("Send it from your script on every request:"));
36518
- console.log(muted(` curl -H "X-Api-Key: ${k7.key}" ...`));
36572
+ console.log(muted(` curl -H "X-Api-Key: ${k7.key}" ... (or Authorization: Bearer <key>)`));
36519
36573
  console.log(muted(`Revoke it any time: gipity key revoke ${k7.short_guid}`));
36520
36574
  console.log("");
36521
36575
  console.log(warning("Copy it now - it will not be shown again."));
@@ -36526,7 +36580,7 @@ keyCommand.command("list").alias("ls").description("List this project's API keys
36526
36580
  res.data,
36527
36581
  opts,
36528
36582
  'No API keys. Mint one with: gipity key create "my script" --role editor',
36529
- (k7) => `${bold(k7.short_guid)} ${k7.name} ${muted(`${k7.role} ${k7.prefix}... last used ${fmtDate2(k7.last_used_at)} expires ${fmtDate2(k7.expires_at)}`)}`
36583
+ (k7) => `${bold(k7.short_guid)} ${k7.name} ${muted(`${k7.role} ${describeScopes(k7.scopes)} ${k7.prefix}... last used ${fmtDate2(k7.last_used_at)} expires ${fmtDate2(k7.expires_at)}`)}`
36530
36584
  );
36531
36585
  }));
36532
36586
  keyCommand.command("revoke <short_guid>").alias("rm").description("Revoke a project API key (instant, irreversible)").option(...projectOpt).option("--json", "Output as JSON").action((shortGuid, opts) => run("Revoke", async () => {
@@ -38216,21 +38270,37 @@ function slowRenderMessage(fps, o) {
38216
38270
  }
38217
38271
  return `${warning("\u26A0 Slow render:")} page painted at ${fps} fps. Waiting on real time (setTimeout) advances animation/physics time far slower than it looks: assertions after a wall-clock wait can report a false negative. Step the app's own loop deterministically instead (3D templates: ${bold("core.advance(seconds)")}; 2D/Phaser template: ${bold("(await import('./js/config.js')).advance(seconds)")}).`;
38218
38272
  }
38219
- var SLOW_EVAL_MS = 2e4;
38273
+ var SLOW_EVAL_MS = 1e4;
38274
+ var LONG_EVAL_WARN_MS = 1e5;
38220
38275
  function evalTimingLine(t) {
38221
38276
  const total = t.hostMs + t.submitMs + t.pollMs;
38222
38277
  if (total < SLOW_EVAL_MS) return null;
38223
38278
  const s = (ms2) => `${(ms2 / 1e3).toFixed(1)}s`;
38224
- const parts = [
38225
- t.hostMs >= 500 ? `hosting files ${s(t.hostMs)}` : null,
38226
- t.submitMs >= 500 ? `camera/feed setup ${s(t.submitMs)}` : null,
38227
- t.browserMs !== void 0 ? `browser ${s(t.browserMs)} (launch, page load, waits, script)` : `browser ${s(t.pollMs)}`,
38279
+ const some = (label2, ms2, min = 500) => ms2 !== void 0 && ms2 >= min ? `${label2} ${s(ms2)}` : null;
38280
+ const head = [
38281
+ some("hosting files", t.hostMs),
38282
+ some("camera/feed setup", t.submitMs)
38283
+ ];
38284
+ const tm2 = t.timing;
38285
+ const browser = tm2 ? [
38286
+ some("sandbox queue", tm2.queueMs),
38287
+ some("browser start", tm2.browserStartMs, 0),
38288
+ some("page load", tm2.pageLoadMs, 0),
38289
+ some("wait/wait-for", tm2.settleMs),
38290
+ ...tm2.scriptMs.map((ms2, i) => `${i === 0 ? "script" : `step ${i}`} ${s(ms2)}`),
38291
+ some("reload", tm2.reloadMs),
38292
+ some("cleanup", tm2.cleanupMs),
38293
+ // Result pickup: the client polls the finished job.
38294
+ some("result pickup", t.pollMs - tm2.totalMs, 1e3)
38295
+ ] : [
38296
+ t.browserMs !== void 0 ? `browser ${s(t.browserMs)}` : `browser ${s(t.pollMs)}`,
38228
38297
  t.browserMs !== void 0 && t.pollMs - t.browserMs >= 2e3 ? `queue + cleanup ${s(t.pollMs - t.browserMs)}` : null
38229
- ].filter(Boolean);
38230
- return `timing: ${s(total)} = ${parts.join(" + ")}`;
38298
+ ];
38299
+ return `timing: ${s(total)} = ${[...head, ...browser].filter(Boolean).join(" + ")}`;
38231
38300
  }
38232
- async function pollEvalResult(evalJobId, expectedWorkMs) {
38233
- const deadline = Date.now() + expectedWorkMs + 6e4;
38301
+ async function pollEvalResult(evalJobId, expectedWorkMs, serverMaxMs) {
38302
+ const budgetMs = serverMaxMs !== void 0 ? serverMaxMs + 1e4 : expectedWorkMs + 6e4;
38303
+ const deadline = Date.now() + budgetMs;
38234
38304
  let missCount = 0;
38235
38305
  while (Date.now() < deadline) {
38236
38306
  let rec;
@@ -38245,12 +38315,12 @@ async function pollEvalResult(evalJobId, expectedWorkMs) {
38245
38315
  }
38246
38316
  if (rec.status === "done") return rec;
38247
38317
  if (rec.status === "error") throw new ApiError(rec.httpStatus, rec.code, rec.reason);
38248
- await sleep(1e3);
38318
+ await sleep(250);
38249
38319
  }
38250
38320
  throw new ApiError(
38251
38321
  504,
38252
38322
  "EVAL_TIMEOUT",
38253
- `the browser did not report back within ${Math.round((expectedWorkMs + 6e4) / 1e3)}s: that budget already covers --wait, --wait-for, the eval body and any --camera setup, so this is the browser itself being slow or stuck (a cold sandbox, a heavy page), not your expression being too big. Lowering --wait does NOT help and on a --camera run actively hurts (the wait is what lets the vision model load: cut it and the eval reads an empty page instead). Just run the same command again: the sandbox is warm on the second hit.`
38323
+ `the browser did not report back within ${Math.round(budgetMs / 1e3)}s: that budget already covers --wait, --wait-for, the eval body and any --camera setup, so this is the browser itself being slow or stuck (a cold sandbox, a heavy page), not your expression being too big. Lowering --wait does NOT help and on a --camera run actively hurts (the wait is what lets the vision model load: cut it and the eval reads an empty page instead). Just run the same command again: the sandbox is warm on the second hit.`
38254
38324
  );
38255
38325
  }
38256
38326
  function evalExecTimeoutMessage(result, budgetMs) {
@@ -38426,6 +38496,12 @@ var pageEvalCommand = new Command("eval").description("Evaluate JS in a real bro
38426
38496
  cameraUrl: camera?.url
38427
38497
  });
38428
38498
  const pollStart = Date.now();
38499
+ const maxMs = kickoff.data.maxMs;
38500
+ if (maxMs !== void 0 && maxMs > LONG_EVAL_WARN_MS) {
38501
+ console.error(muted(
38502
+ `This eval can take up to ${Math.round(maxMs / 1e3)}s (page load + --wait/--wait-for + --timeout per script, each a hard limit). Lower --timeout or --wait-timeout to keep it shorter.`
38503
+ ));
38504
+ }
38429
38505
  let d;
38430
38506
  try {
38431
38507
  d = await pollEvalResult(kickoff.data.evalJobId, evalWorkBudgetMs({
@@ -38435,7 +38511,7 @@ var pageEvalCommand = new Command("eval").description("Evaluate JS in a real bro
38435
38511
  hasCamera: !!camera,
38436
38512
  scriptBudgetMs: sentScriptBudgetMs,
38437
38513
  legs: 1 + sentSteps.length
38438
- }));
38514
+ }), maxMs);
38439
38515
  } catch (err) {
38440
38516
  const msg = err?.message ?? "";
38441
38517
  const hint = budgetOverrunHint(msg, scriptBudgetMs) ?? (reloadExpr === void 0 ? navigationAbortHint(msg) : null);
@@ -38447,7 +38523,8 @@ ${hint}`);
38447
38523
  hostMs: submitStart - hostStart,
38448
38524
  submitMs: pollStart - submitStart,
38449
38525
  pollMs: Date.now() - pollStart,
38450
- browserMs: d.browserMs
38526
+ browserMs: d.browserMs,
38527
+ timing: d.timing
38451
38528
  });
38452
38529
  if (timing) console.error(muted(timing));
38453
38530
  const { result, noValue } = normalizeEvalResult(d.result);
@@ -38612,6 +38689,9 @@ Which one:
38612
38689
  calls; every call re-loads the page and re-pays it. Start that work on page load and
38613
38690
  absorb it in the pre-eval window: --wait <ms> (max ${MAX_WAIT_MS}) or, better,
38614
38691
  --wait-for '<ready-selector>' --wait-timeout ${WAIT_FOR_MAX_MS}.
38692
+ Every one of these is a hard limit: a call takes at most page load (~20s) + the wait
38693
+ + --timeout per script, plus a few seconds of browser start/close. Calls over 10s print
38694
+ a 'timing:' line naming where the time went (--json: the 'timing' field).
38615
38695
 
38616
38696
  Several things to check on one page? Pass --step (max ${MAX_EVAL_STEPS}) instead of running
38617
38697
  'page eval' N times: the steps run in order against the ONE loaded page, so a slow
@@ -38764,7 +38844,7 @@ function looksLikeImagePath(p) {
38764
38844
  }
38765
38845
  function buildWaitForGate(selector, timeoutMs) {
38766
38846
  const sel = JSON.stringify(selector);
38767
- return `await (async () => { const __t0 = Date.now(); while (Date.now() - __t0 < ${timeoutMs}) { try { if (document.querySelector(${sel})) return; } catch (e) { throw new Error('wait-for: invalid selector ' + ${sel}); } await new Promise((r) => setTimeout(r, 100)); } throw new Error('wait-for: nothing matched ' + ${sel} + ' within ${timeoutMs}ms: the page never reached that state (raise --wait-timeout, fix the selector, or check the app actually gets there headlessly)'); })();`;
38847
+ return `await (async () => { const __q = ${sel}; try { document.querySelector(__q); } catch (e) { throw new Error('wait-for: invalid selector ' + __q); } if (document.querySelector(__q)) return; const __ok = await new Promise((res) => { let o; const end = (v) => { clearTimeout(t); clearInterval(iv); if (o) o.disconnect(); res(v); }; try { o = new MutationObserver(() => { if (document.querySelector(__q)) end(true); }); o.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true }); } catch (e) {} const iv = setInterval(() => { if (document.querySelector(__q)) end(true); }, 100); const t = setTimeout(() => end(!!document.querySelector(__q)), ${timeoutMs}); }); if (!__ok) throw new Error('wait-for: nothing matched ' + __q + ' within ${timeoutMs}ms: the page never reached that state (raise --wait-timeout, fix the selector, or check the app actually gets there headlessly)'); })();`;
38768
38848
  }
38769
38849
  var WAIT_FOR_MAX_MS2 = 15e3;
38770
38850
  var WAIT_FOR_DEFAULT_MS = 15e3;
@@ -43436,6 +43516,11 @@ Examples:
43436
43516
  const dur = d.duration_ms;
43437
43517
  console.log(` ${muted(`${d.trigger_type} \u2022 ${dur ?? "?"}ms`)}${d.error_message ? muted(" \u2022 ") + error(String(d.error_message).slice(0, 200)) : ""}`);
43438
43518
  }
43519
+ if (e.kind === "traffic") {
43520
+ const where = [d.city, d.region, d.country].filter(Boolean).join(", ");
43521
+ const bits = [where, d.referrer ? `from ${d.referrer}` : ""].filter(Boolean).join(" \u2022 ");
43522
+ if (bits) console.log(` ${muted(bits)}`);
43523
+ }
43439
43524
  if (e.kind === "service") {
43440
43525
  const dur = d.latency_ms;
43441
43526
  console.log(` ${muted(`${d.service} (${d.provider ?? "?"}/${d.model ?? "?"}) \u2022 ${dur ?? "?"}ms`)}${d.error_message ? muted(" \u2022 ") + error(String(d.error_message).slice(0, 200)) : ""}`);
@@ -43446,6 +43531,90 @@ Examples:
43446
43531
  ${muted(`(truncated at ${limit} entries: bump --limit or narrow --filter)`)}`);
43447
43532
  }
43448
43533
  }));
43534
+ var TRAFFIC_RANGES = ["1h", "24h", "7d", "30d"];
43535
+ logsCommand.command("traffic").description("Visitor summary for this app: page views, sessions, and the top countries, cities, pages and referring sites").addOption(new Option("--range <window>", "Time window").choices(TRAFFIC_RANGES).default("7d")).option("--country <code>", "Only visitors from one country (ISO code, e.g. US)").option("--limit <n>", "Rows per list", "10").option("--json", "Output as JSON (parseable by agents / pipes)").addHelpText("after", `
43536
+ Counts page views recorded by the Gipity tracker (gipity.js), on a Gipity app or
43537
+ on any other site that loads it with this project's data-app. Country and city
43538
+ come from each visitor's IP address when the view arrives; the address itself is
43539
+ not stored.
43540
+
43541
+ Examples:
43542
+ $ gipity logs traffic Last 7 days
43543
+ $ gipity logs traffic --range 24h Last 24 hours
43544
+ $ gipity logs traffic --country US US visitors only: their pages and cities
43545
+ $ gipity logs traffic --json { pageviews, sessions, countries, cities, pages, referrers }
43546
+
43547
+ Page-by-page rows: gipity logs app --type traffic --since 1h
43548
+ `).action((opts) => run("Traffic", async () => {
43549
+ const config = requireConfig2();
43550
+ const limit = Math.min(Math.max(parseInt(opts.limit, 10) || 10, 1), 50);
43551
+ const country = opts.country ? String(opts.country).trim().toUpperCase() : void 0;
43552
+ if (country !== void 0 && !/^[A-Z]{2}$/.test(country)) {
43553
+ throw new Error(`--country takes a two-letter country code (e.g. US), not "${opts.country}"`);
43554
+ }
43555
+ const base = new URLSearchParams({ range: String(opts.range), app_guid: config.projectGuid });
43556
+ const top = (signal) => {
43557
+ const qs = new URLSearchParams(base);
43558
+ qs.set("signal", signal);
43559
+ qs.set("limit", String(limit));
43560
+ if (country) qs.set("country", country);
43561
+ return get(`/account/logs/top?${qs.toString()}`).then((r) => r.data.items);
43562
+ };
43563
+ const [stats, sessions, countries, cities, pages, referrers] = await Promise.all([
43564
+ get(`/account/logs/stats?${base.toString()}`),
43565
+ get(`/account/logs/stats/sessions?${base.toString()}`),
43566
+ top("country"),
43567
+ top("city"),
43568
+ top("path"),
43569
+ top("referrer_host")
43570
+ ]);
43571
+ const summary = {
43572
+ range: String(opts.range),
43573
+ country: country ?? null,
43574
+ pageviews: stats.data.cards.traffic,
43575
+ sessions: sessions.data.sessions,
43576
+ live: sessions.data.live,
43577
+ countries,
43578
+ cities,
43579
+ pages,
43580
+ referrers
43581
+ };
43582
+ if (opts.json) {
43583
+ console.log(JSON.stringify(summary));
43584
+ return;
43585
+ }
43586
+ const scope = country ? `, visitors from ${country}` : "";
43587
+ if (country) {
43588
+ console.log(`${bold("Traffic")} ${muted(`(last ${summary.range}${scope})`)}
43589
+ `);
43590
+ } else {
43591
+ console.log(`${bold("Traffic")} ${muted(`(last ${summary.range})`)}: ${summary.pageviews} page views, ${summary.sessions} sessions, ${summary.live} live now
43592
+ `);
43593
+ }
43594
+ const section = (title, items, label2) => {
43595
+ console.log(bold(title));
43596
+ if (items.length === 0) {
43597
+ console.log(` ${muted("none in this window")}
43598
+ `);
43599
+ return;
43600
+ }
43601
+ const width = Math.min(Math.max(...items.map((i) => label2(i).length)), 48);
43602
+ for (const i of items) {
43603
+ const name = label2(i);
43604
+ const shown = name.length > 48 ? name.slice(0, 45) + "..." : name.padEnd(width);
43605
+ const sess = typeof i.sessions === "number" ? muted(` ${i.sessions} sessions`) : "";
43606
+ console.log(` ${shown} ${String(i.count).padStart(6)} views${sess}`);
43607
+ }
43608
+ console.log("");
43609
+ };
43610
+ section("Countries", countries, (i) => i.key);
43611
+ section("Cities", cities, (i) => [i.key, i.region, i.country].filter(Boolean).join(", "));
43612
+ section("Pages", pages, (i) => i.key);
43613
+ section("Referring sites", referrers, (i) => i.key);
43614
+ if (countries.length === 0 && pages.length === 0) {
43615
+ console.log(muted('No page views yet. Load gipity.js on the site with data-app="' + config.projectGuid + '" (gipity skill read app-debugging).'));
43616
+ }
43617
+ }));
43449
43618
 
43450
43619
  // src/commands/page-test.ts
43451
43620
  init_api();
@@ -43588,7 +43757,7 @@ async function observeClient(url, expr, i, label2, settleMs, holdMs, waitForSele
43588
43757
  // anything still applied at the end of the hold so the harness finishes.
43589
43758
  lifecycle: lifecycle?.length ? { steps: lifecycle, untilMs: holdMs } : void 0
43590
43759
  });
43591
- const d = await pollEvalResult(kickoff.data.evalJobId, settleMs + holdMs + (barrier ? JOIN_ALLOWANCE_MS : 0));
43760
+ const d = await pollEvalResult(kickoff.data.evalJobId, settleMs + holdMs + (barrier ? JOIN_ALLOWANCE_MS : 0), kickoff.data.maxMs);
43592
43761
  const raw = d.result?.trim() ?? "";
43593
43762
  if (raw.startsWith("EvalError:") || raw.startsWith("ObserveError:")) {
43594
43763
  return { ...base, error: raw };
@@ -43970,6 +44139,7 @@ init_api();
43970
44139
  init_auth();
43971
44140
  init_config();
43972
44141
  init_colors();
44142
+ import { pipeline } from "stream/promises";
43973
44143
  var recordsCommand = new Command("records").description("Manage app records (Gipity Records - validated CRUD with audit history)");
43974
44144
  var ANON_FLAG = "--anon";
43975
44145
  var ANON_HELP = "Call as an anonymous visitor (the public path a signed-out user hits) instead of as your signed-in account";
@@ -43998,13 +44168,13 @@ recordsCommand.command("tables").description("List the tables exposed through Gi
43998
44168
  res.data,
43999
44169
  opts,
44000
44170
  "No tables configured for Records API. Configure one with `gipity records config <table> --auth <level>`.",
44001
- (t) => `${bold(t.table_name)} ${muted(t.auth_level)} ${muted(`pk=${t.primary_key_column}`)} ${muted(`db=${t.database_name}`)}`
44171
+ (t) => `${bold(t.table_name)} ${muted(t.auth_level)} ${muted(`pk=${t.primary_key_column}`)} ${muted(`db=${t.database_name}`)}${t.append_only ? ` ${muted("append-only")}` : ""}`
44002
44172
  );
44003
44173
  }));
44004
- recordsCommand.command("config <table>").description("Show or set a table's Records API config (auth level, search, auto-numbering, etc.)").addOption(new Option("--auth <level>", "Auth level: public (anonymous writes), user (any signed-in caller), or member (owner and project members only)").choices(["public", "member", "user"])).option("--searchable <bool>", "Enable full-text search (true/false)").option("--primary-key <col>", "Primary key column (default: id)").option("--soft-delete <col>", 'Soft-delete column (pass "none" to clear)').option("--auto-number <prefix>", 'Number new records automatically, e.g. INC -> INC0001001 (pass "none" to turn off). Same as auto_number in gipity.yaml').option("--auto-number-pad <n>", "Zero-pad width of the auto-number (default 7)").option("--auto-number-column <col>", "Column the auto-number is written to (default: number)").option("--json", "Output as JSON").action((table, opts) => run("Config", async () => {
44174
+ recordsCommand.command("config <table>").description("Show or set a table's Records API config (auth level, search, auto-numbering, etc.)").addOption(new Option("--auth <level>", "Auth level: public (anonymous writes), user (any signed-in caller), or member (owner and project members only)").choices(["public", "member", "user"])).option("--searchable <bool>", "Enable full-text search (true/false)").option("--primary-key <col>", "Primary key column (default: id)").option("--soft-delete <col>", 'Soft-delete column (pass "none" to clear)').option("--auto-number <prefix>", 'Number new records automatically, e.g. INC -> INC0001001 (pass "none" to turn off). Same as auto_number in gipity.yaml').option("--auto-number-pad <n>", "Zero-pad width of the auto-number (default 7)").option("--auto-number-column <col>", "Column the auto-number is written to (default: number)").option("--append-only", "Make the table inserts-only for good: updates, deletes and purges are refused for everyone, including raw SQL. Can't be undone. Same as append_only: true in gipity.yaml").option("--json", "Output as JSON").action((table, opts) => run("Config", async () => {
44005
44175
  const config = requireConfig2();
44006
44176
  const base = `/api/${config.projectGuid}/records/${table}/config`;
44007
- const setting = opts.auth || opts.searchable !== void 0 || opts.primaryKey || opts.softDelete || opts.autoNumber || opts.autoNumberPad || opts.autoNumberColumn;
44177
+ const setting = opts.auth || opts.searchable !== void 0 || opts.primaryKey || opts.softDelete || opts.autoNumber || opts.autoNumberPad || opts.autoNumberColumn || opts.appendOnly;
44008
44178
  if (!setting) {
44009
44179
  const res2 = await get(base);
44010
44180
  printResult(JSON.stringify(res2.data, null, 2), opts, res2.data);
@@ -44022,11 +44192,12 @@ recordsCommand.command("config <table>").description("Show or set a table's Reco
44022
44192
  body.auto_number_pad = pad;
44023
44193
  }
44024
44194
  if (opts.autoNumberColumn) body.auto_number_column = opts.autoNumberColumn;
44195
+ if (opts.appendOnly) body.append_only = true;
44025
44196
  const res = await patch(base, body);
44026
44197
  const d = res.data;
44027
44198
  const autoNumber = d.auto_number_prefix ? `${d.auto_number_prefix} (pad ${d.auto_number_pad}, column ${d.auto_number_column})` : "off";
44028
44199
  printResult(
44029
- `Configured "${table}": auth=${d.auth_level}, searchable=${d.searchable}, pk=${d.primary_key_column}, auto-number=${autoNumber}`,
44200
+ `Configured "${table}": auth=${d.auth_level}, searchable=${d.searchable}, pk=${d.primary_key_column}, auto-number=${autoNumber}${d.append_only ? ", append-only" : ""}`,
44030
44201
  opts,
44031
44202
  d
44032
44203
  );
@@ -44062,7 +44233,15 @@ recordsCommand.command("get <table> <id>").description("Get a record").option(AN
44062
44233
  const res = await api.get(`/api/${api.guid}/records/${table}/${id2}`);
44063
44234
  console.log(opts.json ? JSON.stringify(res.data) : JSON.stringify(res.data, null, 2));
44064
44235
  }));
44065
- recordsCommand.command("history <table> [id]").description("Audit history (who/what changed it, with English summaries). Omit <id> for the whole table's feed.").option("--limit <n>", "Max events", "20").option(ANON_FLAG, ANON_HELP).option("--json", "Output as JSON").action((table, id2, opts) => run("History", async () => {
44236
+ recordsCommand.command("history <table> [id]").description("Audit history (who/what changed it, with English summaries). Omit <id> for the whole table's feed.").option("--limit <n>", "Max events", "20").option("--jsonl", "Export the WHOLE table history to stdout as JSON Lines, oldest first (owner/editor; ignores --limit)").option(ANON_FLAG, ANON_HELP).option("--json", "Output as JSON").action((table, id2, opts) => run("History", async () => {
44237
+ if (opts.jsonl) {
44238
+ if (id2) throw new Error("--jsonl exports a whole table: drop the <id>");
44239
+ if (opts.anon) throw new Error("--jsonl needs the owner or an editor: drop --anon");
44240
+ const config = requireConfig2();
44241
+ const body = await downloadStream(`/api/${config.projectGuid}/records/${encodeURIComponent(table)}/history?format=jsonl`);
44242
+ await pipeline(body, process.stdout, { end: false });
44243
+ return;
44244
+ }
44066
44245
  const api = await recordsHttp(opts);
44067
44246
  const scope = id2 ? `${table}/${encodeURIComponent(id2)}` : table;
44068
44247
  const res = await api.get(
@@ -44284,7 +44463,7 @@ async function scopeQuery(opts) {
44284
44463
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
44285
44464
  return `scope=project&app_guid=${config.projectGuid}`;
44286
44465
  }
44287
- var secretsCommand = new Command("secrets").description("Manage app secrets").addHelpText("after", '\nEncrypted API keys and tokens for your app, read in functions via secrets.get("NAME").');
44466
+ var secretsCommand = new Command("secrets").description("Manage app secrets").addHelpText("after", '\nEncrypted API keys and tokens for your app, read in functions via secrets.get("NAME").\nValues are write-only: no command prints a stored value back.');
44288
44467
  secretsCommand.command("list").alias("ls").description("List secret names (never values). Project secrets by default; --account for account-wide").option("--account", "Account-wide secrets shared across all your projects").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((opts) => run("Secrets", async () => {
44289
44468
  const res = await get(`/secrets?${await scopeQuery(opts)}`);
44290
44469
  if (opts.json) {
@@ -44302,6 +44481,16 @@ secretsCommand.command("list").alias("ls").description("List secret names (never
44302
44481
  console.log(` ${s.name} ${masked} ${muted(`updated ${new Date(s.updated_at).toLocaleDateString()}`)}`);
44303
44482
  }
44304
44483
  }));
44484
+ secretsCommand.command("get <name>").description("Secret values are write-only: confirms the secret exists, never prints its value").option("--account", "Look in account-wide secrets").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((name, opts) => run("Secrets", async () => {
44485
+ const res = await get(`/secrets?${await scopeQuery(opts)}`);
44486
+ const scope = opts.account ? "account-wide" : "project";
44487
+ const found = res.data.find((s) => s.name === name);
44488
+ if (!found) throw new Error(`No ${scope} secret named '${name}'. Values are write-only, so set it with: gipity secrets set ${name} VALUE${opts.account ? " --account" : ""}`);
44489
+ const ends = found.preview ? ` (ends in ...${found.preview})` : "";
44490
+ throw new Error(
44491
+ `secret values are write-only and are never shown. '${name}' exists${ends}; only a deployed function can read it, with secrets.get('${name}'). To hand a value to another service too, generate it yourself, keep it, then store it: TOK=$(openssl rand -hex 24); gipity secrets set ${name} "$TOK"; echo "$TOK". Setting it again replaces the live value.`
44492
+ );
44493
+ }));
44305
44494
  secretsCommand.command("set <name> <value>").description("Create or update a secret (UPPER_SNAKE_CASE name). Encrypted at rest; never echoed back").option("--account", "Store account-wide (shared across all your projects)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((name, value, opts) => run("Secrets", async () => {
44306
44495
  const res = await put(`/secrets?${await scopeQuery(opts)}`, { name, value });
44307
44496
  if (opts.json) {
@@ -44960,7 +45149,7 @@ init_api();
44960
45149
  init_config();
44961
45150
  init_colors();
44962
45151
  var emailCommand = new Command("email").description("Test and inspect a deployed app's email() sends");
44963
- emailCommand.command("test").description("Send a test email through your app's email() path (owner-billed)").argument("<to>", "Recipient address").option("--subject <text>", "Subject", "Test email from Gipity").option("--text <text>", "Body text", "This is a test email sent through your app's email() service. \u2709\uFE0F").option("--reply-to <email>", "Reply-To address").option("--from-name <name>", "Sender display name (address stays gipity@gipity.ai)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((to2, opts) => run("Email", async () => {
45152
+ emailCommand.command("test").description("Send a test email through your app's email() path (owner-billed)").argument("<to>", "Recipient address, or 'owner' for the app owner's own account email").option("--subject <text>", "Subject", "Test email from Gipity").option("--text <text>", "Body text", "This is a test email sent through your app's email() service. \u2709\uFE0F").option("--reply-to <email>", "Reply-To address").option("--from-name <name>", "Sender display name (address stays gipity@gipity.ai)").option("--project <guid-or-slug>", "Target a specific project instead of cwd / Home").option("--json", "Output raw JSON").action((to2, opts) => run("Email", async () => {
44964
45153
  const { config } = await resolveProjectContext({ projectOverride: opts.project });
44965
45154
  const payload = { to: to2, subject: opts.subject, text: opts.text };
44966
45155
  if (opts.replyTo) payload.replyTo = opts.replyTo;
package/dist/knowledge.js CHANGED
@@ -56,7 +56,7 @@ You are the developer. Write files in this directory - Gipity's editor hooks (in
56
56
 
57
57
  ## Use first-party services before reaching outside
58
58
 
59
- 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.
59
+ 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; "email me when..." is \`email({ to: 'owner', ... })\`, which reaches the app owner with no address or secret; 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.
60
60
 
61
61
  ## Don't guess Gipity facts - look them up
62
62
 
@@ -110,7 +110,7 @@ mkdir -p ~/GipityProjects/<slug> && cd ~/GipityProjects/<slug> && gipity init <s
110
110
 
111
111
  ## CLI quick reference
112
112
 
113
- Key commands: \`gipity add <template|kit>\`, \`gipity brand set --emoji <e>|--color <hex>\` (regenerate the app's icons + social share card), \`gipity deploy [prod|<env>]\`, \`gipity env\` (list/create/delete environments), \`gipity sandbox run\`, \`gipity page inspect <url>\`, \`gipity page screenshot <url>\`, \`gipity db query "SQL"\`, \`gipity fn call <name>\`, \`gipity logs fn <name>\`, \`gipity secrets set <NAME> <value> [--account]\` (store an API key/token encrypted; read in functions via \`secrets.get('NAME')\` - never hardcode keys), \`gipity skill read <name>\`.
113
+ Key commands: \`gipity add <template|kit>\`, \`gipity brand set --emoji <e>|--color <hex>\` (regenerate the app's icons + social share card), \`gipity deploy [prod|<env>]\`, \`gipity env\` (list/create/delete environments), \`gipity sandbox run\`, \`gipity page inspect <url>\`, \`gipity page screenshot <url>\`, \`gipity db query "SQL"\`, \`gipity fn call <name>\`, \`gipity logs fn <name>\`, \`gipity secrets set <NAME> <value> [--account]\` (store an API key/token encrypted; read in functions via \`secrets.get('NAME')\`; write-only, so keep a copy of any value another service also needs - never hardcode keys), \`gipity skill read <name>\`.
114
114
  Rename for findability: \`gipity project rename <name>\` renames the current project's display name (the slug and deployed URLs never change); it's the label users scan in Monitor and \`gipity project\`, so keep it SHORT: 2-4 words, at most 40 characters, no trailing punctuation (e.g. "Stripe checkout", "Tetris game").
115
115
  Pull an existing remote project local (given its URL/slug): \`mkdir -p ~/GipityProjects/<slug> && cd ~/GipityProjects/<slug> && gipity init <slug>\` (adopts the matching project and syncs files down - this is the "clone").
116
116
  Move whole apps in/out: \`gipity save\` (export this project as a portable \`.gip\` bundle), \`gipity load <file.gip | github:owner/repo>\` (import as a NEW project; \`--inspect\` to preview), \`gipity github connect\` (1-2 click GitHub access for imports). Porting a Vercel/Replit/Lovable app? Load the \`app-import\` skill first.
@@ -174,6 +174,7 @@ Watch for **bulky output dirs dropped loose at the root** (e.g. \`out/\`, \`vsd_
174
174
  Run \`gipity skill list\` to see every skill. Run \`gipity skill read <name>\` to read one. Load the relevant skill before starting a task - they have the correct API patterns, code examples, and common mistakes.
175
175
 
176
176
  App services skills (load before calling \`/services/*\` endpoints):
177
+ - \`app-api-keys\` - project API keys for scripts/devices: gipity key create, scopes (functions, tables, files, ip)
177
178
  - \`app-audio\` - sound effects, music, transcription
178
179
  - \`app-auth\` - sign in: Gipity accounts or app-owned users (Google, email code), popup vs redirect
179
180
  - \`app-files\` - uploads, then displaying files and the storage helper (ownership check, delete)
@@ -209,7 +210,7 @@ Kit skills (reusable building blocks - \`gipity add <kit>\`):
209
210
  - \`leaderboard\` - game leaderboards: high scores or times, daily/weekly/monthly/season boards, tiebreaks, replays, cheat checks, bans
210
211
 
211
212
  Other key skills:
212
- - \`email\` - sending email from a deployed app with the email() service or a workflow notify step (no setup/keys), gipity email test/log, HTML formatting, images
213
+ - \`email\` - sending email from a deployed app with the email() service or a workflow notify step (no setup/keys; to: 'owner' emails you, the app owner), gipity email test/log, HTML formatting, images
213
214
  - \`sandbox-tools\` - cloud sandbox capabilities and pre-installed tools`;
214
215
  export const DEFINITION_OF_DONE = `## Definition of done (build tasks)
215
216
  1. \`gipity deploy\` succeeds and you have a live URL.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gipity",
3
- "version": "1.1.37",
3
+ "version": "1.1.39",
4
4
  "description": "The full-stack platform tuned for AI agents. Database, storage, auth, functions, deploy, and drop-in kits - all agent-tuned. Pair with Claude Code or use standalone.",
5
5
  "bin": {
6
6
  "gipity": "dist/updater/shim.js",
@@ -14,7 +14,7 @@
14
14
  "prepack": "npm run build",
15
15
  "dev": "tsc --watch",
16
16
  "test": "npm run test:smoke",
17
- "test:smoke": "npm run build && node --test dist/__tests__/utils.test.js dist/__tests__/template-vars.test.js dist/__tests__/platform.test.js dist/__tests__/colors.test.js dist/__tests__/config.test.js dist/__tests__/sync.test.js dist/__tests__/sync-apply.test.js dist/__tests__/sync-unretrievable.test.js dist/__tests__/sync-clean-check.test.js dist/__tests__/sync-lock.test.js dist/__tests__/auth-lock.test.js dist/__tests__/auth-refresh-timeout.test.js dist/__tests__/api-401-retry.test.js dist/__tests__/api-timeout.test.js dist/__tests__/api-error-body.test.js dist/__tests__/push-cas.test.js dist/__tests__/upload.test.js dist/__tests__/progress.test.js dist/__tests__/updater.test.js dist/__tests__/cli-smoke.test.js dist/__tests__/claude-noninteractive.test.js dist/__tests__/claude-trust.test.js dist/__tests__/claude-auth-status.test.js dist/__tests__/build-picker.test.js dist/__tests__/relay-state.test.js dist/__tests__/media-upload.test.js dist/__tests__/prompts.test.js dist/__tests__/capture-transcript.test.js dist/__tests__/capture-parsers.test.js dist/__tests__/agents.test.js dist/__tests__/capture-lock.test.js dist/__tests__/capture-resolve.test.js dist/__tests__/capture-metrics.test.js dist/__tests__/flag-aliases.test.js dist/__tests__/net.test.js dist/__tests__/client-context.test.js dist/__tests__/adopt-cwd.test.js dist/__tests__/cli-cmd-approval.test.js dist/__tests__/cli-cmd-audit.test.js dist/__tests__/cli-cmd-brand.test.js dist/__tests__/cli-cmd-bug.test.js dist/__tests__/cli-cmd-bug-queue.test.js dist/__tests__/cli-cmd-credits.test.js dist/__tests__/cli-cmd-account.test.js dist/__tests__/cli-cmd-db.test.js dist/__tests__/cli-cmd-db-checkpoint.test.js dist/__tests__/cli-cmd-deploy.test.js dist/__tests__/cli-cmd-env.test.js dist/__tests__/cli-cmd-domain.test.js dist/__tests__/cli-cmd-email.test.js dist/__tests__/cli-cmd-file.test.js dist/__tests__/cli-cmd-storage.test.js dist/__tests__/cli-cmd-fn.test.js dist/__tests__/cli-cmd-service.test.js dist/__tests__/cli-cmd-job.test.js dist/__tests__/cli-cmd-generate.test.js dist/__tests__/cli-cmd-ask.test.js dist/__tests__/cli-cmd-gmail.test.js dist/__tests__/cli-cmd-info.test.js dist/__tests__/cli-cmd-init.test.js dist/__tests__/cli-cmd-location.test.js dist/__tests__/cli-cmd-text.test.js dist/__tests__/cli-cmd-login.test.js dist/__tests__/cli-cmd-status.test.js dist/__tests__/cli-cmd-logout.test.js dist/__tests__/cli-cmd-token.test.js dist/__tests__/cli-cmd-key.test.js dist/__tests__/cli-cmd-logs.test.js dist/__tests__/cli-cmd-memory.test.js dist/__tests__/cli-cmd-page.test.js dist/__tests__/cli-cmd-plan.test.js dist/__tests__/cli-cmd-project.test.js dist/__tests__/cli-cmd-rbac.test.js dist/__tests__/cli-cmd-realtime.test.js dist/__tests__/cli-cmd-records.test.js dist/__tests__/cli-cmd-setup.test.js dist/__tests__/cli-cmd-doctor.test.js dist/__tests__/claude-setup.test.js dist/__tests__/cli-cmd-sandbox.test.js dist/__tests__/cli-cmd-add.test.js dist/__tests__/cli-cmd-remove.test.js dist/__tests__/cli-cmd-skill.test.js dist/__tests__/cli-cmd-test.test.js dist/__tests__/cli-cmd-workflow.test.js dist/__tests__/cli-cmd-push.test.js dist/__tests__/cli-cmd-uninstall.test.js dist/__tests__/tool-detection.test.js dist/__tests__/setup-skills-block.test.js dist/__tests__/setup-hooks.test.js dist/__tests__/setup-codex-hooks.test.js dist/__tests__/setup-agy-hooks.test.js dist/__tests__/trace.test.js",
17
+ "test:smoke": "npm run build && node --test dist/__tests__/utils.test.js dist/__tests__/template-vars.test.js dist/__tests__/platform.test.js dist/__tests__/colors.test.js dist/__tests__/config.test.js dist/__tests__/sync.test.js dist/__tests__/sync-apply.test.js dist/__tests__/sync-unretrievable.test.js dist/__tests__/sync-clean-check.test.js dist/__tests__/sync-lock.test.js dist/__tests__/auth-lock.test.js dist/__tests__/auth-refresh-timeout.test.js dist/__tests__/api-401-retry.test.js dist/__tests__/api-timeout.test.js dist/__tests__/api-error-body.test.js dist/__tests__/push-cas.test.js dist/__tests__/upload.test.js dist/__tests__/progress.test.js dist/__tests__/updater.test.js dist/__tests__/cli-smoke.test.js dist/__tests__/claude-noninteractive.test.js dist/__tests__/claude-trust.test.js dist/__tests__/claude-auth-status.test.js dist/__tests__/build-picker.test.js dist/__tests__/relay-state.test.js dist/__tests__/media-upload.test.js dist/__tests__/prompts.test.js dist/__tests__/capture-transcript.test.js dist/__tests__/capture-parsers.test.js dist/__tests__/agents.test.js dist/__tests__/capture-lock.test.js dist/__tests__/capture-resolve.test.js dist/__tests__/capture-metrics.test.js dist/__tests__/flag-aliases.test.js dist/__tests__/net.test.js dist/__tests__/client-context.test.js dist/__tests__/adopt-cwd.test.js dist/__tests__/cli-cmd-approval.test.js dist/__tests__/cli-cmd-audit.test.js dist/__tests__/cli-cmd-brand.test.js dist/__tests__/cli-cmd-bug.test.js dist/__tests__/cli-cmd-bug-queue.test.js dist/__tests__/cli-cmd-credits.test.js dist/__tests__/cli-cmd-account.test.js dist/__tests__/cli-cmd-db.test.js dist/__tests__/cli-cmd-db-checkpoint.test.js dist/__tests__/cli-cmd-deploy.test.js dist/__tests__/cli-cmd-env.test.js dist/__tests__/cli-cmd-domain.test.js dist/__tests__/cli-cmd-email.test.js dist/__tests__/cli-cmd-secrets.test.js dist/__tests__/cli-cmd-file.test.js dist/__tests__/cli-cmd-storage.test.js dist/__tests__/cli-cmd-fn.test.js dist/__tests__/cli-cmd-service.test.js dist/__tests__/cli-cmd-job.test.js dist/__tests__/cli-cmd-generate.test.js dist/__tests__/cli-cmd-ask.test.js dist/__tests__/cli-cmd-gmail.test.js dist/__tests__/cli-cmd-info.test.js dist/__tests__/cli-cmd-init.test.js dist/__tests__/cli-cmd-location.test.js dist/__tests__/cli-cmd-text.test.js dist/__tests__/cli-cmd-login.test.js dist/__tests__/cli-cmd-status.test.js dist/__tests__/cli-cmd-logout.test.js dist/__tests__/cli-cmd-token.test.js dist/__tests__/cli-cmd-key.test.js dist/__tests__/cli-cmd-logs.test.js dist/__tests__/cli-cmd-memory.test.js dist/__tests__/cli-cmd-page.test.js dist/__tests__/cli-cmd-plan.test.js dist/__tests__/cli-cmd-project.test.js dist/__tests__/cli-cmd-rbac.test.js dist/__tests__/cli-cmd-realtime.test.js dist/__tests__/cli-cmd-records.test.js dist/__tests__/cli-cmd-setup.test.js dist/__tests__/cli-cmd-doctor.test.js dist/__tests__/claude-setup.test.js dist/__tests__/cli-cmd-sandbox.test.js dist/__tests__/cli-cmd-add.test.js dist/__tests__/cli-cmd-remove.test.js dist/__tests__/cli-cmd-skill.test.js dist/__tests__/cli-cmd-test.test.js dist/__tests__/cli-cmd-workflow.test.js dist/__tests__/cli-cmd-push.test.js dist/__tests__/cli-cmd-uninstall.test.js dist/__tests__/tool-detection.test.js dist/__tests__/setup-skills-block.test.js dist/__tests__/setup-hooks.test.js dist/__tests__/setup-codex-hooks.test.js dist/__tests__/setup-agy-hooks.test.js dist/__tests__/trace.test.js",
18
18
  "test:relay": "npm run build && node --test dist/__tests__/relay-daemon.test.js dist/__tests__/session-pool.test.js dist/__tests__/relay-diagnostics.test.js dist/__tests__/relay-agent-updates.test.js dist/__tests__/relay-installers.test.js dist/__tests__/relay-bridge-abort.test.js dist/__tests__/relay-redact.test.js dist/__tests__/relay-machine-id.test.js dist/__tests__/stream-json.test.js dist/__tests__/ingest-queue.test.js dist/__tests__/stream-delta.test.js dist/__tests__/phase-tracker.test.js dist/__tests__/relay-ingest-contract.test.js dist/__tests__/cli-cmd-relay.test.js",
19
19
  "test:smoke:quick": "node scripts/smoke-quick.mjs",
20
20
  "test:e2e": "tsc && GIPITY_E2E=1 node --test --test-timeout=180000 dist/__tests__/cli-e2e-live.test.js dist/__tests__/cli-e2e-sync-live.test.js dist/__tests__/cli-e2e-sync-stress-live.test.js dist/__tests__/cli-e2e-rollback-live.test.js dist/__tests__/cli-e2e-services-media-live.test.js dist/__tests__/cli-e2e-workflow-live.test.js dist/__tests__/cli-e2e-sandbox-live.test.js dist/__tests__/cli-e2e-page-fetch-live.test.js dist/__tests__/cli-e2e-page-test-live.test.js dist/__tests__/cli-e2e-surface-live.test.js dist/__tests__/cli-e2e-account-live.test.js dist/__tests__/cli-e2e-envs-live.test.js",