@diafunc/cli 0.3.1 → 0.4.1

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,67 +1,10 @@
1
+ import {
2
+ package_default
3
+ } from "./chunk-FCWSWCFN.js";
4
+
1
5
  // src/index.ts
2
6
  import { Command } from "commander";
3
7
 
4
- // package.json
5
- var package_default = {
6
- name: "@diafunc/cli",
7
- version: "0.3.1",
8
- description: "Diafunc CLI \u2014 command-line interface for the Diafunc platform",
9
- type: "module",
10
- bin: {
11
- diafunc: "./dist/bin/diafunc.js"
12
- },
13
- homepage: "https://diafunc.com",
14
- repository: {
15
- type: "git",
16
- url: "git+https://gitlab.com/diafunc/cli.git"
17
- },
18
- bugs: {
19
- url: "https://gitlab.com/diafunc/cli/-/issues"
20
- },
21
- author: "Markus Pollak <markus.pollak@diafunc.com>",
22
- scripts: {
23
- build: `tsup && node -e "const fs=require('fs');const f='dist/bin/diafunc.js';fs.writeFileSync(f,'#!/usr/bin/env node\\n'+fs.readFileSync(f,'utf8'))"`,
24
- dev: "tsup --watch",
25
- test: "vitest run",
26
- "test:watch": "vitest",
27
- lint: "tsc --noEmit",
28
- start: "node dist/bin/diafunc.js",
29
- prepublishOnly: "npm run lint && npm test && npm run build"
30
- },
31
- files: [
32
- "dist",
33
- "LICENSE",
34
- "README.md"
35
- ],
36
- keywords: [
37
- "diafunc",
38
- "cli",
39
- "data-science",
40
- "symbolic-regression"
41
- ],
42
- license: "Apache-2.0",
43
- publishConfig: {
44
- access: "public",
45
- registry: "https://registry.npmjs.org/"
46
- },
47
- engines: {
48
- node: ">=20.0.0"
49
- },
50
- dependencies: {
51
- "@inquirer/prompts": "^7.0.0",
52
- chalk: "^5.4.0",
53
- "cli-table3": "^0.6.5",
54
- commander: "^12.1.0",
55
- ora: "^8.1.0"
56
- },
57
- devDependencies: {
58
- "@types/node": "^22.0.0",
59
- tsup: "^8.3.0",
60
- typescript: "^5.6.0",
61
- vitest: "^2.1.0"
62
- }
63
- };
64
-
65
8
  // src/commands/auth/login.ts
66
9
  import chalk2 from "chalk";
67
10
 
@@ -149,8 +92,8 @@ var NetworkError = class extends Error {
149
92
  };
150
93
 
151
94
  // src/client/http.ts
