@diafunc/cli 0.12.0 → 0.13.0

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.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-A4VM56MK.js";
3
+ } from "./chunk-TWJWXUZL.js";
4
4
 
5
5
  // src/index.ts
6
- import chalk37 from "chalk";
6
+ import chalk36 from "chalk";
7
7
 
8
8
  // src/commands/auth/login.ts
9
9
  import chalk4 from "chalk";
@@ -973,7 +973,7 @@ async function deviceCodeLogin(config, profile) {
973
973
  failure("Code expired before approval. Run `diafunc auth login` again.");
974
974
  process.exit(1);
975
975
  }
976
- failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? " \u2014 " + errorBody.error_description : ""}`);
976
+ failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? ": " + errorBody.error_description : ""}`);
977
977
  process.exit(1);
978
978
  }
979
979
  failure("Timed out waiting for approval.");
@@ -1210,6 +1210,18 @@ function formatDuration(millis) {
1210
1210
  const days = Math.floor(hours / 24);
1211
1211
  return `${days}d ${hours % 24}h`;
1212
1212
  }
1213
+ function formatDurationPrecise(millis) {
1214
+ const total = Math.max(0, Math.trunc(millis));
1215
+ const days = Math.floor(total / 864e5);
1216
+ const hours = Math.floor(total / 36e5) % 24;
1217
+ const minutes = Math.floor(total / 6e4) % 60;
1218
+ const seconds = Math.floor(total / 1e3) % 60;
1219
+ if (days > 0) return hours > 0 ? `${days} d ${hours} h` : `${days} d`;
1220
+ if (hours > 0) return minutes > 0 ? `${hours} h ${minutes} min` : `${hours} h`;
1221
+ if (minutes > 0) return `${minutes} min`;
1222
+ if (seconds > 0) return `${seconds} sec`;
1223
+ return `${total} ms`;
1224
+ }
1213
1225
  var GOOD_STATES = /* @__PURE__ */ new Set([
1214
1226
  "COMPLETED",
1215
1227
  "SUCCEEDED",
@@ -2760,7 +2772,7 @@ function registerTokenCommands(parent) {
2760
2772
  console.log(` Name: ${result.name}`);
2761
2773
  console.log(` Expires: ${result.expiresAt}`);
2762
2774
  console.log();
2763
- console.log(chalk8.yellow("Save this token \u2014 it will not be shown again."));
2775
+ console.log(chalk8.yellow("Save this token. It will not be shown again."));
2764
2776
  } else {
2765
2777
  format(result, { format: outputFormat });
2766
2778
  }
@@ -3236,7 +3248,7 @@ async function pollUntilFinished(storage, projectId, projectBranch, bundleId, in
3236
3248
  status.stop();
3237
3249
  }
3238
3250
  throw new Error(
3239
- `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)} \u2014 check it with 'diafunc notebook bundles ${projectId}'`
3251
+ `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)}. Check it with 'diafunc notebook bundles ${projectId}'.`
3240
3252
  );
3241
3253
  }
3242
3254
  function progressLine(label, progress, elapsedMs) {
@@ -3265,6 +3277,28 @@ async function resolveLanguage(api, projectId, explicit) {
3265
3277
  return DEFAULT_FUNCTION_LANGUAGE;
3266
3278
  }
3267
3279
 
3280
+ // src/util/project-names.ts
3281
+ var FIRST_PAGE = 100;
3282
+ var CONCURRENCY = 8;
3283
+ async function projectNames(api, projectIds) {
3284
+ const wanted = new Set(projectIds);
3285
+ const names = /* @__PURE__ */ new Map();
3286
+ if (wanted.size === 0) return names;
3287
+ const take = (items) => {
3288
+ for (const item of items) {
3289
+ if (item.contentType !== "project" || !item.name || !wanted.has(item.projectId)) continue;
3290
+ if (!names.has(item.projectId)) names.set(item.projectId, item.name);
3291
+ }
3292
+ };
3293
+ take((await api.index.searchPage({ query: "*", contentType: "project", limit: FIRST_PAGE })).items);
3294
+ const missing = [...wanted].filter((id) => !names.has(id));
3295
+ for (let i = 0; i < missing.length; i += CONCURRENCY) {
3296
+ const pages = await Promise.all(missing.slice(i, i + CONCURRENCY).map((projectId) => api.index.searchPage({ query: "*", contentType: "project", projectId, projectBranch: "main", limit: 5 }).catch(() => null)));
3297
+ for (const page of pages) if (page) take(page.items);
3298
+ }
3299
+ return names;
3300
+ }
3301
+
3268
3302
  // src/commands/project/index.ts
3269
3303
  function getOutputFormat(cmd) {
3270
3304
  const config = loadConfig();
@@ -3282,9 +3316,6 @@ Examples:
3282
3316
  $ diafunc project list the twenty most recent
3283
3317
  $ diafunc project list --limit 0 every one of them
3284
3318
  $ diafunc search "housing" --type project find a project by name
3285
-
3286
- A project's name lives on its main entity rather than on the project row, so this listing shows
3287
- ids. Use 'diafunc search --type project' when you know the name but not the id.
3288
3319
  `).action(async (options, cmd) => {
3289
3320
  try {
3290
3321
  const outputFormat = getOutputFormat(cmd);
@@ -3292,9 +3323,17 @@ ids. Use 'diafunc search --type project' when you know the name but not the id.
3292
3323
  const projects = options.all ? await api.admin.getAllProjects() : await api.admin.getProjects();
3293
3324
  const limit = Number.parseInt(options.limit, 10);
3294
3325
  const capped = Number.isFinite(limit) && limit > 0 ? projects.slice(0, limit) : projects;
3295
- format(capped, {
3326
+ let names = /* @__PURE__ */ new Map();
3327
+ try {
3328
+ names = await projectNames(api, capped.map((p) => p.projectId));
3329
+ } catch {
3330
+ console.error(chalk12.dim("Project names are unavailable right now; showing ids."));
3331
+ }
3332
+ const rows = capped.map((p) => ({ name: names.get(p.projectId) ?? null, ...p }));
3333
+ format(rows, {
3296
3334
  format: outputFormat,
3297
3335
  columns: [
3336
+ { key: "name" },
3298
3337
  { key: "projectId", kind: "id" },
3299
3338
  { key: "teamName", header: "team" },
3300
3339
  { key: "visibility" },
@@ -3305,7 +3344,7 @@ ids. Use 'diafunc search --type project' when you know the name but not the id.
3305
3344
  ]
3306
3345
  });
3307
3346
  if (capped.length < projects.length) {
3308
- console.log(chalk12.dim(
3347
+ console.error(chalk12.dim(
3309
3348
  `
3310
3349
  Showing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`
3311
3350
  ));
@@ -4419,6 +4458,77 @@ Examples:
4419
4458
  import chalk15 from "chalk";
4420
4459
  import * as fs4 from "fs";
4421
4460
  import * as path3 from "path";
4461
+
4462
+ // src/util/table-window.ts
4463
+ var WINDOW_MAX_ROWS = 100;
4464
+ var WINDOW_MAX_COLUMNS = 50;
4465
+ var WINDOW_MAX_CELLS = 2e3;
4466
+ function decodeLongAttribute(value) {
4467
+ if (!value) return null;
4468
+ const bytes = Buffer.from(value, "base64");
4469
+ if (bytes.length !== 8) return null;
4470
+ const decoded = bytes.readBigInt64BE(0);
4471
+ return decoded >= 0n && decoded <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(decoded) : null;
4472
+ }
4473
+ function tableDimensions(entity) {
4474
+ return {
4475
+ rows: decodeLongAttribute(entity.attributes?.rows) ?? 0,
4476
+ columns: decodeLongAttribute(entity.attributes?.columns) ?? 0
4477
+ };
4478
+ }
4479
+ function defaultWindow(rows, columns) {
4480
+ const shownColumns = Math.min(columns, WINDOW_MAX_COLUMNS);
4481
+ const budgeted = Math.max(1, Math.floor(WINDOW_MAX_CELLS / Math.max(1, shownColumns)));
4482
+ const shownRows = Math.min(rows, WINDOW_MAX_ROWS, budgeted);
4483
+ return { rows: { from: 0, to: shownRows }, columns: { from: 0, to: shownColumns } };
4484
+ }
4485
+ function parseRange(text2, size, label) {
4486
+ const noun = label === "Row" ? "rows" : "columns";
4487
+ const match = /^\s*(\d*)\s*:\s*(\d*)\s*$/.exec(text2);
4488
+ if (!match || match[1] === "" && match[2] === "") {
4489
+ throw new CliError(`${label} range "${text2}" is not two numbers like 0:10.`, { exitCode: EXIT_USAGE });
4490
+ }
4491
+ const from = match[1] === "" ? 0 : Number(match[1]);
4492
+ const to = match[2] === "" ? size : Math.min(Number(match[2]), size);
4493
+ if (from >= size) {
4494
+ throw new CliError(`${label} range "${text2}" starts past the table, which has ${size} ${noun}.`, { exitCode: EXIT_USAGE });
4495
+ }
4496
+ if (to <= from) {
4497
+ throw new CliError(`${label} range "${text2}" selects no ${noun}.`, { exitCode: EXIT_USAGE });
4498
+ }
4499
+ return { from, to };
4500
+ }
4501
+ function cellRange(window) {
4502
+ return {
4503
+ fromRowIndex: window.rows.from,
4504
+ toRowIndex: window.rows.to - 1,
4505
+ fromColumnIndex: window.columns.from,
4506
+ toColumnIndex: window.columns.to - 1
4507
+ };
4508
+ }
4509
+ function describeWindow(window, rows, columns) {
4510
+ const whole = window.rows.from === 0 && window.rows.to === rows && window.columns.from === 0 && window.columns.to === columns;
4511
+ const line = `Rows ${window.rows.from}\u2013${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from}\u2013${window.columns.to - 1} of ${columns}`;
4512
+ return whole ? line : `${line} \xB7 use --rows/--cols for more`;
4513
+ }
4514
+ function decodeCellValue(value, type) {
4515
+ if (!value) return "";
4516
+ const bytes = Buffer.from(value, "base64");
4517
+ switch (type) {
4518
+ case "integer":
4519
+ if (bytes.length === 8) return bytes.readBigInt64BE(0).toString();
4520
+ break;
4521
+ case "number":
4522
+ if (bytes.length === 8) return String(bytes.readDoubleBE(0));
4523
+ break;
4524
+ case "bool":
4525
+ if (bytes.length === 1) return bytes[0] !== 0 ? "true" : "false";
4526
+ break;
4527
+ }
4528
+ return bytes.toString("utf-8");
4529
+ }
4530
+
4531
+ // src/commands/table/index.ts
4422
4532
  function getOutputFormat7(cmd) {
4423
4533
  const config = loadConfig();
4424
4534
  const globalOpts = cmd.optsWithGlobals();
@@ -4450,26 +4560,30 @@ Examples:
4450
4560
  $ diafunc table import-formats what can be loaded
4451
4561
  `);
4452
4562
  ;
4453
- table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Row range (e.g., 0:10)").option("--cols <range>", "Column range (e.g., 0:5)").action(async (ref, options, cmd) => {
4563
+ table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Rows to show, half-open: 0:10 is the first ten, 6490: runs to the end (default: up to 100)").option("--cols <range>", "Columns to show, half-open: 0:5 is the first five (default: up to 50)").action(async (ref, options, cmd) => {
4454
4564
  try {
4455
4565
  const outputFormat = getOutputFormat7(cmd);
4456
4566
  const overrides = getOverrides6(cmd);
4457
4567
  const resolved = parseEntityReference(ref, overrides);
4458
4568
  const api = createApiClient();
4459
- const request = {};
4460
- if (options.rows) {
4461
- const [from, to] = options.rows.split(":").map(Number);
4462
- if (!isNaN(from)) request.fromRow = from;
4463
- if (!isNaN(to)) request.toRow = to;
4464
- }
4465
- if (options.cols) {
4466
- const [from, to] = options.cols.split(":").map(Number);
4467
- if (!isNaN(from)) request.fromColumn = from;
4468
- if (!isNaN(to)) request.toColumn = to;
4569
+ const { rows: totalRows, columns: totalColumns } = tableDimensions(await api.storage.getEntity(resolved, false));
4570
+ if (totalRows === 0 || totalColumns === 0) {
4571
+ if (outputFormat === "json") {
4572
+ format({ rows: [], columns: [], cells: [], totalRows, totalColumns, window: null }, { format: outputFormat });
4573
+ } else {
4574
+ console.log(chalk15.dim("Empty table."));
4575
+ }
4576
+ return;
4469
4577
  }
4470
- const snapshot = await api.storage.getTableSnapshot(resolved, request);
4578
+ const initial = defaultWindow(totalRows, totalColumns);
4579
+ const window = {
4580
+ rows: options.rows ? parseRange(options.rows, totalRows, "Row") : initial.rows,
4581
+ columns: options.cols ? parseRange(options.cols, totalColumns, "Column") : initial.columns
4582
+ };
4583
+ const snapshot = await api.storage.getTableSnapshot(resolved, { cellRanges: [cellRange(window)] });
4471
4584
  if (outputFormat === "json") {
4472
- format(snapshot, { format: outputFormat });
4585
+ const cells = snapshot.cells.map((cell3) => ({ ...cell3, text: decodeCellValue(cell3.value, cell3.type) }));
4586
+ format({ ...snapshot, cells, totalRows, totalColumns, window }, { format: outputFormat });
4473
4587
  return;
4474
4588
  }
4475
4589
  const colMap = new Map(snapshot.columns.map((c) => [c.index, c]));
@@ -4477,7 +4591,7 @@ Examples:
4477
4591
  const colNames = sortedCols.map((c) => c.name || `col${c.index}`);
4478
4592
  const cellMap = /* @__PURE__ */ new Map();
4479
4593
  for (const cell3 of snapshot.cells) {
4480
- cellMap.set(`${cell3.rowIndex}:${cell3.columnIndex}`, cell3.value ?? "");
4594
+ cellMap.set(`${cell3.rowIndex}:${cell3.columnIndex}`, decodeCellValue(cell3.value, cell3.type));
4481
4595
  }
4482
4596
  const sortedRows = [...snapshot.rows].sort((a, b) => a.index - b.index);
4483
4597
  const tableData = sortedRows.map((row2) => {
@@ -4493,14 +4607,14 @@ Examples:
4493
4607
  console.log(colNames.map((c) => row2[c] ?? "").join(" "));
4494
4608
  }
4495
4609
  } else {
4496
- console.log(chalk15.dim(`${snapshot.rows.length} rows \xD7 ${snapshot.columns.length} columns`));
4497
- format(tableData, { format: outputFormat, columns: colNames });
4610
+ format(tableData, { format: outputFormat, columns: colNames.map((name) => ({ key: name, header: name })) });
4611
+ console.log(chalk15.dim(describeWindow(window, totalRows, totalColumns)));
4498
4612
  }
4499
4613
  } catch (error) {
4500
4614
  handleError(error);
4501
4615
  }
4502
4616
  });
4503
- table.command("import").description("Import data from a file (any supported format \u2014 see `table import-formats`)").argument("<ref>", "Table entity reference").argument("<file>", "File to import").option("--selection <id>", "Pin a sheet / inner-table id for multi-table sources (Excel sheets, SQLite tables, archive entries)").action(async (ref, file, options, cmd) => {
4617
+ table.command("import").description("Import data from a file (any supported format; see `table import-formats`)").argument("<ref>", "Table entity reference").argument("<file>", "File to import").option("--selection <id>", "Pin a sheet / inner-table id for multi-table sources (Excel sheets, SQLite tables, archive entries)").action(async (ref, file, options, cmd) => {
4504
4618
  try {
4505
4619
  const overrides = getOverrides6(cmd);
4506
4620
  const resolved = parseEntityReference(ref, overrides);
@@ -4541,7 +4655,7 @@ Examples:
4541
4655
  status.stop();
4542
4656
  }
4543
4657
  failure(`Import ${importId} is still running after ${formatDuration(pollInterval * maxAttempts)}.`);
4544
- hint(`It continues on the server \u2014 re-check with 'diafunc table view ${ref}'.`);
4658
+ hint(`It continues on the server. Check again with 'diafunc table view ${ref}'.`);
4545
4659
  process.exit(EXIT_FAILURE);
4546
4660
  } catch (error) {
4547
4661
  handleError(error);
@@ -4582,7 +4696,7 @@ Examples:
4582
4696
  handleError(error);
4583
4697
  }
4584
4698
  });
4585
- table.command("export").description("Export table data in any supported format (see `table export-formats`)").argument("<ref>", "Table entity reference").argument("<format>", "Export format (csv, tsv, excel, parquet, arrow, orc, avro, json, jsonl, yaml, xml, html, pdf, sqlite, duckdb, hdf5, netcdf, ...)").option("--out <file>", "Output file").option("--compression <algorithm>", "Compression wrapper: gzip, bzip2, xz, or zstd").option("--archive <algorithm>", "Archive wrapper: zip or tar").option("--rows <range>", "Row range (e.g., 0:1000) \u2014 half-open").option("--cols <range>", "Column range (e.g., 0:5) \u2014 half-open").option("--delimiter <char>", "CSV/TSV only: single-character delimiter override").option("--quote <char>", 'CSV/TSV only: quote character (use "" for empty)').option("--null <token>", 'CSV/TSV only: null token (default "?")').option("--no-quote-all", "CSV/TSV only: only quote fields when necessary (default quotes every field)").option("--async", "Queue an async export (with progress + later re-download) instead of streaming directly to disk", false).action(async (ref, fmt, options, cmd) => {
4699
+ table.command("export").description("Export table data in any supported format (see `table export-formats`)").argument("<ref>", "Table entity reference").argument("<format>", "Export format (csv, tsv, excel, parquet, arrow, orc, avro, json, jsonl, yaml, xml, html, pdf, sqlite, duckdb, hdf5, netcdf, ...)").option("--out <file>", "Output file").option("--compression <algorithm>", "Compression wrapper: gzip, bzip2, xz, or zstd").option("--archive <algorithm>", "Archive wrapper: zip or tar").option("--rows <range>", "Row range, half-open (e.g. 0:1000)").option("--cols <range>", "Column range, half-open (e.g. 0:5)").option("--delimiter <char>", "CSV/TSV only: single-character delimiter override").option("--quote <char>", 'CSV/TSV only: quote character (use "" for empty)').option("--null <token>", 'CSV/TSV only: null token (default "?")').option("--no-quote-all", "CSV/TSV only: only quote fields when necessary (default quotes every field)").option("--async", "Queue an async export (with progress + later re-download) instead of streaming directly to disk", false).action(async (ref, fmt, options, cmd) => {
4586
4700
  try {
4587
4701
  const overrides = getOverrides6(cmd);
4588
4702
  const resolved = parseEntityReference(ref, overrides);
@@ -4709,7 +4823,7 @@ Examples:
4709
4823
  }
4710
4824
  if (exp.finished === null) {
4711
4825
  const pct = Math.round((exp.progress ?? 0) * 100);
4712
- console.log(chalk15.dim(`Export in progress: ${pct}% \u2014 check again later.`));
4826
+ console.log(chalk15.dim(`Export in progress: ${pct}%. Check again later.`));
4713
4827
  return;
4714
4828
  }
4715
4829
  if (!exp.succeeded) {
@@ -5855,7 +5969,7 @@ var HELP = [
5855
5969
  ];
5856
5970
  async function runChatRepl(options) {
5857
5971
  const { input: promptInput } = await import("@inquirer/prompts");
5858
- const { getUpdateNotice } = await import("./update-check-SNH7P32S.js");
5972
+ const { getUpdateNotice } = await import("./update-check-V23VUFO4.js");
5859
5973
  let sessionId = options.session;
5860
5974
  let lastReportedSession;
5861
5975
  console.log(chalk19.bold("Diafunc chat") + chalk19.dim(" \xB7 /help for commands, /quit to exit"));
@@ -6168,14 +6282,14 @@ Examples:
6168
6282
  projectBranch: projectId ? overrides.branch ?? config.defaults.branch ?? "main" : null
6169
6283
  });
6170
6284
  const items = dedupe(page.items);
6171
- if (items.length === 0) {
6172
- empty("matches", { format: outputFormat });
6173
- return;
6174
- }
6175
6285
  if (outputFormat === "json") {
6176
6286
  format({ ...page, items }, { format: outputFormat });
6177
6287
  return;
6178
6288
  }
6289
+ if (items.length === 0) {
6290
+ empty("matches", { format: outputFormat });
6291
+ return;
6292
+ }
6179
6293
  if (isInteractive()) {
6180
6294
  renderResults(items);
6181
6295
  } else {
@@ -6190,7 +6304,7 @@ Examples:
6190
6304
  });
6191
6305
  }
6192
6306
  if (page.nextCursor && isInteractive()) {
6193
- console.log(chalk20.dim(`More results available \u2014 raise --limit to see them.`));
6307
+ console.log(chalk20.dim(`More results available. Raise --limit to see them.`));
6194
6308
  }
6195
6309
  } catch (error) {
6196
6310
  handleError(error);
@@ -6626,7 +6740,6 @@ Examples:
6626
6740
  }
6627
6741
 
6628
6742
  // src/commands/analyze/index.ts
6629
- import chalk26 from "chalk";
6630
6743
  import * as fs8 from "fs";
6631
6744
  import * as path7 from "path";
6632
6745
  import { spawn as spawn2 } from "child_process";
@@ -6644,22 +6757,79 @@ var RUN_PHASE_LABELS = {
6644
6757
  WRITING: "Writing the report"
6645
6758
  };
6646
6759
 
6647
- // src/commands/analyze/watch-view.ts
6648
- var PHASE_ORDER = ["QUEUED", "PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
6649
- function overallProgress(run) {
6650
- if (run.overallFraction !== null && run.overallFraction !== void 0) return run.overallFraction;
6651
- if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;
6652
- return null;
6653
- }
6760
+ // src/commands/analyze/copy.ts
6761
+ var RUN_STEPS = ["PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
6762
+ var STARTING = "Starting";
6654
6763
  function phaseLabel(run) {
6764
+ if (run.state === "QUEUED") return RUN_PHASE_LABELS.QUEUED;
6765
+ if (run.state === "DISPATCHING") return STARTING;
6655
6766
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
6767
+ if (run.state === "RUNNING" && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;
6656
6768
  return run.state.charAt(0) + run.state.slice(1).toLowerCase();
6657
6769
  }
6658
6770
  function stepCounter(run) {
6659
6771
  if (!run.phase) return null;
6660
- const index = PHASE_ORDER.indexOf(run.phase);
6772
+ const index = RUN_STEPS.indexOf(run.phase);
6661
6773
  if (index < 0) return null;
6662
- return `step ${index + 1} of ${PHASE_ORDER.length}`;
6774
+ return `step ${index + 1} of ${RUN_STEPS.length}`;
6775
+ }
6776
+ function runPhaseCell(run) {
6777
+ if (run.state === "COMPLETED") return null;
6778
+ if (run.state === "QUEUED" || run.state === "DISPATCHING") return phaseLabel(run);
6779
+ if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
6780
+ return null;
6781
+ }
6782
+ function latestRunSentence(state) {
6783
+ switch (state) {
6784
+ case "COMPLETED":
6785
+ return "The latest run has already completed.";
6786
+ case "FAILED":
6787
+ return "The latest run failed.";
6788
+ case "CANCELLED":
6789
+ return "The latest run was cancelled.";
6790
+ case "QUEUED":
6791
+ return "The latest run is waiting for a slot.";
6792
+ case "DISPATCHING":
6793
+ return "The latest run is starting.";
6794
+ default:
6795
+ return "The latest run is in progress.";
6796
+ }
6797
+ }
6798
+ function cancelSentence(run) {
6799
+ switch (run.state) {
6800
+ case "CANCELLED":
6801
+ return `Cancelled run ${run.runId}.`;
6802
+ case "COMPLETED":
6803
+ return `Run ${run.runId} had already completed.`;
6804
+ case "FAILED":
6805
+ return `Run ${run.runId} had already failed.`;
6806
+ default:
6807
+ return `Run ${run.runId} is still ${phaseLabel(run).toLowerCase()}.`;
6808
+ }
6809
+ }
6810
+ function terminalSentence(state, duration) {
6811
+ switch (state) {
6812
+ case "COMPLETED":
6813
+ return `Analysis completed in ${duration}.`;
6814
+ case "CANCELLED":
6815
+ return `Analysis cancelled after ${duration}.`;
6816
+ default:
6817
+ return `Analysis failed after ${duration}.`;
6818
+ }
6819
+ }
6820
+
6821
+ // src/commands/analyze/watch-view.ts
6822
+ function overallProgress(run) {
6823
+ if (run.overallFraction !== null && run.overallFraction !== void 0) return run.overallFraction;
6824
+ if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;
6825
+ return null;
6826
+ }
6827
+ function remainingCeiling(run, budgetHours) {
6828
+ if (run.phase !== "DISCOVERING") return null;
6829
+ if (budgetHours === null || !Number.isFinite(budgetHours) || budgetHours <= 0) return null;
6830
+ const fraction = run.phaseFraction;
6831
+ if (fraction === null || fraction === void 0) return null;
6832
+ return Math.max(0, budgetHours * 36e5 * (1 - Math.max(0, Math.min(fraction, 1))));
6663
6833
  }
6664
6834
  function phaseDetail(run) {
6665
6835
  const parts = [];
@@ -6668,7 +6838,7 @@ function phaseDetail(run) {
6668
6838
  parts.push(`generation ${formatNumber(run.fitGeneration)}`);
6669
6839
  }
6670
6840
  if (run.fitQuality !== null && run.fitQuality !== void 0) {
6671
- parts.push(`quality ${run.fitQuality.toPrecision(4)}`);
6841
+ parts.push(`quality ${Math.floor(Math.max(0, Math.min(run.fitQuality, 1)) * 100)}%`);
6672
6842
  }
6673
6843
  if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== void 0) {
6674
6844
  parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);
@@ -6682,7 +6852,7 @@ function phaseDetail(run) {
6682
6852
  return parts.length > 0 ? parts.join(" \xB7 ") : null;
6683
6853
  }
6684
6854
  function renderWatchBlock(input) {
6685
- const { run, elapsedMs, caption } = input;
6855
+ const { run, elapsedMs, caption, budgetHours } = input;
6686
6856
  const lines = [];
6687
6857
  const step = stepCounter(run);
6688
6858
  const headline = [
@@ -6692,30 +6862,24 @@ function renderWatchBlock(input) {
6692
6862
  ].filter(Boolean).join(" ");
6693
6863
  lines.push(` ${headline}`);
6694
6864
  const fraction = overallProgress(run);
6695
- const elapsed = chalk24.dim(formatDuration(elapsedMs));
6865
+ const elapsed = chalk24.dim(formatDurationPrecise(elapsedMs));
6696
6866
  if (fraction === null) {
6697
6867
  lines.push(` ${chalk24.dim("working")} ${elapsed}`);
6698
6868
  } else {
6699
- const eta = estimateRemaining(fraction, elapsedMs);
6869
+ const ceiling = remainingCeiling(run, budgetHours);
6700
6870
  lines.push(
6701
- ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (eta ? chalk24.dim(` \xB7 ~${formatDuration(eta)} left`) : "")
6871
+ ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk24.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
6702
6872
  );
6703
6873
  }
6704
6874
  const detail2 = caption ?? phaseDetail(run);
6705
6875
  if (detail2) lines.push(` ${chalk24.dim(detail2)}`);
6706
6876
  if (run.retryAttempts && run.retryAttempts > 0) {
6707
6877
  lines.push(` ${chalk24.yellow("!")} ${chalk24.dim(
6708
- `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption \u2014 progress restarts from the beginning`
6878
+ `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
6709
6879
  )}`);
6710
6880
  }
6711
6881
  return lines;
6712
6882
  }
6713
- function estimateRemaining(fraction, elapsedMs) {
6714
- if (fraction <= 0.02 || fraction >= 1 || elapsedMs < 3e4) return null;
6715
- const total = elapsedMs / fraction;
6716
- const remaining = total - elapsedMs;
6717
- return remaining > 0 ? remaining : null;
6718
- }
6719
6883
 
6720
6884
  // src/commands/analyze/wizard.ts
6721
6885
  import chalk25 from "chalk";
@@ -6795,7 +6959,7 @@ async function promptRunFields(prompter, options) {
6795
6959
  if (named.length > 0) {
6796
6960
  const preselected = new Set(defaultTargets(named));
6797
6961
  targets = await prompter.checkbox({
6798
- message: "Target variables: what should the analysis predict?",
6962
+ message: "Target columns: what should the analysis predict?",
6799
6963
  choices: named.map((c) => ({
6800
6964
  name: c.valueType ? `${c.name} ${chalk25.dim(`(${c.valueType})`)}` : c.name,
6801
6965
  value: c.name,
@@ -6867,7 +7031,7 @@ async function promptRunFields(prompter, options) {
6867
7031
  }
6868
7032
  if (hours === void 0) {
6869
7033
  hours = await prompter.input({
6870
- message: "Computation time in hours",
7034
+ message: "Computation time (hours)",
6871
7035
  default: DEFAULT_HOURS,
6872
7036
  validate: positiveNumber("Computation time")
6873
7037
  });
@@ -7024,13 +7188,18 @@ function parseCsv(value) {
7024
7188
  function parseVisibility(value) {
7025
7189
  const upper = value.toUpperCase();
7026
7190
  if (upper !== "PRIVATE" && upper !== "PUBLIC") {
7027
- throw new Error(`Invalid visibility "${value}" \u2014 must be PRIVATE or PUBLIC.`);
7191
+ throw new Error(`Invalid visibility "${value}". Use PRIVATE or PUBLIC.`);
7028
7192
  }
7029
7193
  return upper;
7030
7194
  }
7031
7195
  function isTerminalState(state) {
7032
7196
  return state === "COMPLETED" || state === "FAILED" || state === "CANCELLED";
7033
7197
  }
7198
+ function budgetHoursOf(hours) {
7199
+ if (hours === null || hours === void 0) return null;
7200
+ const parsed = Number(hours);
7201
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
7202
+ }
7034
7203
  function multipartFromFile(file) {
7035
7204
  const buffer = fs8.readFileSync(file);
7036
7205
  const blob = new Blob([buffer]);
@@ -7055,6 +7224,7 @@ async function runAnalysis(file, options, cmd) {
7055
7224
  const opt = await api.analysis.getPreset(options.preset);
7056
7225
  if (!opt.preset) {
7057
7226
  failure(`Preset not found: ${options.preset}`);
7227
+ hint(`List your presets with 'diafunc analyze presets list'.`);
7058
7228
  process.exit(EXIT_FAILURE);
7059
7229
  }
7060
7230
  const p = opt.preset;
@@ -7099,20 +7269,22 @@ async function runAnalysis(file, options, cmd) {
7099
7269
  `Uploading ${path7.basename(file)}`,
7100
7270
  () => api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file))
7101
7271
  );
7272
+ let runHours = request.hours;
7102
7273
  if (interactive) {
7103
- const configured = await configureInteractively(api, prompter, created.analysisId, request, {
7274
+ const configuredHours = await configureInteractively(api, prompter, created.analysisId, request, {
7104
7275
  targets: options.targets === void 0 ? void 0 : parseCsv(options.targets),
7105
7276
  segment: options.segment,
7106
7277
  questions: options.questions === void 0 ? void 0 : parseCsv(options.questions),
7107
7278
  hours: options.hours,
7108
7279
  budget: options.budget
7109
7280
  });
7110
- if (!configured) return;
7281
+ if (configuredHours === null) return;
7282
+ runHours = configuredHours;
7111
7283
  }
7112
7284
  const run = await withStatus("Queuing analysis run", () => api.analysis.runAnalysis(created.analysisId));
7113
7285
  detail(`runId: ${run.runId}`);
7114
7286
  console.log();
7115
- await monitorRun(api, created.analysisId, run.runId, cmd);
7287
+ await monitorRun(api, created.analysisId, run.runId, budgetHoursOf(runHours), cmd);
7116
7288
  }
7117
7289
  async function configureInteractively(api, prompter, analysisId, recipe, supplied) {
7118
7290
  const columns = await readColumns(api, analysisId);
@@ -7140,9 +7312,9 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
7140
7312
  if (!await prompter.confirm({ message: "Start the analysis?", default: true })) {
7141
7313
  warn("Not started. The analysis and these settings are saved.");
7142
7314
  hint(`Start it later with 'diafunc analyze rerun ${analysisId}'.`);
7143
- return false;
7315
+ return null;
7144
7316
  }
7145
- return true;
7317
+ return answers.hours;
7146
7318
  }
7147
7319
  async function readColumns(api, analysisId) {
7148
7320
  for (let attempt = 0; attempt < COLUMN_READ_ATTEMPTS; attempt++) {
@@ -7163,7 +7335,7 @@ async function readPresets(api) {
7163
7335
  return [];
7164
7336
  }
7165
7337
  }
7166
- async function monitorRun(api, analysisId, runId, cmd) {
7338
+ async function monitorRun(api, analysisId, runId, budgetHours, cmd) {
7167
7339
  const config = loadConfig();
7168
7340
  const outputFormat = getOutputFormat15(cmd);
7169
7341
  const human = outputFormat === "human";
@@ -7204,7 +7376,7 @@ async function monitorRun(api, analysisId, runId, cmd) {
7204
7376
  }
7205
7377
  const startedAt = run.startedAt ?? run.submittedAt ?? Date.now();
7206
7378
  if (human) {
7207
- status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption }));
7379
+ status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption, budgetHours }));
7208
7380
  } else {
7209
7381
  const snapshot = JSON.stringify({
7210
7382
  type: "progress",
@@ -7247,16 +7419,17 @@ async function reportTerminalRun(api, config, run, analysisId, runId, outputForm
7247
7419
  return;
7248
7420
  }
7249
7421
  console.log();
7422
+ const sentence = terminalSentence(run.state, formatDurationPrecise(durationMs));
7250
7423
  if (run.state === "COMPLETED") {
7251
- success(`Analysis complete in ${formatDuration(durationMs)}.`);
7424
+ success(sentence);
7252
7425
  await printNotebookLink(api, config, analysisId);
7253
7426
  return;
7254
7427
  }
7255
7428
  if (run.state === "CANCELLED") {
7256
- warn(`Analysis cancelled after ${formatDuration(durationMs)}.`);
7429
+ warn(sentence);
7257
7430
  process.exit(EXIT_FAILURE);
7258
7431
  }
7259
- failure(`Analysis failed after ${formatDuration(durationMs)}.`);
7432
+ failure(sentence);
7260
7433
  if (run.errorMessage) hint(run.errorMessage);
7261
7434
  hint(`Queue a fresh run with 'diafunc analyze rerun ${analysisId}'.`);
7262
7435
  process.exit(EXIT_FAILURE);
@@ -7307,7 +7480,7 @@ async function getAnalysisDetails(analysisId, options, cmd) {
7307
7480
  const analysis = outputFormat === "human" && !options.full ? { ...result.analysis, introduction: abbreviate(result.analysis.introduction) } : result.analysis;
7308
7481
  format(analysis, { format: outputFormat });
7309
7482
  if (outputFormat === "human" && !options.full && isLong(result.analysis.introduction)) {
7310
- hint(`Introduction abbreviated \u2014 pass --full to print it whole.`);
7483
+ hint("Introduction abbreviated. Pass --full to print it whole.");
7311
7484
  }
7312
7485
  }
7313
7486
  var INTRODUCTION_PREVIEW_LINES = 3;
@@ -7327,31 +7500,26 @@ async function watchAnalysis(analysisId, cmd) {
7327
7500
  empty("analysis found");
7328
7501
  return;
7329
7502
  }
7330
- const recipe = result.analysis;
7331
- const runs = await api.analysis.getRunsForAnalysis(recipe.analysisId, 1);
7503
+ const analysis = result.analysis;
7504
+ const runs = await api.analysis.getRunsForAnalysis(analysis.analysisId, 1);
7332
7505
  if (runs.length === 0) {
7333
7506
  empty("runs for this analysis");
7334
7507
  return;
7335
7508
  }
7336
7509
  const latest = runs[0];
7337
7510
  if (isTerminalState(latest.state)) {
7511
+ const sentence = latestRunSentence(latest.state);
7338
7512
  if (latest.state === "COMPLETED") {
7339
- success("The latest run has already completed.");
7513
+ success(sentence);
7340
7514
  } else {
7341
- warn(`The latest run ended as ${latest.state}.`);
7515
+ warn(sentence);
7342
7516
  if (latest.errorMessage) hint(latest.errorMessage);
7343
7517
  }
7344
- try {
7345
- const nav = await api.analysis.getNavigation(recipe.analysisId);
7346
- const config = loadConfig();
7347
- const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
7348
- console.log(` Project: ${endpoint}${nav.labUrl}`);
7349
- } catch {
7350
- }
7518
+ await printNotebookLink(api, loadConfig(), analysis.analysisId);
7351
7519
  return;
7352
7520
  }
7353
- console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
7354
- await monitorRun(api, recipe.analysisId, latest.runId, cmd);
7521
+ console.log(`Watching run ${latest.runId} for analysis ${analysis.analysisId} ...`);
7522
+ await monitorRun(api, analysis.analysisId, latest.runId, budgetHoursOf(analysis.hours), cmd);
7355
7523
  }
7356
7524
  async function rerunAnalysis(analysisId, cmd) {
7357
7525
  const api = createApiClient();
@@ -7384,20 +7552,18 @@ async function rerunAnalysis(analysisId, cmd) {
7384
7552
  questions: analysis.questions,
7385
7553
  segment: analysis.segment
7386
7554
  };
7387
- const configured = await configureInteractively(
7555
+ const configuredHours = await configureInteractively(
7388
7556
  api,
7389
7557
  createInquirerPrompter(),
7390
7558
  analysisId,
7391
7559
  recipe,
7392
7560
  suppliedFromAnalysis(analysis)
7393
7561
  );
7394
- if (!configured) return;
7562
+ if (configuredHours === null) return;
7395
7563
  }
7396
7564
  const run = await api.analysis.runAnalysis(analysisId);
7397
- success(`Queued new run ${run.runId} for analysis ${analysisId}`);
7398
- console.log(chalk26.dim(` State: ${run.state}`));
7399
- console.log();
7400
- console.log(chalk26.dim("Track progress: diafunc analyze watch " + analysisId));
7565
+ success(`Queued run ${run.runId} for analysis ${analysisId}.`);
7566
+ hint(`Follow it with 'diafunc analyze watch ${analysisId}'.`);
7401
7567
  }
7402
7568
  async function openAnalysis(analysisId) {
7403
7569
  const api = createApiClient();
@@ -7414,10 +7580,10 @@ async function openAnalysis(analysisId) {
7414
7580
  console.log(`Opening ${url} ...`);
7415
7581
  openUrl(url);
7416
7582
  } catch {
7417
- console.log(chalk26.dim("Notebook not yet provisioned \u2014 run the analysis first."));
7583
+ hint("The notebook is not available yet. Run the analysis first.");
7418
7584
  }
7419
7585
  }
7420
- async function createRecipe(options, cmd) {
7586
+ async function createAnalysis(options, cmd) {
7421
7587
  const outputFormat = getOutputFormat15(cmd);
7422
7588
  const api = createApiClient();
7423
7589
  const visibility = parseVisibility(options.visibility);
@@ -7438,14 +7604,14 @@ async function createRecipe(options, cmd) {
7438
7604
  async function deleteAnalysis(analysisId) {
7439
7605
  const api = createApiClient();
7440
7606
  await api.analysis.delete(analysisId);
7441
- success(`Deleted analysis ${analysisId}`);
7607
+ success(`Deleted analysis ${analysisId}.`);
7442
7608
  }
7443
7609
  async function patchAndPrint(analysisId, value, handler, successLabel, cmd) {
7444
7610
  const outputFormat = getOutputFormat15(cmd);
7445
7611
  const api = createApiClient();
7446
7612
  const updated = await handler(api, analysisId, value);
7447
7613
  if (outputFormat === "human") {
7448
- success(`${successLabel} updated for analysis ${analysisId}`);
7614
+ success(`${successLabel} updated for analysis ${analysisId}.`);
7449
7615
  } else {
7450
7616
  format(updated, { format: outputFormat });
7451
7617
  }
@@ -7479,7 +7645,8 @@ async function listColumns(analysisId, cmd) {
7479
7645
  const api = createApiClient();
7480
7646
  const columns = await api.analysis.getColumns(analysisId);
7481
7647
  if (columns.length === 0) {
7482
- empty("columns yet \u2014 upload data first");
7648
+ empty("columns", { format: outputFormat });
7649
+ if (outputFormat === "human") hint(`Upload data first: diafunc analyze upload ${analysisId} data.csv`);
7483
7650
  return;
7484
7651
  }
7485
7652
  format(columns, { format: outputFormat, columns: ["name", "valueType"] });
@@ -7491,10 +7658,11 @@ async function listRuns(analysisId, count, cmd) {
7491
7658
  format(runs.map((r) => ({
7492
7659
  runId: r.runId,
7493
7660
  state: r.state,
7494
- submittedAt: r.submittedAt ? new Date(r.submittedAt).toISOString() : "\u2014",
7495
- startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : "\u2014",
7496
- endedAt: r.endedAt ? new Date(r.endedAt).toISOString() : "\u2014",
7497
- evaluationId: r.evaluationId ?? "\u2014"
7661
+ phase: runPhaseCell(r),
7662
+ submittedAt: r.submittedAt,
7663
+ startedAt: r.startedAt,
7664
+ endedAt: r.endedAt,
7665
+ evaluationId: r.evaluationId
7498
7666
  })), {
7499
7667
  format: outputFormat,
7500
7668
  columns: [
@@ -7511,7 +7679,11 @@ async function cancelRun(runId, cmd) {
7511
7679
  const api = createApiClient();
7512
7680
  const run = await api.analysis.cancelRun(runId);
7513
7681
  if (outputFormat === "human") {
7514
- success(`Run ${run.runId} state: ${run.state}`);
7682
+ if (run.state === "CANCELLED") {
7683
+ success(cancelSentence(run));
7684
+ } else {
7685
+ warn(cancelSentence(run));
7686
+ }
7515
7687
  } else {
7516
7688
  format(run, { format: outputFormat });
7517
7689
  }
@@ -7521,16 +7693,24 @@ async function listPresets(cmd) {
7521
7693
  const api = createApiClient();
7522
7694
  const presets = await api.analysis.getPresets();
7523
7695
  format(presets.map((p) => ({
7524
- presetId: p.presetId ?? "\u2014",
7696
+ presetId: p.presetId,
7525
7697
  name: p.name,
7526
7698
  targets: p.targetKeys.join(", "),
7527
7699
  questions: p.questions.length,
7528
- segment: p.segmentKey ?? "\u2014",
7700
+ segment: p.segmentKey,
7529
7701
  hours: p.time,
7530
7702
  budget: p.budget
7531
7703
  })), {
7532
7704
  format: outputFormat,
7533
- columns: ["presetId", "name", "targets", "questions", "segment", "hours", "budget"]
7705
+ columns: [
7706
+ { key: "presetId", kind: "id" },
7707
+ "name",
7708
+ "targets",
7709
+ "questions",
7710
+ "segment",
7711
+ "hours",
7712
+ "budget"
7713
+ ]
7534
7714
  });
7535
7715
  }
7536
7716
  async function getPreset(presetId, cmd) {
@@ -7538,7 +7718,7 @@ async function getPreset(presetId, cmd) {
7538
7718
  const api = createApiClient();
7539
7719
  const opt = await api.analysis.getPreset(presetId);
7540
7720
  if (!opt.preset) {
7541
- console.log(chalk26.dim("Preset not found."));
7721
+ empty("preset found", { format: outputFormat });
7542
7722
  return;
7543
7723
  }
7544
7724
  format(opt.preset, { format: outputFormat });
@@ -7561,7 +7741,7 @@ async function savePreset(options, cmd) {
7561
7741
  async function deletePreset(presetId) {
7562
7742
  const api = createApiClient();
7563
7743
  await api.analysis.deletePreset(presetId);
7564
- success(`Deleted preset ${presetId}`);
7744
+ success(`Deleted preset ${presetId}.`);
7565
7745
  }
7566
7746
  async function listTriggers(analysisId, cmd) {
7567
7747
  const outputFormat = getOutputFormat15(cmd);
@@ -7572,18 +7752,24 @@ async function listTriggers(analysisId, cmd) {
7572
7752
  kind: t.kind,
7573
7753
  schedule: t.scheduleSpec,
7574
7754
  active: t.active,
7575
- nextFireAt: t.nextFireAt ? new Date(t.nextFireAt).toISOString() : "\u2014"
7755
+ nextFireAt: t.nextFireAt
7576
7756
  })), {
7577
7757
  format: outputFormat,
7578
- columns: ["triggerId", "kind", "schedule", "active", "nextFireAt"]
7758
+ columns: [
7759
+ { key: "triggerId", kind: "id" },
7760
+ "kind",
7761
+ "schedule",
7762
+ { key: "active", kind: "boolean" },
7763
+ { key: "nextFireAt", header: "next fire", kind: "date" }
7764
+ ]
7579
7765
  });
7580
7766
  }
7581
7767
  async function createTrigger(analysisId, kind, schedule, cmd) {
7582
7768
  const outputFormat = getOutputFormat15(cmd);
7583
7769
  const upper = kind.toUpperCase();
7584
7770
  if (upper !== "ONCE" && upper !== "CRON") {
7585
- failure(`Invalid kind "${kind}" \u2014 must be ONCE or CRON.`);
7586
- process.exit(1);
7771
+ failure(`Invalid kind "${kind}". Use ONCE or CRON.`);
7772
+ process.exit(EXIT_FAILURE);
7587
7773
  }
7588
7774
  const api = createApiClient();
7589
7775
  const trigger = await api.analysis.createTrigger(analysisId, {
@@ -7595,7 +7781,7 @@ async function createTrigger(analysisId, kind, schedule, cmd) {
7595
7781
  async function deleteTrigger(triggerId) {
7596
7782
  const api = createApiClient();
7597
7783
  await api.analysis.deleteTrigger(triggerId);
7598
- success(`Deleted trigger ${triggerId}`);
7784
+ success(`Deleted trigger ${triggerId}.`);
7599
7785
  }
7600
7786
  async function updateTriggerCmd(triggerId, options, cmd) {
7601
7787
  const outputFormat = getOutputFormat15(cmd);
@@ -7603,14 +7789,14 @@ async function updateTriggerCmd(triggerId, options, cmd) {
7603
7789
  if (options.active !== void 0) {
7604
7790
  const lc = options.active.toLowerCase();
7605
7791
  if (lc !== "true" && lc !== "false") {
7606
- failure(`Invalid --active value "${options.active}" \u2014 must be true or false.`);
7607
- process.exit(1);
7792
+ failure(`Invalid --active value "${options.active}". Use true or false.`);
7793
+ process.exit(EXIT_FAILURE);
7608
7794
  }
7609
7795
  activeFlag = lc === "true";
7610
7796
  }
7611
7797
  if (activeFlag === void 0 && !options.schedule) {
7612
7798
  failure("Pass at least one of --active or --schedule.");
7613
- process.exit(1);
7799
+ process.exit(EXIT_FAILURE);
7614
7800
  }
7615
7801
  const api = createApiClient();
7616
7802
  const trigger = await api.analysis.updateTrigger(triggerId, {
@@ -7621,7 +7807,7 @@ async function updateTriggerCmd(triggerId, options, cmd) {
7621
7807
  }
7622
7808
  function registerAnalyzeCommand(program) {
7623
7809
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
7624
- analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--hours <hours>", `Computation time in hours (default: ${DEFAULT_HOURS}; preset value used when --preset set)`).option("--budget <credits>", `Credit budget (default: ${DEFAULT_BUDGET}; preset value used when --preset set)`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction at notebook position 0").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override preset values)").action(async (file, options, cmd) => {
7810
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "Data file to analyze (CSV, Excel, Parquet, JSON and 20+ more formats)").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--hours <hours>", `Computation time (hours). Default ${DEFAULT_HOURS}, the Standard preset; a saved preset applies when omitted`).option("--budget <credits>", `Credit budget. Default ${Number(DEFAULT_BUDGET).toLocaleString("en-US")}, the Standard preset; a saved preset applies when omitted`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").action(async (file, options, cmd) => {
7625
7811
  try {
7626
7812
  if (!file) {
7627
7813
  analyze.help();
@@ -7646,7 +7832,7 @@ function registerAnalyzeCommand(program) {
7646
7832
  handleError(error);
7647
7833
  }
7648
7834
  });
7649
- analyze.command("watch").description("Live-monitor the latest run of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
7835
+ analyze.command("watch").description("Follow the latest run of an analysis live").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
7650
7836
  try {
7651
7837
  await watchAnalysis(id, cmd);
7652
7838
  } catch (error) {
@@ -7667,14 +7853,14 @@ function registerAnalyzeCommand(program) {
7667
7853
  reportCommandError(error);
7668
7854
  }
7669
7855
  });
7670
- analyze.command("create").description("Create an analysis recipe without uploading data or running").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <h>", "Computation hours").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Segmentation column").option("--introduction <markdown>", "Markdown introduction").action(async (options, cmd) => {
7856
+ analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Computation time (hours)").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
7671
7857
  try {
7672
- await createRecipe(options, cmd);
7858
+ await createAnalysis(options, cmd);
7673
7859
  } catch (error) {
7674
7860
  handleError(error);
7675
7861
  }
7676
7862
  });
7677
- analyze.command("delete").description("Delete an analysis (cancels in-flight run; removes underlying project)").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
7863
+ analyze.command("delete").description("Delete an analysis, cancelling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
7678
7864
  try {
7679
7865
  await confirmDestructive(`This will permanently delete analysis "${id}".`, { yes: options.yes, resourceId: id });
7680
7866
  await deleteAnalysis(id);
@@ -7735,7 +7921,7 @@ function registerAnalyzeCommand(program) {
7735
7921
  handleError(error);
7736
7922
  }
7737
7923
  });
7738
- analyze.command("hours").description("Set the compute-hours budget for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Compute hours (e.g. 4)").action(async (id, hours, _options, cmd) => {
7924
+ analyze.command("hours").description("Set the computation time (hours) for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Computation time (hours), e.g. 4").action(async (id, hours, _options, cmd) => {
7739
7925
  try {
7740
7926
  await patchAndPrint(
7741
7927
  id,
@@ -7748,7 +7934,7 @@ function registerAnalyzeCommand(program) {
7748
7934
  handleError(error);
7749
7935
  }
7750
7936
  });
7751
- analyze.command("budget").description("Set the token-credit budget for the next run").argument("<id>", "Analysis ID").argument("<credits>", "Credit budget (e.g. 10000)").action(async (id, credits, _options, cmd) => {
7937
+ analyze.command("budget").description("Set the credit budget for the next run").argument("<id>", "Analysis ID").argument("<credits>", "Credit budget, e.g. 10000").action(async (id, credits, _options, cmd) => {
7752
7938
  try {
7753
7939
  await patchAndPrint(
7754
7940
  id,
@@ -7802,14 +7988,14 @@ function registerAnalyzeCommand(program) {
7802
7988
  handleError(error);
7803
7989
  }
7804
7990
  });
7805
- analyze.command("upload").description("Replace the analysis raw-data table with a new data table (any supported format \u2014 see `table import-formats`)").argument("<id>", "Analysis ID").argument("[file]", "CSV file to upload").option("--url <url>", "HTTPS URL to fetch the CSV from (mutually exclusive with file)").action(async (id, file, options) => {
7991
+ analyze.command("upload").description("Replace the analysis data with a new file (any supported format; see `table import-formats`)").argument("<id>", "Analysis ID").argument("[file]", "Data file to upload (CSV, Excel, Parquet, JSON and 20+ more formats)").option("--url <url>", "HTTPS URL to fetch the data file from, instead of a file path").action(async (id, file, options) => {
7806
7992
  try {
7807
7993
  await uploadData(id, file, options);
7808
7994
  } catch (error) {
7809
7995
  handleError(error);
7810
7996
  }
7811
7997
  });
7812
- analyze.command("columns").description("List columns of the analysis raw-data table").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
7998
+ analyze.command("columns").description("List the columns of the analysis data").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
7813
7999
  try {
7814
8000
  await listColumns(id, cmd);
7815
8001
  } catch (error) {
@@ -7823,7 +8009,7 @@ function registerAnalyzeCommand(program) {
7823
8009
  handleError(error);
7824
8010
  }
7825
8011
  });
7826
- analyze.command("cancel").description("Cancel a non-terminal run (idempotent on terminal runs)").argument("<runId>", "Run ID to cancel").action(async (runId, _options, cmd) => {
8012
+ analyze.command("cancel").description("Cancel a run that has not finished (a finished run is left as it is)").argument("<runId>", "Run ID to cancel").action(async (runId, _options, cmd) => {
7827
8013
  try {
7828
8014
  await cancelRun(runId, cmd);
7829
8015
  } catch (error) {
@@ -7845,7 +8031,7 @@ function registerAnalyzeCommand(program) {
7845
8031
  handleError(error);
7846
8032
  }
7847
8033
  });
7848
- presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <csv>", "Comma-separated target column names").requiredOption("--hours <h>", "Compute hours").requiredOption("--budget <credits>", "Credit budget").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Segmentation column").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
8034
+ presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <csv>", "Comma-separated target column names").requiredOption("--hours <hours>", "Computation time (hours)").requiredOption("--budget <credits>", "Credit budget").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Column to segment the analysis by").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
7849
8035
  try {
7850
8036
  await savePreset(options, cmd);
7851
8037
  } catch (error) {
@@ -7883,7 +8069,7 @@ function registerAnalyzeCommand(program) {
7883
8069
  handleError(error);
7884
8070
  }
7885
8071
  });
7886
- triggers.command("update").description("Update a trigger \u2014 pause/resume (--active) and/or reschedule (--schedule)").argument("<triggerId>", "Trigger ID").option("--active <bool>", "true to resume, false to pause").option("--schedule <spec>", "New schedule spec (ISO-8601 instant for ONCE, Quartz cron for CRON)").action(async (triggerId, options, cmd) => {
8072
+ triggers.command("update").description("Update a trigger: pause or resume it (--active), reschedule it (--schedule), or both").argument("<triggerId>", "Trigger ID").option("--active <bool>", "true to resume, false to pause").option("--schedule <spec>", "New schedule spec (ISO-8601 instant for ONCE, Quartz cron for CRON)").action(async (triggerId, options, cmd) => {
7887
8073
  try {
7888
8074
  await updateTriggerCmd(triggerId, options, cmd);
7889
8075
  } catch (error) {
@@ -7893,7 +8079,7 @@ function registerAnalyzeCommand(program) {
7893
8079
  }
7894
8080
 
7895
8081
  // src/commands/data-sources/index.ts
7896
- import chalk27 from "chalk";
8082
+ import chalk26 from "chalk";
7897
8083
  function getOutputFormat16(cmd) {
7898
8084
  const config = loadConfig();
7899
8085
  const globalOpts = cmd.optsWithGlobals();
@@ -7905,12 +8091,12 @@ function parseConfigPairs(pairs) {
7905
8091
  for (const pair of pairs) {
7906
8092
  const idx = pair.indexOf("=");
7907
8093
  if (idx <= 0) {
7908
- throw new Error(`Invalid --config "${pair}" \u2014 expected key=value.`);
8094
+ throw new Error(`Invalid --config "${pair}". Expected key=value.`);
7909
8095
  }
7910
8096
  const key = pair.substring(0, idx).trim();
7911
8097
  const value = pair.substring(idx + 1);
7912
8098
  if (!key) {
7913
- throw new Error(`Invalid --config "${pair}" \u2014 empty key.`);
8099
+ throw new Error(`Invalid --config "${pair}". The key is empty.`);
7914
8100
  }
7915
8101
  out[key] = value;
7916
8102
  }
@@ -8029,7 +8215,7 @@ async function showDashboard(projectId, cmd) {
8029
8215
  return;
8030
8216
  }
8031
8217
  const r = dashboard.rollup;
8032
- let line = chalk27.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8218
+ let line = chalk26.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8033
8219
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
8034
8220
  console.log(line);
8035
8221
  if (dashboard.sources.length === 0) {
@@ -8067,8 +8253,8 @@ async function createDataSource(options, cmd) {
8067
8253
  const ds = await api.storage.createDataSource(request);
8068
8254
  if (outputFormat === "human") {
8069
8255
  success(`Created data source ${ds.id}`);
8070
- console.log(chalk27.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8071
- if (ds.lastRunError) console.log(chalk27.dim(` Error: ${ds.lastRunError}`));
8256
+ console.log(chalk26.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8257
+ if (ds.lastRunError) console.log(chalk26.dim(` Error: ${ds.lastRunError}`));
8072
8258
  } else {
8073
8259
  format(ds, { format: outputFormat });
8074
8260
  }
@@ -8113,8 +8299,8 @@ async function refreshDataSource(id, cmd) {
8113
8299
  const api = createApiClient();
8114
8300
  const run = await api.storage.refreshDataSource(id);
8115
8301
  if (outputFormat === "human") {
8116
- success(`Refresh queued \u2014 run ${run.runId}, status ${run.status}`);
8117
- if (run.errorMessage) console.log(chalk27.red(` Error: ${run.errorMessage}`));
8302
+ success(`Refresh queued: run ${run.runId}, status ${run.status}.`);
8303
+ if (run.errorMessage) console.log(chalk26.red(` Error: ${run.errorMessage}`));
8118
8304
  } else {
8119
8305
  format(run, { format: outputFormat });
8120
8306
  }
@@ -8188,14 +8374,14 @@ Examples:
8188
8374
  handleError(error);
8189
8375
  }
8190
8376
  });
8191
- dataSources.command("create").description("Create a data source (runs the initial fetch synchronously)").requiredOption("--project-id <id>", "Project ID").requiredOption("--project-branch <branch>", 'Project branch (usually "main")').requiredOption("--target-entity-id <id>", "Target table entity ID").requiredOption("--target-entity-branch <branch>", "Target table entity branch").requiredOption("--name <name>", "Display name").requiredOption("--type <type>", "Connector type (google_sheets, s3_url, jdbc)").option("--config <key=value>", "Connector config field \u2014 repeat for multiple", (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", 'Quartz cron expression (e.g. "0 0 2 * * ?" for daily 02:00 UTC); omit for manual-only').action(async (options, cmd) => {
8377
+ dataSources.command("create").description("Create a data source (runs the initial fetch synchronously)").requiredOption("--project-id <id>", "Project ID").requiredOption("--project-branch <branch>", 'Project branch (usually "main")').requiredOption("--target-entity-id <id>", "Target table entity ID").requiredOption("--target-entity-branch <branch>", "Target table entity branch").requiredOption("--name <name>", "Display name").requiredOption("--type <type>", "Connector type (google_sheets, s3_url, jdbc)").option("--config <key=value>", "Connector config field; repeat for multiple", (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", 'Quartz cron expression (e.g. "0 0 2 * * ?" for daily 02:00 UTC); omit for manual-only').action(async (options, cmd) => {
8192
8378
  try {
8193
8379
  await createDataSource(options, cmd);
8194
8380
  } catch (error) {
8195
8381
  handleError(error);
8196
8382
  }
8197
8383
  });
8198
- dataSources.command("update").description("Update a data source (omit a flag to leave that field unchanged)").argument("<id>", "Data source ID").option("--name <name>", "New display name").option("--type <type>", "New connector type").option("--config <key=value>", 'Replace the entire config map \u2014 repeat for multiple. Send "[redacted]" as a value to keep the existing encrypted credential.', (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", "New Quartz cron expression").option("--clear-schedule", "Switch this data source to manual-only").action(async (id, options, cmd) => {
8384
+ dataSources.command("update").description("Update a data source (omit a flag to leave that field unchanged)").argument("<id>", "Data source ID").option("--name <name>", "New display name").option("--type <type>", "New connector type").option("--config <key=value>", 'Replace the entire config map; repeat for multiple. Send "[redacted]" as a value to keep the existing encrypted credential.', (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", "New Quartz cron expression").option("--clear-schedule", "Switch this data source to manual-only").action(async (id, options, cmd) => {
8199
8385
  try {
8200
8386
  await updateDataSource(id, options, cmd);
8201
8387
  } catch (error) {
@@ -8241,14 +8427,14 @@ Examples:
8241
8427
  }
8242
8428
 
8243
8429
  // src/commands/table-exporters/index.ts
8244
- import chalk28 from "chalk";
8430
+ import chalk27 from "chalk";
8245
8431
  function getOutputFormat17(cmd) {
8246
8432
  const config = loadConfig();
8247
8433
  const globalOpts = cmd.optsWithGlobals();
8248
8434
  return globalOpts.output ?? config.defaults.output ?? "human";
8249
8435
  }
8250
8436
  function registerTableExportersCommands(program) {
8251
- const exporters = program.command("table-exporters").description("Manage user-defined exporters (UDE) \u2014 admin-only");
8437
+ const exporters = program.command("table-exporters").description("Manage user-defined exporters (UDE); admin only");
8252
8438
  exporters.command("list").description("List all registered user-defined exporters").action(async (_options, cmd) => {
8253
8439
  try {
8254
8440
  const outputFormat = getOutputFormat17(cmd);
@@ -8272,7 +8458,7 @@ function registerTableExportersCommands(program) {
8272
8458
  format: outputFormat,
8273
8459
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
8274
8460
  });
8275
- console.log(chalk28.dim(`${list.length} exporter(s)`));
8461
+ console.log(chalk27.dim(`${list.length} exporter(s)`));
8276
8462
  } catch (error) {
8277
8463
  handleError(error);
8278
8464
  }
@@ -8330,7 +8516,7 @@ function registerTableExportersCommands(program) {
8330
8516
  }
8331
8517
 
8332
8518
  // src/commands/skeleton/index.ts
8333
- import chalk29 from "chalk";
8519
+ import chalk28 from "chalk";
8334
8520
  import * as fs9 from "fs";
8335
8521
  function getOutputFormat18(cmd) {
8336
8522
  const config = loadConfig();
@@ -8366,7 +8552,7 @@ function parseWeight(raw) {
8366
8552
  if (raw === void 0) return null;
8367
8553
  const value = Number(raw);
8368
8554
  if (!Number.isFinite(value) || value <= 0) {
8369
- throw new Error(`Invalid --weight "${raw}" \u2014 must be a positive number.`);
8555
+ throw new Error(`Invalid --weight "${raw}". Use a positive number.`);
8370
8556
  }
8371
8557
  return value;
8372
8558
  }
@@ -8397,10 +8583,10 @@ async function createSkeleton(options, cmd) {
8397
8583
  const skeleton = await api.storage.createSkeleton(request);
8398
8584
  if (outputFormat === "human") {
8399
8585
  success(`Created skeleton ${skeleton.id}`);
8400
- console.log(chalk29.dim(` name: ${skeleton.name}`));
8401
- console.log(chalk29.dim(` template: ${skeleton.template}`));
8402
- console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8403
- console.log(chalk29.dim(` weight: ${skeleton.weight}`));
8586
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
8587
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
8588
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8589
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8404
8590
  } else {
8405
8591
  format(skeleton, { format: outputFormat });
8406
8592
  }
@@ -8439,10 +8625,10 @@ async function updateSkeleton(id, options, cmd) {
8439
8625
  const skeleton = await api.storage.updateSkeleton(id, request);
8440
8626
  if (outputFormat === "human") {
8441
8627
  success(`Updated skeleton ${skeleton.id}`);
8442
- console.log(chalk29.dim(` name: ${skeleton.name}`));
8443
- console.log(chalk29.dim(` template: ${skeleton.template}`));
8444
- console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8445
- console.log(chalk29.dim(` weight: ${skeleton.weight}`));
8628
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
8629
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
8630
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8631
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8446
8632
  } else {
8447
8633
  format(skeleton, { format: outputFormat });
8448
8634
  }
@@ -8759,7 +8945,7 @@ function registerCompletionCommand(program) {
8759
8945
  }
8760
8946
 
8761
8947
  // src/commands/whoami/index.ts
8762
- import chalk30 from "chalk";
8948
+ import chalk29 from "chalk";
8763
8949
  function registerWhoamiCommand(program) {
8764
8950
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
8765
8951
  try {
@@ -8769,8 +8955,8 @@ function registerWhoamiCommand(program) {
8769
8955
  const api = createApiClient();
8770
8956
  const user = await api.admin.getMyUser();
8771
8957
  if (outputFormat === "human") {
8772
- console.log(chalk30.bold(user.name) + chalk30.dim(` <${user.email}>`));
8773
- console.log(chalk30.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8958
+ console.log(chalk29.bold(user.name) + chalk29.dim(` <${user.email}>`));
8959
+ console.log(chalk29.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8774
8960
  } else {
8775
8961
  format(user, { format: outputFormat });
8776
8962
  }
@@ -8781,7 +8967,7 @@ function registerWhoamiCommand(program) {
8781
8967
  }
8782
8968
 
8783
8969
  // src/commands/utilization/index.ts
8784
- import chalk31 from "chalk";
8970
+ import chalk30 from "chalk";
8785
8971
  function getOutputFormat19(cmd) {
8786
8972
  const config = loadConfig();
8787
8973
  const globalOpts = cmd.optsWithGlobals();
@@ -8798,19 +8984,44 @@ function windowLabel(u) {
8798
8984
  }
8799
8985
  function printUtilizationHuman(u, label) {
8800
8986
  const when2 = windowLabel(u);
8801
- console.log(label ? chalk31.bold(label) + " " + chalk31.dim(when2) : chalk31.bold(when2));
8987
+ console.log(label ? chalk30.bold(label) + " " + chalk30.dim(when2) : chalk30.bold(when2));
8802
8988
  if (u.types.length === 0) {
8803
- console.log(chalk31.dim(" (no usage)"));
8989
+ console.log(chalk30.dim(" (no usage)"));
8804
8990
  return;
8805
8991
  }
8806
8992
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
8807
8993
  const width = Math.max(...types.map((t) => t.type.length));
8808
8994
  for (const t of types) {
8809
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk31.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8810
- console.log(t.credits === 0 ? chalk31.dim(line) : line);
8995
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk30.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8996
+ console.log(t.credits === 0 ? chalk30.dim(line) : line);
8811
8997
  }
8812
8998
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
8813
- console.log(chalk31.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk31.dim("credits")} ${total.toFixed(2).padStart(10)}`));
8999
+ console.log(chalk30.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk30.dim("credits")} ${total.toFixed(2).padStart(10)}`));
9000
+ }
9001
+ function formatDailyHistory(history) {
9002
+ const spentOn = (u) => u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);
9003
+ const costly = (u) => u.types.filter((t) => (t.dailyCredits ?? 0) > 0).sort((a, b) => (b.dailyCredits ?? 0) - (a.dailyCredits ?? 0));
9004
+ const totalLabel = `Total, ${history.length} ${history.length === 1 ? "day" : "days"}`;
9005
+ const width = Math.max(
9006
+ totalLabel.length,
9007
+ ...history.map((u) => windowLabel(u).length),
9008
+ ...history.flatMap((u) => costly(u).map((t) => t.type.length + 2))
9009
+ );
9010
+ const amount = (credits) => credits.toFixed(2).padStart(10);
9011
+ const lines = [];
9012
+ let total = 0;
9013
+ for (const u of history) {
9014
+ const spent = spentOn(u);
9015
+ total += spent;
9016
+ const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk30.dim("credits")}`;
9017
+ lines.push(spent > 0 ? chalk30.bold(line) : chalk30.dim(line));
9018
+ for (const t of costly(u)) {
9019
+ lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);
9020
+ }
9021
+ }
9022
+ lines.push("");
9023
+ lines.push(chalk30.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk30.dim("credits")}`));
9024
+ return lines;
8814
9025
  }
8815
9026
  function registerUtilizationCommand(program) {
8816
9027
  const util = program.command("utilization").description("Show credit utilization for the current billing cycle").addHelpText("after", `
@@ -8834,7 +9045,7 @@ Examples:
8834
9045
  handleError(error);
8835
9046
  }
8836
9047
  });
8837
- util.command("history").description("Show utilization history").action(async (_options, cmd) => {
9048
+ util.command("history").description("Show what each day of the billing cycle cost").action(async (_options, cmd) => {
8838
9049
  try {
8839
9050
  const outputFormat = getOutputFormat19(cmd);
8840
9051
  const api = createApiClient();
@@ -8844,9 +9055,8 @@ Examples:
8844
9055
  empty("usage recorded");
8845
9056
  return;
8846
9057
  }
8847
- for (const u of history) {
8848
- printUtilizationHuman(u);
8849
- console.log();
9058
+ for (const line of formatDailyHistory(history)) {
9059
+ console.log(line);
8850
9060
  }
8851
9061
  } else {
8852
9062
  format(history, { format: outputFormat });
@@ -9013,7 +9223,7 @@ Examples:
9013
9223
  }
9014
9224
 
9015
9225
  // src/commands/shell/index.ts
9016
- import chalk32 from "chalk";
9226
+ import chalk31 from "chalk";
9017
9227
  import * as fs11 from "fs";
9018
9228
  import * as os3 from "os";
9019
9229
  import * as path8 from "path";
@@ -9079,21 +9289,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
9079
9289
  }, false);
9080
9290
  if (result.outputs?.length) {
9081
9291
  for (const out of result.outputs) {
9082
- console.log(chalk32.dim(` [${out.type}]`) + " " + out.output);
9292
+ console.log(chalk31.dim(` [${out.type}]`) + " " + out.output);
9083
9293
  }
9084
9294
  }
9085
9295
  if (result.successful) {
9086
9296
  if (result.result) {
9087
- console.log(chalk32.green("=>") + " " + result.result);
9297
+ console.log(chalk31.green("=>") + " " + result.result);
9088
9298
  } else {
9089
- console.log(chalk32.dim("=> (no value)"));
9299
+ console.log(chalk31.dim("=> (no value)"));
9090
9300
  }
9091
9301
  const duration = result.completed - result.started;
9092
- console.log(chalk32.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9302
+ console.log(chalk31.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9093
9303
  } else {
9094
- console.log(chalk32.red("error: ") + result.error);
9304
+ console.log(chalk31.red("error: ") + result.error);
9095
9305
  if (result.lineNumber > 0) {
9096
- console.log(chalk32.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9306
+ console.log(chalk31.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9097
9307
  }
9098
9308
  }
9099
9309
  }
@@ -9114,19 +9324,19 @@ function registerShellCommand(program) {
9114
9324
  });
9115
9325
  const api = createApiClient();
9116
9326
  const { input: promptInput } = await import("@inquirer/prompts");
9117
- const { getUpdateNotice } = await import("./update-check-SNH7P32S.js");
9327
+ const { getUpdateNotice } = await import("./update-check-V23VUFO4.js");
9118
9328
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
9119
- console.log(chalk32.bold("Diafunc shell") + chalk32.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9120
- console.log(chalk32.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9121
- console.log(chalk32.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9329
+ console.log(chalk31.bold("Diafunc shell") + chalk31.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9330
+ console.log(chalk31.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9331
+ console.log(chalk31.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9122
9332
  const notice = await getUpdateNotice();
9123
- if (notice) console.log(chalk32.dim(notice));
9333
+ if (notice) console.log(chalk31.dim(notice));
9124
9334
  console.log();
9125
9335
  let language = resolvedLanguage;
9126
9336
  for (; ; ) {
9127
9337
  let line;
9128
9338
  try {
9129
- line = await promptInput({ message: chalk32.cyan.bold(`${language} >`) });
9339
+ line = await promptInput({ message: chalk31.cyan.bold(`${language} >`) });
9130
9340
  } catch {
9131
9341
  console.log();
9132
9342
  return;
@@ -9144,54 +9354,54 @@ function registerShellCommand(program) {
9144
9354
  case "help":
9145
9355
  case "h":
9146
9356
  case "?":
9147
- console.log(chalk32.dim(" /edit open $EDITOR for multi-line code"));
9148
- console.log(chalk32.dim(" /file <path> evaluate the contents of a file"));
9149
- console.log(chalk32.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9150
- console.log(chalk32.dim(" /quit exit the shell"));
9357
+ console.log(chalk31.dim(" /edit open $EDITOR for multi-line code"));
9358
+ console.log(chalk31.dim(" /file <path> evaluate the contents of a file"));
9359
+ console.log(chalk31.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9360
+ console.log(chalk31.dim(" /quit exit the shell"));
9151
9361
  continue;
9152
9362
  case "lang":
9153
9363
  if (arg) language = arg;
9154
- console.log(chalk32.dim(`Language: ${language}`));
9364
+ console.log(chalk31.dim(`Language: ${language}`));
9155
9365
  continue;
9156
9366
  case "edit": {
9157
9367
  const sourceCode = await openInEditor("", extensionFor2(language));
9158
9368
  if (!sourceCode.trim()) {
9159
- console.log(chalk32.dim("(empty \u2014 not evaluated)"));
9369
+ console.log(chalk31.dim("(empty; not evaluated)"));
9160
9370
  continue;
9161
9371
  }
9162
9372
  try {
9163
9373
  await evaluate(api, fnRef, language, sourceCode);
9164
9374
  } catch (e) {
9165
- console.error(chalk32.red(e.message));
9375
+ console.error(chalk31.red(e.message));
9166
9376
  }
9167
9377
  continue;
9168
9378
  }
9169
9379
  case "file": {
9170
9380
  if (!arg) {
9171
- console.log(chalk32.dim("usage: /file <path>"));
9381
+ console.log(chalk31.dim("usage: /file <path>"));
9172
9382
  continue;
9173
9383
  }
9174
9384
  if (!fs11.existsSync(arg)) {
9175
- console.log(chalk32.red(`file not found: ${arg}`));
9385
+ console.log(chalk31.red(`file not found: ${arg}`));
9176
9386
  continue;
9177
9387
  }
9178
9388
  const sourceCode = fs11.readFileSync(arg, "utf-8");
9179
9389
  try {
9180
9390
  await evaluate(api, fnRef, language, sourceCode);
9181
9391
  } catch (e) {
9182
- console.error(chalk32.red(e.message));
9392
+ console.error(chalk31.red(e.message));
9183
9393
  }
9184
9394
  continue;
9185
9395
  }
9186
9396
  default:
9187
- console.log(chalk32.dim(`Unknown command: /${cmd2}. Try /help.`));
9397
+ console.log(chalk31.dim(`Unknown command: /${cmd2}. Try /help.`));
9188
9398
  continue;
9189
9399
  }
9190
9400
  }
9191
9401
  try {
9192
9402
  await evaluate(api, fnRef, language, trimmed);
9193
9403
  } catch (e) {
9194
- console.error(chalk32.red(e.message));
9404
+ console.error(chalk31.red(e.message));
9195
9405
  }
9196
9406
  }
9197
9407
  } catch (error) {
@@ -9201,7 +9411,7 @@ function registerShellCommand(program) {
9201
9411
  }
9202
9412
 
9203
9413
  // src/commands/update/index.ts
9204
- import chalk33 from "chalk";
9414
+ import chalk32 from "chalk";
9205
9415
  import * as path9 from "path";
9206
9416
  import { spawn as spawn4 } from "child_process";
9207
9417
 
@@ -9247,14 +9457,14 @@ function registerUpdateCommand(program) {
9247
9457
  const install = detectInstall();
9248
9458
  const latest = await fetchLatestVersion();
9249
9459
  if (latest === package_default.version) {
9250
- console.log(chalk33.dim(`diafunc is already at the latest version (${package_default.version}).`));
9460
+ console.log(chalk32.dim(`diafunc is already at the latest version (${package_default.version}).`));
9251
9461
  return;
9252
9462
  }
9253
- console.log(chalk33.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9463
+ console.log(chalk32.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9254
9464
  if (install.method === "npm") {
9255
9465
  console.log();
9256
9466
  console.log("Installed via npm. Upgrade with:");
9257
- console.log(chalk33.bold(` npm install -g @diafunc/cli@${latest}`));
9467
+ console.log(chalk32.bold(` npm install -g @diafunc/cli@${latest}`));
9258
9468
  return;
9259
9469
  }
9260
9470
  const installDir = path9.dirname(install.binaryPath);
@@ -9268,7 +9478,7 @@ function registerUpdateCommand(program) {
9268
9478
  }
9269
9479
 
9270
9480
  // src/commands/uninstall/index.ts
9271
- import chalk34 from "chalk";
9481
+ import chalk33 from "chalk";
9272
9482
  import { spawn as spawn5 } from "child_process";
9273
9483
  import * as fs13 from "fs";
9274
9484
  import * as os4 from "os";
@@ -9280,11 +9490,11 @@ function registerUninstallCommand(program) {
9280
9490
  const configDir = path10.join(os4.homedir(), ".diafunc");
9281
9491
  if (install.method === "npm") {
9282
9492
  console.log("Installed via npm. Remove with:");
9283
- console.log(chalk34.bold(" npm uninstall -g @diafunc/cli"));
9493
+ console.log(chalk33.bold(" npm uninstall -g @diafunc/cli"));
9284
9494
  if (fs13.existsSync(configDir)) {
9285
9495
  console.log();
9286
- console.log(`Config + credentials live at ${configDir} \u2014 remove manually with:`);
9287
- console.log(chalk34.bold(` rm -rf ${configDir}`));
9496
+ console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);
9497
+ console.log(chalk33.bold(` rm -rf ${configDir}`));
9288
9498
  }
9289
9499
  return;
9290
9500
  }
@@ -9294,7 +9504,7 @@ function registerUninstallCommand(program) {
9294
9504
  default: false
9295
9505
  });
9296
9506
  if (!removeBinary) {
9297
- console.log(chalk34.dim("Aborted."));
9507
+ console.log(chalk33.dim("Aborted."));
9298
9508
  return;
9299
9509
  }
9300
9510
  let removeConfig = options.purge ?? false;
@@ -9306,7 +9516,7 @@ function registerUninstallCommand(program) {
9306
9516
  }
9307
9517
  if (removeConfig && fs13.existsSync(configDir)) {
9308
9518
  fs13.rmSync(configDir, { recursive: true, force: true });
9309
- console.log(chalk34.dim(`Removed ${configDir}`));
9519
+ console.log(chalk33.dim(`Removed ${configDir}`));
9310
9520
  }
9311
9521
  if (process.platform === "win32") {
9312
9522
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -9316,13 +9526,13 @@ function registerUninstallCommand(program) {
9316
9526
  windowsHide: true
9317
9527
  });
9318
9528
  child.unref();
9319
- console.log(chalk34.dim(`Removing ${install.binaryPath} on exit...`));
9529
+ console.log(chalk33.dim(`Removing ${install.binaryPath} on exit...`));
9320
9530
  console.log();
9321
9531
  console.log("diafunc uninstalled.");
9322
9532
  return;
9323
9533
  }
9324
9534
  fs13.rmSync(install.binaryPath, { force: true });
9325
- console.log(chalk34.dim(`Removed ${install.binaryPath}`));
9535
+ console.log(chalk33.dim(`Removed ${install.binaryPath}`));
9326
9536
  console.log();
9327
9537
  console.log("diafunc uninstalled.");
9328
9538
  } catch (error) {
@@ -9386,7 +9596,7 @@ var DiafuncCommand = class _DiafuncCommand extends Command {
9386
9596
  };
9387
9597
 
9388
9598
  // src/prompting/fill.ts
9389
- import chalk36 from "chalk";
9599
+ import chalk35 from "chalk";
9390
9600
 
9391
9601
  // src/prompting/resolvers.ts
9392
9602
  var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
@@ -9579,7 +9789,7 @@ function dependencies(spec) {
9579
9789
 
9580
9790
  // src/prompting/pickers.ts
9581
9791
  import * as fs14 from "fs";
9582
- import chalk35 from "chalk";
9792
+ import chalk34 from "chalk";
9583
9793
  var SEARCH_THRESHOLD = 10;
9584
9794
  var TYPE_IT = "\0type-it";
9585
9795
  async function askFor(spec, input, ctx) {
@@ -9772,7 +9982,7 @@ async function projectContext(ctx, projectFrom) {
9772
9982
  const [projectId, branch] = raw.split("/");
9773
9983
  return { projectId, projectBranch: branch || ctx.globals.branch || config.defaults.branch || "main" };
9774
9984
  }
9775
- var FIRST_PAGE = 100;
9985
+ var FIRST_PAGE2 = 100;
9776
9986
  async function fromIndex(ctx, message, query, answer) {
9777
9987
  let firstPage = null;
9778
9988
  let warned = false;
@@ -9784,7 +9994,7 @@ async function fromIndex(ctx, message, query, answer) {
9784
9994
  message,
9785
9995
  source: async (term) => {
9786
9996
  try {
9787
- firstPage ??= await indexItems(ctx, "*", query, FIRST_PAGE);
9997
+ firstPage ??= await indexItems(ctx, "*", query, FIRST_PAGE2);
9788
9998
  const needle = term.trim().toLowerCase();
9789
9999
  let items = needle ? firstPage.filter((item) => `${item.name ?? ""} ${item.entityId ?? item.projectId}`.toLowerCase().includes(needle)) : firstPage;
9790
10000
  if (needle && items.length === 0) items = await indexItems(ctx, term.trim(), query, 30);
@@ -9927,7 +10137,7 @@ function typedValue(ctx, message) {
9927
10137
  return typed(ctx, message);
9928
10138
  }
9929
10139
  function typeItChoice() {
9930
- return { name: chalk35.dim("Type it instead"), value: TYPE_IT };
10140
+ return { name: chalk34.dim("Type it instead"), value: TYPE_IT };
9931
10141
  }
9932
10142
  function text(ctx, name) {
9933
10143
  const value = ctx.known.get(name);
@@ -9957,7 +10167,7 @@ function capitalize(value) {
9957
10167
  return value.charAt(0).toUpperCase() + value.slice(1);
9958
10168
  }
9959
10169
  function labelled(label, hint2) {
9960
- return hint2 && hint2 !== label ? `${label} ${chalk35.dim(hint2)}` : label;
10170
+ return hint2 && hint2 !== label ? `${label} ${chalk34.dim(hint2)}` : label;
9961
10171
  }
9962
10172
  function numberRule(spec) {
9963
10173
  return (raw) => {
@@ -10003,7 +10213,7 @@ async function fillPendingInputs(actionCommand) {
10003
10213
  known: knownValues(actionCommand),
10004
10214
  globals: actionCommand.optsWithGlobals(),
10005
10215
  prefill: /* @__PURE__ */ new Map(),
10006
- note: (line) => process.stderr.write(chalk36.dim(` ${line}
10216
+ note: (line) => process.stderr.write(chalk35.dim(` ${line}
10007
10217
  `))
10008
10218
  };
10009
10219
  for (const item of orderByDependencies(pending)) {
@@ -10012,7 +10222,7 @@ async function fillPendingInputs(actionCommand) {
10012
10222
  ctx.known.set(item.input.name, value);
10013
10223
  }
10014
10224
  const log = env.log ?? ((line) => console.log(line));
10015
- log(chalk36.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
10225
+ log(chalk35.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
10016
10226
  }
10017
10227
  function commandChain(cmd) {
10018
10228
  const chain = [];
@@ -10109,7 +10319,7 @@ Docs: https://diafunc.com/documentation
10109
10319
  function createProgram(environment = {}) {
10110
10320
  const program = new DiafuncCommand();
10111
10321
  program.promptEnvironment = environment;
10112
- program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
10322
+ program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
10113
10323
  // Commander writes usage errors to stdout by default, which puts a complaint in the middle
10114
10324
  // of whatever a caller was capturing.
10115
10325
  writeErr: (str) => process.stderr.write(str)
@@ -10117,7 +10327,7 @@ function createProgram(environment = {}) {
10117
10327
  const opts = thisCommand.optsWithGlobals();
10118
10328
  if (opts.dryRun) setDryRun(true);
10119
10329
  if (opts.verbose) setVerbose(true);
10120
- if (opts.color === false) chalk37.level = 0;
10330
+ if (opts.color === false) chalk36.level = 0;
10121
10331
  }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
10122
10332
  program.addHelpText("after", HELP_EPILOGUE);
10123
10333
  registerAuthCommands(program);
@@ -10159,4 +10369,4 @@ export {
10159
10369
  PromptCancelled,
10160
10370
  createProgram
10161
10371
  };
10162
- //# sourceMappingURL=chunk-4NQYIRPF.js.map
10372
+ //# sourceMappingURL=chunk-EJLRB75G.js.map