152
- function buildUrl(endpoint, service, path7, query) {
153
- const base = `${endpoint}/api/v1/${service}${path7}`;
95
+ function buildUrl(endpoint, service, path9, query) {
96
+ const base = `${endpoint}/api/v1/${service}${path9}`;
154
97
  const params = new URLSearchParams();
155
98
  if (query) {
156
99
  for (const [key, value] of Object.entries(query)) {
@@ -1046,6 +989,30 @@ var PRESETS_SERVICE = "analysis-presets";
1046
989
  var TRIGGERS_SERVICE = "triggers";
1047
990
  function createAnalysisService(client) {
1048
991
  return {
992
+ // ----- Lifecycle: create / read / replace / delete --------------------------------
993
+ async create(request) {
994
+ return client.request({
995
+ method: "POST",
996
+ service: SERVICE2,
997
+ path: "/",
998
+ body: request
999
+ });
1000
+ },
1001
+ async update(analysisId, request) {
1002
+ return client.request({
1003
+ method: "PUT",
1004
+ service: SERVICE2,
1005
+ path: `/${encodeURIComponent(analysisId)}`,
1006
+ body: request
1007
+ });
1008
+ },
1009
+ async delete(analysisId) {
1010
+ return client.request({
1011
+ method: "DELETE",
1012
+ service: SERVICE2,
1013
+ path: `/${encodeURIComponent(analysisId)}`
1014
+ });
1015
+ },
1049
1016
  async getLast() {
1050
1017
  return client.request({
1051
1018
  method: "GET",
@@ -1068,34 +1035,120 @@ function createAnalysisService(client) {
1068
1035
  path: `/${encodeURIComponent(analysisId)}`
1069
1036
  });
1070
1037
  },
1071
- async save(analysis) {
1038
+ // ----- Typed PATCH per editable field --------------------------------------------
1039
+ async patchName(analysisId, request) {
1040
+ return client.request({
1041
+ method: "PATCH",
1042
+ service: SERVICE2,
1043
+ path: `/${encodeURIComponent(analysisId)}/name`,
1044
+ body: request
1045
+ });
1046
+ },
1047
+ async patchDescription(analysisId, request) {
1048
+ return client.request({
1049
+ method: "PATCH",
1050
+ service: SERVICE2,
1051
+ path: `/${encodeURIComponent(analysisId)}/description`,
1052
+ body: request
1053
+ });
1054
+ },
1055
+ async patchVisibility(analysisId, request) {
1056
+ return client.request({
1057
+ method: "PATCH",
1058
+ service: SERVICE2,
1059
+ path: `/${encodeURIComponent(analysisId)}/visibility`,
1060
+ body: request
1061
+ });
1062
+ },
1063
+ async patchIntroduction(analysisId, request) {
1064
+ return client.request({
1065
+ method: "PATCH",
1066
+ service: SERVICE2,
1067
+ path: `/${encodeURIComponent(analysisId)}/introduction`,
1068
+ body: request
1069
+ });
1070
+ },
1071
+ async patchHours(analysisId, request) {
1072
+ return client.request({
1073
+ method: "PATCH",
1074
+ service: SERVICE2,
1075
+ path: `/${encodeURIComponent(analysisId)}/hours`,
1076
+ body: request
1077
+ });
1078
+ },
1079
+ async patchBudget(analysisId, request) {
1080
+ return client.request({
1081
+ method: "PATCH",
1082
+ service: SERVICE2,
1083
+ path: `/${encodeURIComponent(analysisId)}/budget`,
1084
+ body: request
1085
+ });
1086
+ },
1087
+ async patchTargets(analysisId, request) {
1088
+ return client.request({
1089
+ method: "PATCH",
1090
+ service: SERVICE2,
1091
+ path: `/${encodeURIComponent(analysisId)}/targets`,
1092
+ body: request
1093
+ });
1094
+ },
1095
+ async patchQuestions(analysisId, request) {
1096
+ return client.request({
1097
+ method: "PATCH",
1098
+ service: SERVICE2,
1099
+ path: `/${encodeURIComponent(analysisId)}/questions`,
1100
+ body: request
1101
+ });
1102
+ },
1103
+ async patchSegment(analysisId, request) {
1104
+ return client.request({
1105
+ method: "PATCH",
1106
+ service: SERVICE2,
1107
+ path: `/${encodeURIComponent(analysisId)}/segment`,
1108
+ body: request
1109
+ });
1110
+ },
1111
+ // ----- Data ingest ----------------------------------------------------------------
1112
+ async uploadDataMultipart(analysisId, formData) {
1072
1113
  return client.request({
1073
1114
  method: "POST",
1074
1115
  service: SERVICE2,
1075
- path: "/",
1076
- body: analysis
1116
+ path: `/${encodeURIComponent(analysisId)}/data`,
1117
+ rawBody: formData
1077
1118
  });
1078
1119
  },
1079
- /**
1080
- * Combined create-and-run in one round-trip. Body is a fresh recipe (analysisId
1081
- * must be null); server saves it and queues a run. Returns AnalysisRun with
1082
- * analysisId populated. Preferred over save+rerun for one-shot tools.
1083
- */
1084
- async createAndRun(analysis) {
1120
+ async uploadDataUrl(analysisId, request) {
1085
1121
  return client.request({
1086
1122
  method: "POST",
1087
1123
  service: SERVICE2,
1088
- path: "/runs",
1089
- body: analysis
1124
+ path: `/${encodeURIComponent(analysisId)}/data/url`,
1125
+ body: request
1090
1126
  });
1091
1127
  },
1092
- /**
1093
- * Enqueues a new run for an existing analysis recipe. Returns the newly created
1094
- * run in state QUEUED; the dispatcher pool picks it up within ~5s and transitions
1095
- * it through DISPATCHING -> RUNNING -> COMPLETED / FAILED. Poll getRun(runId) to
1096
- * follow progress.
1097
- */
1098
- async rerun(analysisId) {
1128
+ async uploadDataInline(analysisId, request) {
1129
+ return client.request({
1130
+ method: "POST",
1131
+ service: SERVICE2,
1132
+ path: `/${encodeURIComponent(analysisId)}/data/inline`,
1133
+ body: request
1134
+ });
1135
+ },
1136
+ async getColumns(analysisId) {
1137
+ return client.request({
1138
+ method: "GET",
1139
+ service: SERVICE2,
1140
+ path: `/${encodeURIComponent(analysisId)}/columns`
1141
+ });
1142
+ },
1143
+ async getNavigation(analysisId) {
1144
+ return client.request({
1145
+ method: "GET",
1146
+ service: SERVICE2,
1147
+ path: `/${encodeURIComponent(analysisId)}/navigation`
1148
+ });
1149
+ },
1150
+ // ----- Runs -----------------------------------------------------------------------
1151
+ async runAnalysis(analysisId) {
1099
1152
  return client.request({
1100
1153
  method: "POST",
1101
1154
  service: SERVICE2,
@@ -1124,7 +1177,14 @@ function createAnalysisService(client) {
1124
1177
  path: `/${encodeURIComponent(runId)}/cancel`
1125
1178
  });
1126
1179
  },
1127
- // ---------- presets ----------
1180
+ async getRunOutputs(analysisId, runId) {
1181
+ return client.request({
1182
+ method: "GET",
1183
+ service: SERVICE2,
1184
+ path: `/${encodeURIComponent(analysisId)}/runs/${encodeURIComponent(runId)}/outputs`
1185
+ });
1186
+ },
1187
+ // ----- Presets --------------------------------------------------------------------
1128
1188
  async getPresets() {
1129
1189
  return client.request({
1130
1190
  method: "GET",
@@ -1154,7 +1214,7 @@ function createAnalysisService(client) {
1154
1214
  path: `/${encodeURIComponent(presetId)}`
1155
1215
  });
1156
1216
  },
1157
- // ---------- triggers ----------
1217
+ // ----- Triggers -------------------------------------------------------------------
1158
1218
  async createTrigger(analysisId, body) {
1159
1219
  return client.request({
1160
1220
  method: "POST",
@@ -1337,14 +1397,14 @@ function createStorageService(client) {
1337
1397
  });
1338
1398
  },
1339
1399
  async deleteLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch) {
1340
- let path7 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
1400
+ let path9 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
1341
1401
  if (targetEntityId && targetEntityBranch) {
1342
- path7 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
1402
+ path9 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
1343
1403
  }
1344
1404
  return client.request({
1345
1405
  method: "DELETE",
1346
1406
  service: SERVICE3,
1347
- path: path7
1407
+ path: path9
1348
1408
  });
1349
1409
  },
1350
1410
  // --- Events ---
@@ -2033,8 +2093,8 @@ function registerConfigCommands(program) {
2033
2093
  console.log(chalk7.green(`Profile "${name}" removed.`));
2034
2094
  });
2035
2095
  }
2036
- function setNestedValue(obj, path7, value) {
2037
- const keys = path7.split(".");
2096
+ function setNestedValue(obj, path9, value) {
2097
+ const keys = path9.split(".");
2038
2098
  let current = obj;
2039
2099
  for (let i = 0; i < keys.length - 1; i++) {
2040
2100
  const key = keys[i];
@@ -2045,8 +2105,8 @@ function setNestedValue(obj, path7, value) {
2045
2105
  }
2046
2106
  current[keys[keys.length - 1]] = value;
2047
2107
  }
2048
- function getNestedValue(obj, path7) {
2049
- const keys = path7.split(".");
2108
+ function getNestedValue(obj, path9) {
2109
+ const keys = path9.split(".");
2050
2110
  let current = obj;
2051
2111
  for (const key of keys) {
2052
2112
  if (current === null || current === void 0 || typeof current !== "object") {
@@ -2596,8 +2656,8 @@ function registerEventCommands(program) {
2596
2656
  });
2597
2657
  event.command("create").description("Create one or more events (body from JSON file or stdin)").argument("[file]", "JSON file containing a BareEvent array; defaults to stdin").action(async (file) => {
2598
2658
  try {
2599
- const fs9 = await import("fs");
2600
- const body = file ? fs9.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
2659
+ const fs11 = await import("fs");
2660
+ const body = file ? fs11.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
2601
2661
  let data = "";
2602
2662
  process.stdin.setEncoding("utf-8");
2603
2663
  process.stdin.on("data", (chunk) => {
@@ -3633,11 +3693,14 @@ Error: ${event.content}`));
3633
3693
  }
3634
3694
  async function runChatRepl(options) {
3635
3695
  const { input: promptInput } = await import("@inquirer/prompts");
3696
+ const { getUpdateNotice } = await import("./update-check-4DNIH3LQ.js");
3636
3697
  let sessionId = options.session;
3637
3698
  console.log(chalk17.bold("Diafunc chat") + chalk17.dim(" \xB7 /help for commands, /quit to exit"));
3638
3699
  if (sessionId) {
3639
3700
  console.log(chalk17.dim(`Continuing session ${sessionId}`));
3640
3701
  }
3702
+ const notice = await getUpdateNotice();
3703
+ if (notice) console.log(chalk17.dim(notice));
3641
3704
  console.log();
3642
3705
  for (; ; ) {
3643
3706
  let line;
@@ -4183,8 +4246,8 @@ import chalk20 from "chalk";
4183
4246
  function createStatusService() {
4184
4247
  const config = loadConfig();
4185
4248
  const endpoint = resolveEndpoint(config);
4186
- async function fetchJson(path7) {
4187
- const url = `${endpoint}/status/v1${path7}`;
4249
+ async function fetchJson(path9) {
4250
+ const url = `${endpoint}/status/v1${path9}`;
4188
4251
  const response = await fetch(url, {
4189
4252
  headers: { "Accept": "application/json" }
4190
4253
  });
@@ -4370,54 +4433,6 @@ import chalk23 from "chalk";
4370
4433
  import * as fs6 from "fs";
4371
4434
  import * as path5 from "path";
4372
4435
  import { spawn as spawn2 } from "child_process";
4373
- import { randomUUID as randomUUID3 } from "crypto";
4374
- function createEntity(projectId, entityId, entityType, name, description, attributes, tags, contentType, content) {
4375
- const now = Date.now();
4376
- const entity = {
4377
- projectId,
4378
- projectBranch: "main",
4379
- entityId,
4380
- entityBranch: "main",
4381
- head: true,
4382
- version: 1,
4383
- type: entityType,
4384
- attributes: {},
4385
- attributeTypes: {},
4386
- metaAttributes: {},
4387
- metaAttributeTypes: {},
4388
- tags,
4389
- modified: now,
4390
- created: now,
4391
- versioned: false,
4392
- versionTtl: null,
4393
- retain: false,
4394
- contentAvailable: content !== null,
4395
- contentLoaded: content !== null,
4396
- contentType,
4397
- contentSize: null,
4398
- content
4399
- };
4400
- if (name !== null) {
4401
- entity.attributeTypes["name"] = "text";
4402
- entity.attributes["name"] = name;
4403
- }
4404
- if (description !== null) {
4405
- entity.attributeTypes["description"] = "text";
4406
- entity.attributes["description"] = description;
4407
- }
4408
- if (attributes) {
4409
- for (const [key, value] of Object.entries(attributes)) {
4410
- if (typeof value === "string") {
4411
- entity.attributeTypes[key] = "text";
4412
- entity.attributes[key] = value;
4413
- } else if (typeof value === "number") {
4414
- entity.attributeTypes[key] = "integer";
4415
- entity.attributes[key] = String(value);
4416
- }
4417
- }
4418
- }
4419
- return entity;
4420
- }
4421
4436
  function formatDuration(ms) {
4422
4437
  const seconds = Math.floor(ms / 1e3);
4423
4438
  const minutes = Math.floor(seconds / 60);
@@ -4426,9 +4441,6 @@ function formatDuration(ms) {
4426
4441
  if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
4427
4442
  return `${seconds}s`;
4428
4443
  }
4429
- function analysisUrl(analysis, endpoint) {
4430
- return `${endpoint}/lab/${analysis.projectId}/main/entities/${analysis.notebookId}/main`;
4431
- }
4432
4444
  function openUrl(url) {
4433
4445
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
4434
4446
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -4443,125 +4455,62 @@ function parseCsv(value) {
4443
4455
  if (value === void 0) return null;
4444
4456
  return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4445
4457
  }
4458
+ function parseVisibility(value) {
4459
+ const upper = value.toUpperCase();
4460
+ if (upper !== "PRIVATE" && upper !== "PUBLIC") {
4461
+ throw new Error(`Invalid visibility "${value}" \u2014 must be PRIVATE or PUBLIC.`);
4462
+ }
4463
+ return upper;
4464
+ }
4446
4465
  function isTerminalState(state) {
4447
4466
  return state === "COMPLETED" || state === "FAILED" || state === "CANCELLED";
4448
4467
  }
4468
+ function multipartFromFile(file) {
4469
+ const buffer = fs6.readFileSync(file);
4470
+ const blob = new Blob([buffer]);
4471
+ const formData = new FormData();
4472
+ formData.append("content", blob, path5.basename(file));
4473
+ return formData;
4474
+ }
4449
4475
  async function runAnalysis(file, options, cmd) {
4450
4476
  if (!fs6.existsSync(file)) {
4451
4477
  console.error(chalk23.red(`File not found: ${file}`));
4452
4478
  process.exit(1);
4453
4479
  }
4454
4480
  const api = createApiClient();
4455
- const projectName = options.name ?? path5.basename(file, path5.extname(file));
4456
- const visibility = options.visibility.toUpperCase();
4457
- const recipe = {
4458
- userId: null,
4459
- analysisId: null,
4460
- phase: "PREPARATION",
4461
- step: "LAUNCH_ANALYSIS",
4462
- projectName,
4463
- projectDescription: options.description,
4481
+ const visibility = parseVisibility(options.visibility);
4482
+ const name = options.name ?? path5.basename(file, path5.extname(file));
4483
+ const request = {
4484
+ name,
4485
+ description: options.description || null,
4464
4486
  visibility,
4465
- time: options.time,
4487
+ introduction: options.introduction ?? null,
4488
+ hours: options.hours,
4466
4489
  budget: options.budget,
4467
- projectId: null,
4468
- notebookId: null,
4469
- rawDataTableId: null,
4470
- analysisFunctionId: null,
4471
- analysisChapterId: null,
4472
- year: null,
4473
- month: null,
4474
- day: null,
4475
- hour: null,
4476
- evaluationId: null,
4477
- started: null,
4478
- targetKeys: parseCsv(options.targets),
4490
+ targets: parseCsv(options.targets),
4479
4491
  questions: parseCsv(options.questions),
4480
- segmentKey: options.segment ?? null
4492
+ segment: options.segment ?? null
4481
4493
  };
4482
- process.stdout.write(`Creating project "${projectName}" ...`);
4483
- const { projectId, rawDataTableId } = await provisionProject(api, recipe);
4484
- recipe.projectId = projectId;
4485
- recipe.rawDataTableId = rawDataTableId;
4494
+ process.stdout.write(`Creating analysis "${name}" ...`);
4495
+ const created = await api.analysis.create(request);
4486
4496
  console.log(chalk23.green(" done"));
4487
- process.stdout.write(`Importing ${path5.basename(file)} ...`);
4488
- await importData(api, projectId, rawDataTableId, file);
4497
+ console.log(chalk23.dim(` analysisId: ${created.analysisId}`));
4498
+ process.stdout.write(`Uploading ${path5.basename(file)} ...`);
4499
+ await api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file));
4489
4500
  console.log(chalk23.green(" done"));
4490
4501
  process.stdout.write("Queuing analysis run ...");
4491
- const run = await api.analysis.createAndRun(recipe);
4502
+ const run = await api.analysis.runAnalysis(created.analysisId);
4492
4503
  console.log(chalk23.green(" done"));
4493
- console.log(chalk23.dim(` analysisId: ${run.analysisId}`));
4494
4504
  console.log(chalk23.dim(` runId: ${run.runId}`));
4495
4505
  console.log();
4496
- await monitorRun(api, run.runId, recipe, cmd);
4497
- }
4498
- async function provisionProject(api, recipe) {
4499
- const project = await api.admin.createProject({
4500
- visibility: recipe.visibility,
4501
- language: "Java",
4502
- active: true
4503
- });
4504
- await api.storage.createProjectBranch({
4505
- projectId: project.projectId,
4506
- sourceProjectBranch: null,
4507
- targetProjectBranch: "main"
4508
- });
4509
- const projectEntity = createEntity(
4510
- project.projectId,
4511
- project.projectId,
4512
- "project",
4513
- recipe.projectName,
4514
- recipe.projectDescription,
4515
- null,
4516
- [],
4517
- null,
4518
- null
4519
- );
4520
- await api.storage.saveEntities([projectEntity]);
4521
- const rawDataTableId = randomUUID3();
4522
- const rawDataTable = createEntity(
4523
- project.projectId,
4524
- rawDataTableId,
4525
- "table",
4526
- "Raw Data Table",
4527
- null,
4528
- null,
4529
- [],
4530
- null,
4531
- null
4532
- );
4533
- await api.storage.saveEntities([rawDataTable]);
4534
- return { projectId: project.projectId, rawDataTableId };
4535
- }
4536
- async function importData(api, projectId, rawDataTableId, file) {
4537
- const ref = {
4538
- projectId,
4539
- projectBranch: "main",
4540
- entityId: rawDataTableId,
4541
- entityBranch: "main"
4542
- };
4543
- const fileBuffer = fs6.readFileSync(file);
4544
- const blob = new Blob([fileBuffer]);
4545
- const formData = new FormData();
4546
- formData.append("content", blob, path5.basename(file));
4547
- const importId = await api.storage.importTable(ref, formData, true);
4548
- for (let i = 0; i < 300; i++) {
4549
- await new Promise((resolve) => setTimeout(resolve, 1e3));
4550
- const imp = await api.storage.getImport(ref, importId);
4551
- if (imp.finished !== null) {
4552
- if (!imp.succeeded) throw new Error(`Import failed: ${imp.error}`);
4553
- return;
4554
- }
4555
- }
4556
- throw new Error("Import did not finish within 5 minutes");
4506
+ await monitorRun(api, created.analysisId, run.runId, parseFloat(options.hours), cmd);
4557
4507
  }
4558
- async function monitorRun(api, runId, recipe, cmd) {
4508
+ async function monitorRun(api, analysisId, runId, hoursForProgress, cmd) {
4559
4509
  const config = loadConfig();
4560
4510
  const outputFormat = getOutputFormat14(cmd);
4561
- const computationMs = parseFloat(recipe.time) * 60 * 60 * 1e3;
4511
+ const computationMs = hoursForProgress * 60 * 60 * 1e3;
4562
4512
  const startMs = Date.now();
4563
4513
  const seenOutputIds = /* @__PURE__ */ new Set();
4564
- let observedAnalysisId = recipe.analysisId;
4565
4514
  for (let i = 0; ; i++) {
4566
4515
  await new Promise((resolve) => setTimeout(resolve, 2e3));
4567
4516
  let run = null;
@@ -4571,20 +4520,17 @@ async function monitorRun(api, runId, recipe, cmd) {
4571
4520
  } catch {
4572
4521
  }
4573
4522
  if (!run) continue;
4574
- if (run.analysisId) observedAnalysisId = run.analysisId;
4575
- if (run.evaluationId && recipe.projectId) {
4576
- try {
4577
- const outputs = await api.evaluation.getOutputs(recipe.projectId, run.evaluationId);
4578
- for (const out of outputs) {
4579
- if (!seenOutputIds.has(out.outputId)) {
4580
- seenOutputIds.add(out.outputId);
4581
- if (outputFormat === "human") {
4582
- console.log(` ${chalk23.dim("Output:")} ${out.output}`);
4583
- }
4523
+ try {
4524
+ const outputs = await api.analysis.getRunOutputs(analysisId, runId);
4525
+ for (const out of outputs) {
4526
+ if (!seenOutputIds.has(out.outputId)) {
4527
+ seenOutputIds.add(out.outputId);
4528
+ if (outputFormat === "human") {
4529
+ console.log(` ${chalk23.dim("Output:")} ${out.output}`);
4584
4530
  }
4585
4531
  }
4586
- } catch {
4587
4532
  }
4533
+ } catch {
4588
4534
  }
4589
4535
  if (isTerminalState(run.state)) {
4590
4536
  console.log();
@@ -4594,42 +4540,27 @@ async function monitorRun(api, runId, recipe, cmd) {
4594
4540
  if (run.state === "COMPLETED") {
4595
4541
  if (outputFormat === "human") {
4596
4542
  console.log(chalk23.green(`Analysis complete! (${durationStr})`));
4597
- if (observedAnalysisId) {
4598
- try {
4599
- const opt = await api.analysis.get(observedAnalysisId);
4600
- if (opt.analysis?.notebookId) {
4601
- const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
4602
- console.log(` Project: ${analysisUrl(opt.analysis, endpoint)}`);
4603
- }
4604
- } catch {
4605
- }
4543
+ try {
4544
+ const nav = await api.analysis.getNavigation(analysisId);
4545
+ const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
4546
+ console.log(` Project: ${endpoint}${nav.labUrl}`);
4547
+ } catch {
4606
4548
  }
4607
4549
  } else {
4608
- format({
4609
- status: "completed",
4610
- runId,
4611
- analysisId: observedAnalysisId,
4612
- duration,
4613
- projectId: recipe.projectId
4614
- }, { format: outputFormat });
4550
+ format({ status: "completed", runId, analysisId, duration }, { format: outputFormat });
4615
4551
  }
4616
4552
  } else if (run.state === "CANCELLED") {
4617
4553
  if (outputFormat === "human") {
4618
4554
  console.log(chalk23.yellow("Analysis cancelled."));
4619
4555
  } else {
4620
- format({ status: "cancelled", runId, analysisId: observedAnalysisId }, { format: outputFormat });
4556
+ format({ status: "cancelled", runId, analysisId }, { format: outputFormat });
4621
4557
  }
4622
4558
  } else {
4623
4559
  if (outputFormat === "human") {
4624
4560
  console.log(chalk23.red("Analysis failed."));
4625
4561
  if (run.errorMessage) console.log(` Error: ${run.errorMessage}`);
4626
4562
  } else {
4627
- format({
4628
- status: "failed",
4629
- runId,
4630
- analysisId: observedAnalysisId,
4631
- error: run.errorMessage
4632
- }, { format: outputFormat });
4563
+ format({ status: "failed", runId, analysisId, error: run.errorMessage }, { format: outputFormat });
4633
4564
  }
4634
4565
  }
4635
4566
  return;
@@ -4649,17 +4580,18 @@ async function listAnalyses(limit, cmd) {
4649
4580
  const outputFormat = getOutputFormat14(cmd);
4650
4581
  const api = createApiClient();
4651
4582
  const analyses = await api.analysis.getRecent(limit);
4652
- const rows = analyses.map((a) => ({
4653
- analysisId: a.analysisId ?? "\u2014",
4654
- projectName: a.projectName ?? "\u2014",
4655
- projectId: a.projectId ?? "\u2014",
4656
- phase: a.phase,
4657
- step: a.step,
4658
- started: a.started ? new Date(a.started).toISOString() : "\u2014"
4659
- }));
4660
- format(rows, {
4583
+ format(analyses.map((a) => ({
4584
+ analysisId: a.analysisId,
4585
+ name: a.name,
4586
+ visibility: a.visibility,
4587
+ hours: a.hours,
4588
+ budget: a.budget,
4589
+ targets: (a.targets ?? []).join(", "),
4590
+ latestRunState: a.latestRunState ?? "\u2014",
4591
+ createdAt: a.createdAt ?? "\u2014"
4592
+ })), {
4661
4593
  format: outputFormat,
4662
- columns: ["analysisId", "projectName", "phase", "step", "started"]
4594
+ columns: ["analysisId", "name", "visibility", "hours", "budget", "targets", "latestRunState", "createdAt"]
4663
4595
  });
4664
4596
  }
4665
4597
  async function getAnalysisDetails(analysisId, cmd) {
@@ -4680,10 +4612,6 @@ async function watchAnalysis(analysisId, cmd) {
4680
4612
  return;
4681
4613
  }
4682
4614
  const recipe = result.analysis;
4683
- if (!recipe.analysisId) {
4684
- console.log(chalk23.dim("Analysis has no analysisId yet."));
4685
- return;
4686
- }
4687
4615
  const runs = await api.analysis.getRunsForAnalysis(recipe.analysisId, 1);
4688
4616
  if (runs.length === 0) {
4689
4617
  console.log(chalk23.dim("No runs for this analysis."));
@@ -4692,102 +4620,123 @@ async function watchAnalysis(analysisId, cmd) {
4692
4620
  const latest = runs[0];
4693
4621
  if (isTerminalState(latest.state)) {
4694
4622
  console.log(chalk23.green(`Latest run already in terminal state: ${latest.state}`));
4695
- if (recipe.projectId && recipe.notebookId) {
4623
+ try {
4624
+ const nav = await api.analysis.getNavigation(recipe.analysisId);
4696
4625
  const config = loadConfig();
4697
4626
  const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
4698
- console.log(` Project: ${analysisUrl(recipe, endpoint)}`);
4627
+ console.log(` Project: ${endpoint}${nav.labUrl}`);
4628
+ } catch {
4699
4629
  }
4700
4630
  return;
4701
4631
  }
4702
4632
  console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
4703
- await monitorRun(api, latest.runId, recipe, cmd);
4633
+ await monitorRun(api, recipe.analysisId, latest.runId, parseFloat(recipe.hours), cmd);
4704
4634
  }
4705
4635
  async function rerunAnalysis(analysisId) {
4706
4636
  const api = createApiClient();
4707
- const run = await api.analysis.rerun(analysisId);
4637
+ const run = await api.analysis.runAnalysis(analysisId);
4708
4638
  console.log(chalk23.green(`\u2713 Queued new run ${run.runId} for analysis ${analysisId}`));
4709
4639
  console.log(chalk23.dim(` State: ${run.state}`));
4710
4640
  console.log();
4711
- console.log(chalk23.dim("The dispatcher picks up queued runs every few seconds."));
4712
- console.log(chalk23.dim(`Track progress: diafunc analyze watch ${analysisId}`));
4641
+ console.log(chalk23.dim("Track progress: diafunc analyze watch " + analysisId));
4713
4642
  }
4714
4643
  async function openAnalysis(analysisId) {
4715
4644
  const api = createApiClient();
4716
4645
  const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
4717
- if (!result.analysis?.projectId) {
4718
- console.log(chalk23.dim("No analysis found (or analysis has no project yet)."));
4646
+ if (!result.analysis) {
4647
+ console.log(chalk23.dim("No analysis found."));
4719
4648
  return;
4720
4649
  }
4721
4650
  const config = loadConfig();
4722
4651
  const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
4723
- const url = analysisUrl(result.analysis, endpoint);
4724
- console.log(`Opening ${url} ...`);
4725
- openUrl(url);
4652
+ try {
4653
+ const nav = await api.analysis.getNavigation(result.analysis.analysisId);
4654
+ const url = `${endpoint}${nav.labUrl}`;
4655
+ console.log(`Opening ${url} ...`);
4656
+ openUrl(url);
4657
+ } catch {
4658
+ console.log(chalk23.dim("Notebook not yet provisioned \u2014 run the analysis first."));
4659
+ }
4726
4660
  }
4727
4661
  async function createRecipe(options, cmd) {
4728
4662
  const outputFormat = getOutputFormat14(cmd);
4729
4663
  const api = createApiClient();
4730
- const visibility = options.visibility.toUpperCase();
4731
- const recipe = {
4732
- userId: null,
4733
- analysisId: null,
4734
- phase: "PREPARATION",
4735
- step: "LAUNCH_ANALYSIS",
4736
- projectName: options.name ?? "CLI Analysis",
4737
- projectDescription: options.description ?? "",
4664
+ const visibility = parseVisibility(options.visibility);
4665
+ const request = {
4666
+ name: options.name ?? "CLI Analysis",
4667
+ description: options.description ?? null,
4738
4668
  visibility,
4739
- time: options.hours,
4740
- budget: options.budget,
4741
- projectId: options.projectId,
4742
- notebookId: null,
4743
- rawDataTableId: options.rawDataTableId,
4744
- analysisFunctionId: null,
4745
- analysisChapterId: null,
4746
- year: null,
4747
- month: null,
4748
- day: null,
4749
- hour: null,
4750
- evaluationId: null,
4751
- started: null,
4752
- targetKeys: parseCsv(options.targets),
4669
+ introduction: options.introduction ?? null,
4670
+ hours: options.hours ?? null,
4671
+ budget: options.budget ?? null,
4672
+ targets: parseCsv(options.targets),
4753
4673
  questions: parseCsv(options.questions),
4754
- segmentKey: options.segment ?? null
4674
+ segment: options.segment ?? null
4755
4675
  };
4756
- const saved = await api.analysis.save(recipe);
4757
- format(saved, { format: outputFormat });
4676
+ const created = await api.analysis.create(request);
4677
+ format(created, { format: outputFormat });
4678
+ }
4679
+ async function deleteAnalysis(analysisId) {
4680
+ const api = createApiClient();
4681
+ await api.analysis.delete(analysisId);
4682
+ console.log(chalk23.green(`\u2713 Deleted analysis ${analysisId}`));
4758
4683
  }
4759
- async function updateRecipe(analysisId, options, cmd) {
4684
+ async function patchAndPrint(analysisId, value, handler, successLabel, cmd) {
4760
4685
  const outputFormat = getOutputFormat14(cmd);
4761
4686
  const api = createApiClient();
4762
- const opt = await api.analysis.get(analysisId);
4763
- if (!opt.analysis) {
4764
- console.error(chalk23.red(`Analysis not found: ${analysisId}`));
4687
+ const updated = await handler(api, analysisId, value);
4688
+ if (outputFormat === "human") {
4689
+ console.log(chalk23.green(`\u2713 ${successLabel} updated for analysis ${analysisId}`));
4690
+ } else {
4691
+ format(updated, { format: outputFormat });
4692
+ }
4693
+ }
4694
+ async function uploadData(analysisId, file, options) {
4695
+ const api = createApiClient();
4696
+ if (options.url) {
4697
+ if (file) {
4698
+ console.error(chalk23.red("Provide either a file or --url, not both."));
4699
+ process.exit(1);
4700
+ }
4701
+ process.stdout.write(`Uploading from ${options.url} ...`);
4702
+ await api.analysis.uploadDataUrl(analysisId, { dataUrl: options.url });
4703
+ console.log(chalk23.green(" done"));
4704
+ return;
4705
+ }
4706
+ if (!file) {
4707
+ console.error(chalk23.red("Provide a file path or --url <URL>."));
4765
4708
  process.exit(1);
4766
4709
  }
4767
- const recipe = opt.analysis;
4768
- if (options.targets !== void 0) recipe.targetKeys = parseCsv(options.targets);
4769
- if (options.hours !== void 0) recipe.time = options.hours;
4770
- if (options.budget !== void 0) recipe.budget = options.budget;
4771
- if (options.questions !== void 0) recipe.questions = parseCsv(options.questions);
4772
- if (options.segment !== void 0) recipe.segmentKey = options.segment;
4773
- if (options.name !== void 0) recipe.projectName = options.name;
4774
- if (options.description !== void 0) recipe.projectDescription = options.description;
4775
- const saved = await api.analysis.save(recipe);
4776
- format(saved, { format: outputFormat });
4710
+ if (!fs6.existsSync(file)) {
4711
+ console.error(chalk23.red(`File not found: ${file}`));
4712
+ process.exit(1);
4713
+ }
4714
+ process.stdout.write(`Uploading ${path5.basename(file)} ...`);
4715
+ await api.analysis.uploadDataMultipart(analysisId, multipartFromFile(file));
4716
+ console.log(chalk23.green(" done"));
4717
+ }
4718
+ async function listColumns(analysisId, cmd) {
4719
+ const outputFormat = getOutputFormat14(cmd);
4720
+ const api = createApiClient();
4721
+ const columns = await api.analysis.getColumns(analysisId);
4722
+ if (columns.length === 0) {
4723
+ console.log(chalk23.dim("No columns yet \u2014 upload data first."));
4724
+ return;
4725
+ }
4726
+ format(columns, { format: outputFormat, columns: ["name", "valueType"] });
4777
4727
  }
4778
4728
  async function listRuns(analysisId, count, cmd) {
4779
4729
  const outputFormat = getOutputFormat14(cmd);
4780
4730
  const api = createApiClient();
4781
4731
  const runs = await api.analysis.getRunsForAnalysis(analysisId, count);
4782
- const rows = runs.map((r) => ({
4732
+ format(runs.map((r) => ({
4783
4733
  runId: r.runId,
4784
4734
  state: r.state,
4785
4735
  submittedAt: r.submittedAt ? new Date(r.submittedAt).toISOString() : "\u2014",
4786
4736
  startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : "\u2014",
4787
4737
  endedAt: r.endedAt ? new Date(r.endedAt).toISOString() : "\u2014",
4788
4738
  evaluationId: r.evaluationId ?? "\u2014"
4789
- }));
4790
- format(rows, {
4739
+ })), {
4791
4740
  format: outputFormat,
4792
4741
  columns: ["runId", "state", "submittedAt", "endedAt", "evaluationId"]
4793
4742
  });
@@ -4896,7 +4845,7 @@ async function toggleTrigger(triggerId, active, cmd) {
4896
4845
  }
4897
4846
  function registerAnalyzeCommand(program) {
4898
4847
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
4899
- analyze.argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Project name (derived from filename if omitted)").option("--description <text>", "Project description", "").option("--visibility <vis>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--time <hours>", "Computation time in hours", "4").option("--budget <credits>", "Credit budget", "400").option("--targets <keys>", "Comma-separated target column keys").option("--questions <list>", "Comma-separated questions to answer").option("--segment <key>", "Column key to segment the analysis by").action(async (file, options, cmd) => {
4848
+ analyze.argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Analysis name (derived from filename if omitted)").option("--description <text>", "Analysis description", "").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Computation time in hours", "4").option("--budget <credits>", "Credit budget", "400").option("--targets <csv>", "Comma-separated target column names").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").action(async (file, options, cmd) => {
4900
4849
  try {
4901
4850
  if (!file) {
4902
4851
  analyze.help();
@@ -4921,37 +4870,171 @@ function registerAnalyzeCommand(program) {
4921
4870
  handleError(error);
4922
4871
  }
4923
4872
  });
4924
- analyze.command("watch").description("Live-monitor the latest run of an analysis with progress and streaming outputs").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
4873
+ 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) => {
4925
4874
  try {
4926
4875
  await watchAnalysis(id, cmd);
4927
4876
  } catch (error) {
4928
4877
  handleError(error);
4929
4878
  }
4930
4879
  });
4931
- analyze.command("open").description("Open an analysis project in your browser").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id) => {
4880
+ analyze.command("open").description("Open an analysis notebook in your browser").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id) => {
4932
4881
  try {
4933
4882
  await openAnalysis(id);
4934
4883
  } catch (error) {
4935
4884
  handleError(error);
4936
4885
  }
4937
4886
  });
4938
- analyze.command("rerun").description("Rerun an existing analysis as a new run \u2014 reuses the recipe and data").argument("<id>", "Analysis ID to rerun").action(async (id) => {
4887
+ analyze.command("rerun").description("Queue a fresh run on an existing analysis").argument("<id>", "Analysis ID to rerun").action(async (id) => {
4939
4888
  try {
4940
4889
  await rerunAnalysis(id);
4941
4890
  } catch (error) {
4942
4891
  handleError(error);
4943
4892
  }
4944
4893
  });
4945
- analyze.command("create").description("Create a recipe without queuing a run (use `analyze rerun <id>` later to launch)").requiredOption("--project-id <id>", "Project ID hosting the raw-data table").requiredOption("--raw-data-table-id <id>", "Raw-data table entity ID").requiredOption("--targets <keys>", "Comma-separated target column keys").option("--hours <h>", "Computation hours", "4").option("--budget <credits>", "Credit budget", "400").option("--questions <list>", "Comma-separated questions").option("--segment <key>", "Segmentation column key").option("--name <name>", "Recipe name").option("--description <text>", "Recipe description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").action(async (options, cmd) => {
4894
+ 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) => {
4946
4895
  try {
4947
4896
  await createRecipe(options, cmd);
4948
4897
  } catch (error) {
4949
4898
  handleError(error);
4950
4899
  }
4951
4900
  });
4952
- analyze.command("update").description("Update fields of an existing analysis recipe").argument("<id>", "Analysis ID to update").option("--targets <keys>", "New comma-separated target keys").option("--hours <h>", "New compute hours").option("--budget <credits>", "New token budget").option("--questions <list>", "New comma-separated questions").option("--segment <key>", "New segment key").option("--name <name>", "New name").option("--description <text>", "New description").action(async (id, options, cmd) => {
4901
+ analyze.command("delete").description("Delete an analysis (cancels in-flight run; removes underlying project)").argument("<id>", "Analysis ID").action(async (id) => {
4902
+ try {
4903
+ await deleteAnalysis(id);
4904
+ } catch (error) {
4905
+ handleError(error);
4906
+ }
4907
+ });
4908
+ analyze.command("rename").description("Set the analysis name").argument("<id>", "Analysis ID").argument("<name>", "New name").action(async (id, name, _options, cmd) => {
4909
+ try {
4910
+ await patchAndPrint(
4911
+ id,
4912
+ name,
4913
+ (api, aid, v) => api.analysis.patchName(aid, { name: v }),
4914
+ "Name",
4915
+ cmd
4916
+ );
4917
+ } catch (error) {
4918
+ handleError(error);
4919
+ }
4920
+ });
4921
+ analyze.command("description").description("Set or clear the analysis description (empty string clears)").argument("<id>", "Analysis ID").argument("<text>", "New description (empty string to clear)").action(async (id, text, _options, cmd) => {
4922
+ try {
4923
+ await patchAndPrint(
4924
+ id,
4925
+ text,
4926
+ (api, aid, v) => api.analysis.patchDescription(aid, { description: v === "" ? null : v }),
4927
+ "Description",
4928
+ cmd
4929
+ );
4930
+ } catch (error) {
4931
+ handleError(error);
4932
+ }
4933
+ });
4934
+ analyze.command("visibility").description("Set analysis visibility (PRIVATE or PUBLIC)").argument("<id>", "Analysis ID").argument("<vis>", "PRIVATE or PUBLIC").action(async (id, vis, _options, cmd) => {
4935
+ try {
4936
+ const visibility = parseVisibility(vis);
4937
+ await patchAndPrint(
4938
+ id,
4939
+ visibility,
4940
+ (api, aid, v) => api.analysis.patchVisibility(aid, { visibility: v }),
4941
+ "Visibility",
4942
+ cmd
4943
+ );
4944
+ } catch (error) {
4945
+ handleError(error);
4946
+ }
4947
+ });
4948
+ analyze.command("introduction").description("Set or clear the markdown introduction").argument("<id>", "Analysis ID").argument("<markdown>", "New introduction (empty string to clear)").action(async (id, markdown, _options, cmd) => {
4949
+ try {
4950
+ await patchAndPrint(
4951
+ id,
4952
+ markdown,
4953
+ (api, aid, v) => api.analysis.patchIntroduction(aid, { introduction: v === "" ? null : v }),
4954
+ "Introduction",
4955
+ cmd
4956
+ );
4957
+ } catch (error) {
4958
+ handleError(error);
4959
+ }
4960
+ });
4961
+ 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) => {
4962
+ try {
4963
+ await patchAndPrint(
4964
+ id,
4965
+ hours,
4966
+ (api, aid, v) => api.analysis.patchHours(aid, { hours: v }),
4967
+ "Hours",
4968
+ cmd
4969
+ );
4970
+ } catch (error) {
4971
+ handleError(error);
4972
+ }
4973
+ });
4974
+ 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) => {
4953
4975
  try {
4954
- await updateRecipe(id, options, cmd);
4976
+ await patchAndPrint(
4977
+ id,
4978
+ credits,
4979
+ (api, aid, v) => api.analysis.patchBudget(aid, { budget: v }),
4980
+ "Budget",
4981
+ cmd
4982
+ );
4983
+ } catch (error) {
4984
+ handleError(error);
4985
+ }
4986
+ });
4987
+ analyze.command("targets").description("Set the target column names (comma-separated)").argument("<id>", "Analysis ID").argument("<csv>", "Comma-separated target column names").action(async (id, csv, _options, cmd) => {
4988
+ try {
4989
+ const targets = parseCsv(csv) ?? [];
4990
+ await patchAndPrint(
4991
+ id,
4992
+ csv,
4993
+ (api, aid) => api.analysis.patchTargets(aid, { targets }),
4994
+ "Targets",
4995
+ cmd
4996
+ );
4997
+ } catch (error) {
4998
+ handleError(error);
4999
+ }
5000
+ });
5001
+ analyze.command("questions").description("Set the questions list (comma-separated)").argument("<id>", "Analysis ID").argument("<csv>", "Comma-separated questions (empty string to clear)").action(async (id, csv, _options, cmd) => {
5002
+ try {
5003
+ const questions = parseCsv(csv) ?? [];
5004
+ await patchAndPrint(
5005
+ id,
5006
+ csv,
5007
+ (api, aid) => api.analysis.patchQuestions(aid, { questions }),
5008
+ "Questions",
5009
+ cmd
5010
+ );
5011
+ } catch (error) {
5012
+ handleError(error);
5013
+ }
5014
+ });
5015
+ analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name (empty string to clear)").action(async (id, name, _options, cmd) => {
5016
+ try {
5017
+ await patchAndPrint(
5018
+ id,
5019
+ name,
5020
+ (api, aid, v) => api.analysis.patchSegment(aid, { segment: v === "" ? null : v }),
5021
+ "Segment",
5022
+ cmd
5023
+ );
5024
+ } catch (error) {
5025
+ handleError(error);
5026
+ }
5027
+ });
5028
+ analyze.command("upload").description("Replace the analysis raw-data table with a new CSV (file path or --url)").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) => {
5029
+ try {
5030
+ await uploadData(id, file, options);
5031
+ } catch (error) {
5032
+ handleError(error);
5033
+ }
5034
+ });
5035
+ analyze.command("columns").description("List columns of the analysis raw-data table").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
5036
+ try {
5037
+ await listColumns(id, cmd);
4955
5038
  } catch (error) {
4956
5039
  handleError(error);
4957
5040
  }
@@ -4985,7 +5068,7 @@ function registerAnalyzeCommand(program) {
4985
5068
  handleError(error);
4986
5069
  }
4987
5070
  });
4988
- presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <keys>", "Comma-separated target keys").requiredOption("--hours <h>", "Compute hours").requiredOption("--budget <credits>", "Credit budget").option("--questions <list>", "Comma-separated questions").option("--segment <key>", "Segmentation key").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
5071
+ 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) => {
4989
5072
  try {
4990
5073
  await savePreset(options, cmd);
4991
5074
  } catch (error) {
@@ -5501,7 +5584,7 @@ import * as fs8 from "fs";
5501
5584
  import * as os3 from "os";
5502
5585
  import * as path6 from "path";
5503
5586
  import { spawn as spawn3 } from "child_process";
5504
- import { randomUUID as randomUUID4 } from "crypto";
5587
+ import { randomUUID as randomUUID3 } from "crypto";
5505
5588
  function extensionFor2(language) {
5506
5589
  const l = language.toLowerCase();
5507
5590
  if (l === "java") return "java";
@@ -5512,7 +5595,7 @@ function extensionFor2(language) {
5512
5595
  return "txt";
5513
5596
  }
5514
5597
  async function openInEditor(initial, ext) {
5515
- const tmpFile = path6.join(os3.tmpdir(), `diafunc-shell-${randomUUID4()}.${ext}`);
5598
+ const tmpFile = path6.join(os3.tmpdir(), `diafunc-shell-${randomUUID3()}.${ext}`);
5516
5599
  fs8.writeFileSync(tmpFile, initial);
5517
5600
  const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
5518
5601
  await new Promise((resolve, reject) => {
@@ -5544,7 +5627,7 @@ async function evaluate(api, fnRef, language, sourceCode) {
5544
5627
  sourceCode
5545
5628
  });
5546
5629
  await api.storage.saveEntities([entity]);
5547
- const evaluationId = randomUUID4();
5630
+ const evaluationId = randomUUID3();
5548
5631
  const nowParts = utcNowParts();
5549
5632
  const result = await api.evaluation.call({
5550
5633
  evaluationId,
@@ -5597,9 +5680,12 @@ function registerShellCommand(program) {
5597
5680
  });
5598
5681
  const api = createApiClient();
5599
5682
  const { input: promptInput } = await import("@inquirer/prompts");
5683
+ const { getUpdateNotice } = await import("./update-check-4DNIH3LQ.js");
5600
5684
  console.log(chalk28.bold("Diafunc shell") + chalk28.dim(` \xB7 function ${fnRef.entityId} \xB7 ${options.language}`));
5601
5685
  console.log(chalk28.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
5602
5686
  console.log(chalk28.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
5687
+ const notice = await getUpdateNotice();
5688
+ if (notice) console.log(chalk28.dim(notice));
5603
5689
  console.log();
5604
5690
  let language = options.language;
5605
5691
  for (; ; ) {
@@ -5679,6 +5765,130 @@ function registerShellCommand(program) {
5679
5765
  });
5680
5766
  }
5681
5767
 
5768
+ // src/commands/update/index.ts
5769
+ import chalk29 from "chalk";
5770
+ import * as path7 from "path";
5771
+ import { spawn as spawn4 } from "child_process";
5772
+
5773
+ // src/util/install-method.ts
5774
+ import * as fs9 from "fs";
5775
+ function detectInstall() {
5776
+ const exec = process.execPath;
5777
+ const exe = exec.replace(/\\/g, "/").toLowerCase();
5778
+ const isNode = exe.endsWith("/node") || exe.endsWith("/node.exe");
5779
+ return {
5780
+ method: isNode ? "npm" : "binary",
5781
+ binaryPath: isNode ? exec : fs9.realpathSync(exec)
5782
+ };
5783
+ }
5784
+
5785
+ // src/commands/update/index.ts
5786
+ var MANIFEST_URL = "https://diafunc.com/cli/latest.json";
5787
+ var INSTALLER_URL = "https://diafunc.com/cli/install.sh";
5788
+ async function fetchLatestVersion() {
5789
+ const res = await fetch(MANIFEST_URL);
5790
+ if (!res.ok) throw new Error(`Failed to fetch ${MANIFEST_URL}: HTTP ${res.status}`);
5791
+ const manifest = await res.json();
5792
+ if (!manifest.version) throw new Error("Manifest missing version field.");
5793
+ return manifest.version;
5794
+ }
5795
+ function runInstaller(installDir) {
5796
+ return new Promise((resolve, reject) => {
5797
+ const child = spawn4("sh", ["-c", `curl -fsSL ${INSTALLER_URL} | sh`], {
5798
+ stdio: "inherit",
5799
+ env: { ...process.env, DIAFUNC_CLI_INSTALL_DIR: installDir }
5800
+ });
5801
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`Installer exited with code ${code}`)));
5802
+ child.on("error", reject);
5803
+ });
5804
+ }
5805
+ function registerUpdateCommand(program) {
5806
+ program.command("update").description("Update the CLI to the latest released version").action(async () => {
5807
+ try {
5808
+ const install = detectInstall();
5809
+ const latest = await fetchLatestVersion();
5810
+ if (latest === package_default.version) {
5811
+ console.log(chalk29.dim(`diafunc is already at the latest version (${package_default.version}).`));
5812
+ return;
5813
+ }
5814
+ console.log(chalk29.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
5815
+ if (install.method === "npm") {
5816
+ console.log();
5817
+ console.log("Installed via npm. Upgrade with:");
5818
+ console.log(chalk29.bold(` npm install -g @diafunc/cli@${latest}`));
5819
+ return;
5820
+ }
5821
+ if (process.platform === "win32") {
5822
+ console.log();
5823
+ console.log("In-place update is not supported on Windows. Re-download from:");
5824
+ console.log(chalk29.bold(" https://diafunc.com/cli/diafunc-windows-x64.zip"));
5825
+ return;
5826
+ }
5827
+ const installDir = path7.dirname(install.binaryPath);
5828
+ console.log(`Installing diafunc ${latest} to ${installDir}...`);
5829
+ console.log();
5830
+ await runInstaller(installDir);
5831
+ } catch (error) {
5832
+ handleError(error);
5833
+ }
5834
+ });
5835
+ }
5836
+
5837
+ // src/commands/uninstall/index.ts
5838
+ import chalk30 from "chalk";
5839
+ import * as fs10 from "fs";
5840
+ import * as os4 from "os";
5841
+ import * as path8 from "path";
5842
+ function registerUninstallCommand(program) {
5843
+ program.command("uninstall").description("Remove the CLI binary and (optionally) its config from this machine").option("-y, --yes", "Skip confirmation prompts").option("--purge", "Also remove ~/.diafunc/ (config + credentials) without prompting").action(async (options) => {
5844
+ try {
5845
+ const install = detectInstall();
5846
+ const configDir = path8.join(os4.homedir(), ".diafunc");
5847
+ if (install.method === "npm") {
5848
+ console.log("Installed via npm. Remove with:");
5849
+ console.log(chalk30.bold(" npm uninstall -g @diafunc/cli"));
5850
+ if (fs10.existsSync(configDir)) {
5851
+ console.log();
5852
+ console.log(`Config + credentials live at ${configDir} \u2014 remove manually with:`);
5853
+ console.log(chalk30.bold(` rm -rf ${configDir}`));
5854
+ }
5855
+ return;
5856
+ }
5857
+ if (process.platform === "win32") {
5858
+ console.log("Self-uninstall is not supported on Windows (the running .exe is locked).");
5859
+ console.log(`Delete the binary manually: ${install.binaryPath}`);
5860
+ return;
5861
+ }
5862
+ const { confirm } = await import("@inquirer/prompts");
5863
+ const removeBinary = options.yes ? true : await confirm({
5864
+ message: `Remove binary at ${install.binaryPath}?`,
5865
+ default: false
5866
+ });
5867
+ if (!removeBinary) {
5868
+ console.log(chalk30.dim("Aborted."));
5869
+ return;
5870
+ }
5871
+ let removeConfig = options.purge ?? false;
5872
+ if (!options.purge && !options.yes && fs10.existsSync(configDir)) {
5873
+ removeConfig = await confirm({
5874
+ message: `Also remove ${configDir} (config + credentials)?`,
5875
+ default: false
5876
+ });
5877
+ }
5878
+ if (removeConfig && fs10.existsSync(configDir)) {
5879
+ fs10.rmSync(configDir, { recursive: true, force: true });
5880
+ console.log(chalk30.dim(`Removed ${configDir}`));
5881
+ }
5882
+ fs10.rmSync(install.binaryPath, { force: true });
5883
+ console.log(chalk30.dim(`Removed ${install.binaryPath}`));
5884
+ console.log();
5885
+ console.log("diafunc uninstalled.");
5886
+ } catch (error) {
5887
+ handleError(error);
5888
+ }
5889
+ });
5890
+ }
5891
+
5682
5892
  // src/index.ts
5683
5893
  function createProgram() {
5684
5894
  const program = new Command();
@@ -5712,11 +5922,12 @@ function createProgram() {
5712
5922
  registerSubscriptionCommand(program);
5713
5923
  registerInvoiceCommand(program);
5714
5924
  registerShellCommand(program);
5925
+ registerUpdateCommand(program);
5926
+ registerUninstallCommand(program);
5715
5927
  return program;
5716
5928
  }
5717
5929
 
5718
5930
  export {
5719
- package_default,
5720
5931
  createProgram
5721
5932
  };
5722
- //# sourceMappingURL=chunk-PDVC2LAL.js.map
5933
+ //# sourceMappingURL=chunk-7TYSZ6GC.js.map