@diafunc/cli 0.1.2 → 0.3.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,6 +1,67 @@
1
1
  // src/index.ts
2
2
  import { Command } from "commander";
3
3
 
4
+ // package.json
5
+ var package_default = {
6
+ name: "@diafunc/cli",
7
+ version: "0.3.0",
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
+
4
65
  // src/commands/auth/login.ts
5
66
  import chalk2 from "chalk";
6
67
 
@@ -88,8 +149,8 @@ var NetworkError = class extends Error {
88
149
  };
89
150
 
90
151
  // src/client/http.ts
91
- function buildUrl(endpoint, service, path5, query) {
92
- const base = `${endpoint}/api/v1/${service}${path5}`;
152
+ function buildUrl(endpoint, service, path7, query) {
153
+ const base = `${endpoint}/api/v1/${service}${path7}`;
93
154
  const params = new URLSearchParams();
94
155
  if (query) {
95
156
  for (const [key, value] of Object.entries(query)) {
@@ -106,14 +167,27 @@ function getAuthHeader(auth) {
106
167
  if (auth.type === "api-token") {
107
168
  return `Bearer ${auth.token}`;
108
169
  }
109
- if (auth.type === "session") {
170
+ if (auth.type === "session" || auth.type === "device-code") {
110
171
  return `Bearer ${auth.accessToken}`;
111
172
  }
112
173
  return void 0;
113
174
  }
114
175
  function isTokenExpired(auth) {
115
- if (!auth || auth.type !== "session") return false;
116
- return Date.now() >= auth.accessTokenExpiry - 3e4;
176
+ if (!auth) return false;
177
+ if (auth.type === "session" || auth.type === "device-code") {
178
+ return Date.now() >= auth.accessTokenExpiry - 3e4;
179
+ }
180
+ return false;
181
+ }
182
+ function deriveAuthUrl(endpoint) {
183
+ const trimmed = endpoint.replace(/\/+$/, "");
184
+ if (trimmed.includes("://auth.")) {
185
+ return trimmed;
186
+ }
187
+ const url = new URL(trimmed);
188
+ url.hostname = `auth.${url.hostname}`;
189
+ url.pathname = "";
190
+ return url.toString().replace(/\/+$/, "");
117
191
  }
118
192
  async function refreshSession(endpoint, refreshToken) {
119
193
  const url = `${endpoint}/api/v1/admin/sessions/`;
@@ -131,18 +205,51 @@ async function refreshSession(endpoint, refreshToken) {
131
205
  accessTokenExpiry: session.accessToken.expiry
132
206
  };
133
207
  }
208
+ async function refreshOAuthTokens(endpoint, clientId, refreshToken) {
209
+ const authUrl = deriveAuthUrl(endpoint);
210
+ const response = await fetch(`${authUrl}/token`, {
211
+ method: "POST",
212
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
213
+ body: new URLSearchParams({
214
+ grant_type: "refresh_token",
215
+ refresh_token: refreshToken,
216
+ client_id: clientId
217
+ }).toString()
218
+ });
219
+ if (!response.ok) {
220
+ throw new ApiError(response.status, "OAuth token refresh failed. Please run `diafunc auth login` again.");
221
+ }
222
+ const body = await response.json();
223
+ return {
224
+ accessToken: body.access_token,
225
+ refreshToken: body.refresh_token,
226
+ accessTokenExpiry: Date.now() + body.expires_in * 1e3
227
+ };
228
+ }
134
229
  async function ensureValidAuth(config, profileOverride) {
135
230
  const profileName = profileOverride ?? config.currentProfile;
136
231
  const profile = config.profiles[profileName];
137
232
  if (!profile?.auth) return void 0;
138
- if (isTokenExpired(profile.auth)) {
139
- const auth = profile.auth;
140
- const endpoint = resolveEndpoint(config, profileOverride);
141
- const refreshed = await refreshSession(endpoint, auth.refreshToken);
233
+ if (!isTokenExpired(profile.auth)) {
234
+ return profile.auth;
235
+ }
236
+ const endpoint = resolveEndpoint(config, profileOverride);
237
+ if (profile.auth.type === "session") {
238
+ const refreshed = await refreshSession(endpoint, profile.auth.refreshToken);
142
239
  profile.auth = {
143
240
  type: "session",
144
241
  accessToken: refreshed.accessToken,
145
- refreshToken: auth.refreshToken,
242
+ refreshToken: profile.auth.refreshToken,
243
+ accessTokenExpiry: refreshed.accessTokenExpiry
244
+ };
245
+ saveConfig(config);
246
+ } else if (profile.auth.type === "device-code") {
247
+ const refreshed = await refreshOAuthTokens(endpoint, profile.auth.clientId, profile.auth.refreshToken);
248
+ profile.auth = {
249
+ type: "device-code",
250
+ clientId: profile.auth.clientId,
251
+ accessToken: refreshed.accessToken,
252
+ refreshToken: refreshed.refreshToken,
146
253
  accessTokenExpiry: refreshed.accessTokenExpiry
147
254
  };
148
255
  saveConfig(config);
@@ -434,6 +541,14 @@ function createAdminService(client) {
434
541
  body: group
435
542
  });
436
543
  },
544
+ async updateGroup(group) {
545
+ return client.request({
546
+ method: "PUT",
547
+ service: SERVICE,
548
+ path: "/groups/",
549
+ body: group
550
+ });
551
+ },
437
552
  async deleteGroup(groupId) {
438
553
  return client.request({
439
554
  method: "DELETE",
@@ -507,43 +622,66 @@ function createAdminService(client) {
507
622
  path: "/subscriptions/current"
508
623
  });
509
624
  },
510
- // Backup
511
- async createShortTermProjectBackup(body) {
625
+ async getNextSubscription() {
512
626
  return client.request({
513
- method: "POST",
627
+ method: "GET",
514
628
  service: SERVICE,
515
- path: "/backups/project/short-term/create",
516
- body
629
+ path: "/subscriptions/next"
517
630
  });
518
631
  },
519
- async createShortTermFullBackup() {
632
+ async getSubscriptionPlans(subscriptionToken) {
520
633
  return client.request({
521
- method: "POST",
634
+ method: "GET",
522
635
  service: SERVICE,
523
- path: "/backups/full/short-term/create"
636
+ path: `/subscription-plans/${encodeURIComponent(subscriptionToken)}`
524
637
  });
525
638
  },
526
- // Analyses
527
- async getLastAnalysis() {
639
+ // Invoices
640
+ async hasInvoices() {
528
641
  return client.request({
529
642
  method: "GET",
530
643
  service: SERVICE,
531
- path: "/analyses/last"
644
+ path: "/invoices/any"
532
645
  });
533
646
  },
534
- async getAnalysis(analysisId) {
647
+ async getInvoices() {
535
648
  return client.request({
536
649
  method: "GET",
537
650
  service: SERVICE,
538
- path: `/analyses/${encodeURIComponent(analysisId)}`
651
+ path: "/invoices/"
652
+ });
653
+ },
654
+ async downloadInvoice(invoiceNumber, fileName) {
655
+ return client.requestRaw({
656
+ method: "GET",
657
+ service: SERVICE,
658
+ path: `/invoices/${encodeURIComponent(invoiceNumber)}/documents/${encodeURIComponent(fileName)}`
539
659
  });
540
660
  },
541
- async saveAnalysis(analysis) {
661
+ // (Backup methods moved to storage service — see src/client/services/storage.ts.
662
+ // Backup endpoints live under @RestApi("storage") on the platform.)
663
+ // Analyses moved to the analysis service (see src/client/services/analysis.ts).
664
+ // Utilization
665
+ async getActualUtilization() {
542
666
  return client.request({
543
- method: "POST",
667
+ method: "GET",
544
668
  service: SERVICE,
545
- path: "/analyses/",
546
- body: analysis
669
+ path: "/utilization/actual"
670
+ });
671
+ },
672
+ async getUtilizationHistory() {
673
+ return client.request({
674
+ method: "GET",
675
+ service: SERVICE,
676
+ path: "/utilization/history"
677
+ });
678
+ },
679
+ // Recent projects
680
+ async getRecentProjects() {
681
+ return client.request({
682
+ method: "GET",
683
+ service: SERVICE,
684
+ path: "/recent-projects/"
547
685
  });
548
686
  }
549
687
  };
@@ -569,8 +707,21 @@ function handleError(error) {
569
707
  }
570
708
 
571
709
  // src/commands/auth/login.ts
710
+ var DEVICE_CLIENT_ID = "diafunc-cli";
711
+ var DEVICE_SCOPE = "openid profile email user";
712
+ var ACCESS_TOKEN_LIFETIME_SECONDS = 15 * 60;
713
+ function deriveAuthUrl2(endpoint) {
714
+ const trimmed = endpoint.replace(/\/+$/, "");
715
+ if (trimmed.includes("://auth.")) {
716
+ return trimmed;
717
+ }
718
+ const url = new URL(trimmed);
719
+ url.hostname = `auth.${url.hostname}`;
720
+ url.pathname = "";
721
+ return url.toString().replace(/\/+$/, "");
722
+ }
572
723
  function registerLoginCommand(parent) {
573
- parent.command("login").description("Authenticate with the Diafunc platform").option("--token <token>", "API token (dfat_...) for token-based auth").option("--endpoint <url>", "Override the endpoint URL for this login").action(async (options) => {
724
+ parent.command("login").description("Authenticate with the Diafunc platform").option("--token <token>", "API token (dfat_...) for non-interactive token-based auth").option("--endpoint <url>", "Override the endpoint URL for this login").option("--password", "Use legacy username/password login instead of OIDC device code").action(async (options) => {
574
725
  try {
575
726
  const config = loadConfig();
576
727
  const profile = config.profiles[config.currentProfile];
@@ -582,10 +733,7 @@ function registerLoginCommand(parent) {
582
733
  profile.endpoint = options.endpoint;
583
734
  }
584
735
  if (options.token) {
585
- profile.auth = {
586
- type: "api-token",
587
- token: options.token
588
- };
736
+ profile.auth = { type: "api-token", token: options.token };
589
737
  saveConfig(config);
590
738
  const client = createHttpClient();
591
739
  const admin = createAdminService(client);
@@ -595,55 +743,141 @@ function registerLoginCommand(parent) {
595
743
  console.log(` Email: ${user.email}`);
596
744
  console.log(` Profile: ${config.currentProfile}`);
597
745
  console.log(` Endpoint: ${profile.endpoint}`);
598
- } else {
599
- const { input, password } = await import("@inquirer/prompts");
600
- const username = await input({
601
- message: "Username or email:"
602
- });
603
- const pwd = await password({
604
- message: "Password:"
605
- });
606
- const endpoint = profile.endpoint.replace(/\/+$/, "");
607
- const response = await fetch(`${endpoint}/api/v1/admin/sessions/`, {
608
- method: "POST",
609
- headers: { "Content-Type": "application/json" },
610
- body: JSON.stringify({
611
- userNameOrEmail: username,
612
- password: pwd
613
- })
614
- });
615
- if (!response.ok) {
616
- const text = await response.text();
617
- console.error(chalk2.red("Login failed:"), text || response.statusText);
618
- process.exit(1);
619
- }
620
- const session = await response.json();
621
- profile.auth = {
622
- type: "session",
623
- accessToken: session.accessToken.raw,
624
- refreshToken: session.refreshToken.raw,
625
- accessTokenExpiry: session.accessToken.expiry
626
- };
627
- saveConfig(config);
628
- const client = createHttpClient();
629
- const admin = createAdminService(client);
630
- const user = await admin.getMyUser();
631
- console.log(chalk2.green("Logged in successfully."));
632
- console.log(` User: ${chalk2.bold(user.name)}`);
633
- console.log(` Email: ${user.email}`);
634
- console.log(` Profile: ${config.currentProfile}`);
635
- console.log(` Endpoint: ${profile.endpoint}`);
746
+ return;
747
+ }
748
+ if (options.password) {
749
+ await legacyPasswordLogin(config, profile);
750
+ return;
636
751
  }
752
+ await deviceCodeLogin(config, profile);
637
753
  } catch (error) {
638
754
  handleError(error);
639
755
  }
640
756
  });
641
757
  }
758
+ async function deviceCodeLogin(config, profile) {
759
+ const authUrl = deriveAuthUrl2(profile.endpoint);
760
+ const deviceResponse = await fetch(`${authUrl}/device_authorization`, {
761
+ method: "POST",
762
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
763
+ body: new URLSearchParams({ client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }).toString()
764
+ });
765
+ if (!deviceResponse.ok) {
766
+ const text = await deviceResponse.text();
767
+ console.error(chalk2.red("Failed to start device-code flow:"), text || deviceResponse.statusText);
768
+ process.exit(1);
769
+ }
770
+ const device = await deviceResponse.json();
771
+ console.log("");
772
+ console.log(`Open this URL in a browser: ${chalk2.cyan(device.verification_uri)}`);
773
+ console.log(`Enter the code: ${chalk2.bold.yellow(device.user_code)}`);
774
+ console.log("");
775
+ console.log(chalk2.dim("Or open the full URL to pre-fill:"));
776
+ console.log(chalk2.dim(` ${device.verification_uri_complete}`));
777
+ console.log("");
778
+ console.log(chalk2.dim(`Waiting for approval (expires in ${Math.floor(device.expires_in / 60)} min)...`));
779
+ const deadline = Date.now() + device.expires_in * 1e3;
780
+ let interval = Math.max(1, device.interval || 5);
781
+ while (Date.now() < deadline) {
782
+ await sleep(interval * 1e3);
783
+ const pollResponse = await fetch(`${authUrl}/token`, {
784
+ method: "POST",
785
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
786
+ body: new URLSearchParams({
787
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
788
+ device_code: device.device_code,
789
+ client_id: DEVICE_CLIENT_ID
790
+ }).toString()
791
+ });
792
+ if (pollResponse.ok) {
793
+ const tokens = await pollResponse.json();
794
+ profile.auth = {
795
+ type: "device-code",
796
+ clientId: DEVICE_CLIENT_ID,
797
+ accessToken: tokens.access_token,
798
+ refreshToken: tokens.refresh_token,
799
+ accessTokenExpiry: Date.now() + (tokens.expires_in || ACCESS_TOKEN_LIFETIME_SECONDS) * 1e3
800
+ };
801
+ saveConfig(config);
802
+ const client = createHttpClient();
803
+ const admin = createAdminService(client);
804
+ const user = await admin.getMyUser();
805
+ console.log(chalk2.green("\nLogged in successfully."));
806
+ console.log(` User: ${chalk2.bold(user.name)}`);
807
+ console.log(` Email: ${user.email}`);
808
+ console.log(` Profile: ${config.currentProfile}`);
809
+ console.log(` Endpoint: ${profile.endpoint}`);
810
+ return;
811
+ }
812
+ const errorBody = await pollResponse.json().catch(() => ({ error: "unknown" }));
813
+ if (errorBody.error === "authorization_pending") {
814
+ continue;
815
+ }
816
+ if (errorBody.error === "slow_down") {
817
+ interval += 5;
818
+ continue;
819
+ }
820
+ if (errorBody.error === "expired_token") {
821
+ console.error(chalk2.red("\nCode expired before approval. Run `diafunc auth login` again."));
822
+ process.exit(1);
823
+ }
824
+ console.error(chalk2.red(`
825
+ Device-code flow failed: ${errorBody.error}${errorBody.error_description ? " \u2014 " + errorBody.error_description : ""}`));
826
+ process.exit(1);
827
+ }
828
+ console.error(chalk2.red("\nTimed out waiting for approval."));
829
+ process.exit(1);
830
+ }
831
+ async function legacyPasswordLogin(config, profile) {
832
+ const { input, password } = await import("@inquirer/prompts");
833
+ const username = await input({ message: "Username or email:" });
834
+ const pwd = await password({ message: "Password:" });
835
+ const endpoint = profile.endpoint.replace(/\/+$/, "");
836
+ const response = await fetch(`${endpoint}/api/v1/admin/sessions/`, {
837
+ method: "POST",
838
+ headers: { "Content-Type": "application/json" },
839
+ body: JSON.stringify({ userNameOrEmail: username, password: pwd })
840
+ });
841
+ if (!response.ok) {
842
+ const text = await response.text();
843
+ console.error(chalk2.red("Login failed:"), text || response.statusText);
844
+ process.exit(1);
845
+ }
846
+ const session = await response.json();
847
+ profile.auth = {
848
+ type: "session",
849
+ accessToken: session.accessToken.raw,
850
+ refreshToken: session.refreshToken.raw,
851
+ accessTokenExpiry: session.accessToken.expiry
852
+ };
853
+ saveConfig(config);
854
+ const client = createHttpClient();
855
+ const admin = createAdminService(client);
856
+ const user = await admin.getMyUser();
857
+ console.log(chalk2.green("Logged in successfully (legacy password path)."));
858
+ console.log(` User: ${chalk2.bold(user.name)}`);
859
+ console.log(` Email: ${user.email}`);
860
+ console.log(` Profile: ${config.currentProfile}`);
861
+ console.log(` Endpoint: ${profile.endpoint}`);
862
+ }
863
+ function sleep(ms) {
864
+ return new Promise((resolve) => setTimeout(resolve, ms));
865
+ }
642
866
 
643
867
  // src/commands/auth/logout.ts
644
868
  import chalk3 from "chalk";
869
+ function deriveAuthUrl3(endpoint) {
870
+ const trimmed = endpoint.replace(/\/+$/, "");
871
+ if (trimmed.includes("://auth.")) {
872
+ return trimmed;
873
+ }
874
+ const url = new URL(trimmed);
875
+ url.hostname = `auth.${url.hostname}`;
876
+ url.pathname = "";
877
+ return url.toString().replace(/\/+$/, "");
878
+ }
645
879
  function registerLogoutCommand(parent) {
646
- parent.command("logout").description("Remove stored credentials for the active profile").action(() => {
880
+ parent.command("logout").description("Remove stored credentials for the active profile and revoke refresh token if possible").action(async () => {
647
881
  const config = loadConfig();
648
882
  const profile = config.profiles[config.currentProfile];
649
883
  if (!profile) {
@@ -654,6 +888,26 @@ function registerLogoutCommand(parent) {
654
888
  console.log(chalk3.dim("No credentials stored for this profile."));
655
889
  return;
656
890
  }
891
+ if (profile.auth.type === "device-code") {
892
+ try {
893
+ const authUrl = deriveAuthUrl3(profile.endpoint);
894
+ await fetch(`${authUrl}/revoke`, {
895
+ method: "POST",
896
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
897
+ body: new URLSearchParams({
898
+ token: profile.auth.refreshToken,
899
+ token_type_hint: "refresh_token"
900
+ }).toString()
901
+ });
902
+ } catch {
903
+ }
904
+ } else if (profile.auth.type === "session") {
905
+ try {
906
+ const endpoint = profile.endpoint.replace(/\/+$/, "");
907
+ await fetch(`${endpoint}/api/v1/admin/sessions/`, { method: "DELETE" });
908
+ } catch {
909
+ }
910
+ }
657
911
  delete profile.auth;
658
912
  saveConfig(config);
659
913
  console.log(chalk3.green(`Logged out from profile "${config.currentProfile}".`));
@@ -785,8 +1039,157 @@ function registerStatusCommand(parent) {
785
1039
  // src/commands/auth/token.ts
786
1040
  import chalk6 from "chalk";
787
1041
 
1042
+ // src/client/services/analysis.ts
1043
+ var SERVICE2 = "analyses";
1044
+ var RUNS_SERVICE = "runs";
1045
+ var PRESETS_SERVICE = "analysis-presets";
1046
+ var TRIGGERS_SERVICE = "triggers";
1047
+ function createAnalysisService(client) {
1048
+ return {
1049
+ async getLast() {
1050
+ return client.request({
1051
+ method: "GET",
1052
+ service: SERVICE2,
1053
+ path: "/last"
1054
+ });
1055
+ },
1056
+ async getRecent(count = 20) {
1057
+ return client.request({
1058
+ method: "GET",
1059
+ service: SERVICE2,
1060
+ path: "/recent",
1061
+ query: { count }
1062
+ });
1063
+ },
1064
+ async get(analysisId) {
1065
+ return client.request({
1066
+ method: "GET",
1067
+ service: SERVICE2,
1068
+ path: `/${encodeURIComponent(analysisId)}`
1069
+ });
1070
+ },
1071
+ async save(analysis) {
1072
+ return client.request({
1073
+ method: "POST",
1074
+ service: SERVICE2,
1075
+ path: "/",
1076
+ body: analysis
1077
+ });
1078
+ },
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) {
1085
+ return client.request({
1086
+ method: "POST",
1087
+ service: SERVICE2,
1088
+ path: "/runs",
1089
+ body: analysis
1090
+ });
1091
+ },
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) {
1099
+ return client.request({
1100
+ method: "POST",
1101
+ service: SERVICE2,
1102
+ path: `/${encodeURIComponent(analysisId)}/runs`
1103
+ });
1104
+ },
1105
+ async getRunsForAnalysis(analysisId, count = 20) {
1106
+ return client.request({
1107
+ method: "GET",
1108
+ service: SERVICE2,
1109
+ path: `/${encodeURIComponent(analysisId)}/runs`,
1110
+ query: { count }
1111
+ });
1112
+ },
1113
+ async getRun(runId) {
1114
+ return client.request({
1115
+ method: "GET",
1116
+ service: RUNS_SERVICE,
1117
+ path: `/${encodeURIComponent(runId)}`
1118
+ });
1119
+ },
1120
+ async cancelRun(runId) {
1121
+ return client.request({
1122
+ method: "POST",
1123
+ service: RUNS_SERVICE,
1124
+ path: `/${encodeURIComponent(runId)}/cancel`
1125
+ });
1126
+ },
1127
+ // ---------- presets ----------
1128
+ async getPresets() {
1129
+ return client.request({
1130
+ method: "GET",
1131
+ service: PRESETS_SERVICE,
1132
+ path: "/"
1133
+ });
1134
+ },
1135
+ async getPreset(presetId) {
1136
+ return client.request({
1137
+ method: "GET",
1138
+ service: PRESETS_SERVICE,
1139
+ path: `/${encodeURIComponent(presetId)}`
1140
+ });
1141
+ },
1142
+ async savePreset(preset) {
1143
+ return client.request({
1144
+ method: "POST",
1145
+ service: PRESETS_SERVICE,
1146
+ path: "/",
1147
+ body: preset
1148
+ });
1149
+ },
1150
+ async deletePreset(presetId) {
1151
+ await client.request({
1152
+ method: "DELETE",
1153
+ service: PRESETS_SERVICE,
1154
+ path: `/${encodeURIComponent(presetId)}`
1155
+ });
1156
+ },
1157
+ // ---------- triggers ----------
1158
+ async createTrigger(analysisId, body) {
1159
+ return client.request({
1160
+ method: "POST",
1161
+ service: SERVICE2,
1162
+ path: `/${encodeURIComponent(analysisId)}/triggers`,
1163
+ body
1164
+ });
1165
+ },
1166
+ async listTriggers(analysisId) {
1167
+ return client.request({
1168
+ method: "GET",
1169
+ service: SERVICE2,
1170
+ path: `/${encodeURIComponent(analysisId)}/triggers`
1171
+ });
1172
+ },
1173
+ async updateTrigger(triggerId, body) {
1174
+ return client.request({
1175
+ method: "PATCH",
1176
+ service: TRIGGERS_SERVICE,
1177
+ path: `/${encodeURIComponent(triggerId)}`,
1178
+ body
1179
+ });
1180
+ },
1181
+ async deleteTrigger(triggerId) {
1182
+ await client.request({
1183
+ method: "DELETE",
1184
+ service: TRIGGERS_SERVICE,
1185
+ path: `/${encodeURIComponent(triggerId)}`
1186
+ });
1187
+ }
1188
+ };
1189
+ }
1190
+
788
1191
  // src/client/services/storage.ts
789
- var SERVICE2 = "storage";
1192
+ var SERVICE3 = "storage";
790
1193
  function enc(s) {
791
1194
  return encodeURIComponent(s);
792
1195
  }
@@ -799,14 +1202,14 @@ function createStorageService(client) {
799
1202
  async entityExists(ref) {
800
1203
  return client.request({
801
1204
  method: "GET",
802
- service: SERVICE2,
1205
+ service: SERVICE3,
803
1206
  path: `/entities/exists${entityPath(ref)}`
804
1207
  });
805
1208
  },
806
1209
  async getEntity(ref, content = false) {
807
1210
  return client.request({
808
1211
  method: "GET",
809
- service: SERVICE2,
1212
+ service: SERVICE3,
810
1213
  path: `/entities/actual${entityPath(ref)}`,
811
1214
  query: content ? { content: true } : void 0
812
1215
  });
@@ -814,14 +1217,14 @@ function createStorageService(client) {
814
1217
  async getEntityContent(ref) {
815
1218
  return client.requestRaw({
816
1219
  method: "GET",
817
- service: SERVICE2,
1220
+ service: SERVICE3,
818
1221
  path: `/entities/contents/actual${entityPath(ref)}`
819
1222
  });
820
1223
  },
821
1224
  async saveEntities(entities) {
822
1225
  return client.request({
823
1226
  method: "PUT",
824
- service: SERVICE2,
1227
+ service: SERVICE3,
825
1228
  path: "/entities/actual",
826
1229
  body: entities
827
1230
  });
@@ -829,14 +1232,14 @@ function createStorageService(client) {
829
1232
  async deleteEntity(ref) {
830
1233
  return client.request({
831
1234
  method: "DELETE",
832
- service: SERVICE2,
1235
+ service: SERVICE3,
833
1236
  path: `/entities/actual${entityPath(ref)}`
834
1237
  });
835
1238
  },
836
1239
  async saveEntityContentBase64(ref, base64Content) {
837
1240
  return client.request({
838
1241
  method: "PUT",
839
- service: SERVICE2,
1242
+ service: SERVICE3,
840
1243
  path: `/entities/contents/actual${entityPath(ref)}`,
841
1244
  rawBody: base64Content,
842
1245
  contentType: "text/plain"
@@ -845,7 +1248,7 @@ function createStorageService(client) {
845
1248
  async uploadEntityContent(ref, formData) {
846
1249
  return client.request({
847
1250
  method: "PUT",
848
- service: SERVICE2,
1251
+ service: SERVICE3,
849
1252
  path: `/entities/contents/actual${entityPath(ref)}`,
850
1253
  rawBody: formData
851
1254
  });
@@ -853,35 +1256,35 @@ function createStorageService(client) {
853
1256
  async deleteEntityContent(ref) {
854
1257
  return client.request({
855
1258
  method: "DELETE",
856
- service: SERVICE2,
1259
+ service: SERVICE3,
857
1260
  path: `/entities/contents/actual${entityPath(ref)}`
858
1261
  });
859
1262
  },
860
1263
  async getEntityHistory(ref, version) {
861
1264
  return client.request({
862
1265
  method: "GET",
863
- service: SERVICE2,
1266
+ service: SERVICE3,
864
1267
  path: `/entities/history${entityPath(ref)}/${version}`
865
1268
  });
866
1269
  },
867
1270
  async getEntityHistoryRange(ref, fromVersion, toVersion) {
868
1271
  return client.request({
869
1272
  method: "GET",
870
- service: SERVICE2,
1273
+ service: SERVICE3,
871
1274
  path: `/entities/history${entityPath(ref)}/${fromVersion}/${toVersion}`
872
1275
  });
873
1276
  },
874
1277
  async renameEntity(ref, newEntityId) {
875
1278
  return client.request({
876
1279
  method: "PUT",
877
- service: SERVICE2,
1280
+ service: SERVICE3,
878
1281
  path: `/entities/ids${entityPath(ref)}/${enc(newEntityId)}`
879
1282
  });
880
1283
  },
881
1284
  async revertEntity(ref, version) {
882
1285
  return client.request({
883
1286
  method: "PUT",
884
- service: SERVICE2,
1287
+ service: SERVICE3,
885
1288
  path: `/entities/revert${entityPath(ref)}/${version}`
886
1289
  });
887
1290
  },
@@ -889,7 +1292,7 @@ function createStorageService(client) {
889
1292
  async searchEntityIds(projectId, projectBranch, body) {
890
1293
  return client.request({
891
1294
  method: "POST",
892
- service: SERVICE2,
1295
+ service: SERVICE3,
893
1296
  path: "/entity-ids/search",
894
1297
  body
895
1298
  });
@@ -898,14 +1301,14 @@ function createStorageService(client) {
898
1301
  async getLinkedEntities(direction, ref) {
899
1302
  return client.request({
900
1303
  method: "GET",
901
- service: SERVICE2,
1304
+ service: SERVICE3,
902
1305
  path: `/linked-entities/${enc(direction)}${entityPath(ref)}`
903
1306
  });
904
1307
  },
905
1308
  async saveLinkedEntities(ref, linkId, entities) {
906
1309
  return client.request({
907
1310
  method: "PUT",
908
- service: SERVICE2,
1311
+ service: SERVICE3,
909
1312
  path: `/linked-entities/${enc(ref.projectId)}/${enc(ref.projectBranch)}/${enc(ref.entityId)}/${enc(ref.entityBranch)}/${enc(linkId)}`,
910
1313
  body: entities
911
1314
  });
@@ -914,55 +1317,55 @@ function createStorageService(client) {
914
1317
  async getLinks(direction, ref) {
915
1318
  return client.request({
916
1319
  method: "GET",
917
- service: SERVICE2,
1320
+ service: SERVICE3,
918
1321
  path: `/links/actual/${enc(direction)}${entityPath(ref)}`
919
1322
  });
920
1323
  },
921
1324
  async getLinkIds(direction, ref) {
922
1325
  return client.request({
923
1326
  method: "GET",
924
- service: SERVICE2,
1327
+ service: SERVICE3,
925
1328
  path: `/links/ids/actual/${enc(direction)}${entityPath(ref)}`
926
1329
  });
927
1330
  },
928
1331
  async createLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch, link) {
929
1332
  return client.request({
930
1333
  method: "POST",
931
- service: SERVICE2,
1334
+ service: SERVICE3,
932
1335
  path: `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}/${enc(targetEntityId)}/${enc(targetEntityBranch)}`,
933
1336
  body: link
934
1337
  });
935
1338
  },
936
1339
  async deleteLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch) {
937
- let path5 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
1340
+ let path7 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
938
1341
  if (targetEntityId && targetEntityBranch) {
939
- path5 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
1342
+ path7 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
940
1343
  }
941
1344
  return client.request({
942
1345
  method: "DELETE",
943
- service: SERVICE2,
944
- path: path5
1346
+ service: SERVICE3,
1347
+ path: path7
945
1348
  });
946
1349
  },
947
1350
  // --- Events ---
948
1351
  async getEvents(ref) {
949
1352
  return client.request({
950
1353
  method: "GET",
951
- service: SERVICE2,
1354
+ service: SERVICE3,
952
1355
  path: `/events/actual${entityPath(ref)}`
953
1356
  });
954
1357
  },
955
1358
  async getEvent(ref, eventId, occurrenceId) {
956
1359
  return client.request({
957
1360
  method: "GET",
958
- service: SERVICE2,
1361
+ service: SERVICE3,
959
1362
  path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`
960
1363
  });
961
1364
  },
962
1365
  async createEvents(events) {
963
1366
  return client.request({
964
1367
  method: "POST",
965
- service: SERVICE2,
1368
+ service: SERVICE3,
966
1369
  path: "/events/",
967
1370
  body: events
968
1371
  });
@@ -970,7 +1373,7 @@ function createStorageService(client) {
970
1373
  async consumeEvents(body) {
971
1374
  return client.request({
972
1375
  method: "POST",
973
- service: SERVICE2,
1376
+ service: SERVICE3,
974
1377
  path: "/events/consume",
975
1378
  body
976
1379
  });
@@ -978,7 +1381,7 @@ function createStorageService(client) {
978
1381
  async deleteEvent(ref, eventId, occurrenceId) {
979
1382
  return client.request({
980
1383
  method: "DELETE",
981
- service: SERVICE2,
1384
+ service: SERVICE3,
982
1385
  path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`
983
1386
  });
984
1387
  },
@@ -986,7 +1389,7 @@ function createStorageService(client) {
986
1389
  async getTableSnapshot(ref, request) {
987
1390
  return client.request({
988
1391
  method: "POST",
989
- service: SERVICE2,
1392
+ service: SERVICE3,
990
1393
  path: `/tables${entityPath(ref)}/snapshots`,
991
1394
  body: request ?? {}
992
1395
  });
@@ -994,35 +1397,35 @@ function createStorageService(client) {
994
1397
  async appendRow(ref) {
995
1398
  return client.request({
996
1399
  method: "POST",
997
- service: SERVICE2,
1400
+ service: SERVICE3,
998
1401
  path: `/tables${entityPath(ref)}/rows`
999
1402
  });
1000
1403
  },
1001
1404
  async deleteRow(ref, rowIndex) {
1002
1405
  return client.request({
1003
1406
  method: "DELETE",
1004
- service: SERVICE2,
1407
+ service: SERVICE3,
1005
1408
  path: `/tables${entityPath(ref)}/rows/${rowIndex}`
1006
1409
  });
1007
1410
  },
1008
1411
  async appendColumn(ref) {
1009
1412
  return client.request({
1010
1413
  method: "POST",
1011
- service: SERVICE2,
1414
+ service: SERVICE3,
1012
1415
  path: `/tables${entityPath(ref)}/columns`
1013
1416
  });
1014
1417
  },
1015
1418
  async deleteColumn(ref, columnIndex) {
1016
1419
  return client.request({
1017
1420
  method: "DELETE",
1018
- service: SERVICE2,
1421
+ service: SERVICE3,
1019
1422
  path: `/tables${entityPath(ref)}/columns/${columnIndex}`
1020
1423
  });
1021
1424
  },
1022
1425
  async mergeCells(ref, cells) {
1023
1426
  return client.request({
1024
1427
  method: "PUT",
1025
- service: SERVICE2,
1428
+ service: SERVICE3,
1026
1429
  path: `/tables${entityPath(ref)}/cells`,
1027
1430
  body: cells
1028
1431
  });
@@ -1030,14 +1433,14 @@ function createStorageService(client) {
1030
1433
  async deleteCell(ref, rowIndex, columnIndex) {
1031
1434
  return client.request({
1032
1435
  method: "DELETE",
1033
- service: SERVICE2,
1436
+ service: SERVICE3,
1034
1437
  path: `/tables${entityPath(ref)}/cells/${rowIndex}/${columnIndex}`
1035
1438
  });
1036
1439
  },
1037
1440
  async clearTable(ref) {
1038
1441
  return client.request({
1039
1442
  method: "POST",
1040
- service: SERVICE2,
1443
+ service: SERVICE3,
1041
1444
  path: `/tables${entityPath(ref)}/clear`
1042
1445
  });
1043
1446
  },
@@ -1045,7 +1448,7 @@ function createStorageService(client) {
1045
1448
  async importTable(ref, formData, columnHeaders = true) {
1046
1449
  return client.request({
1047
1450
  method: "PUT",
1048
- service: SERVICE2,
1451
+ service: SERVICE3,
1049
1452
  path: `/table-imports${entityPath(ref)}`,
1050
1453
  query: { columnHeaders },
1051
1454
  rawBody: formData
@@ -1054,21 +1457,21 @@ function createStorageService(client) {
1054
1457
  async getImport(ref, importId) {
1055
1458
  return client.request({
1056
1459
  method: "GET",
1057
- service: SERVICE2,
1460
+ service: SERVICE3,
1058
1461
  path: `/imports${entityPath(ref)}/${enc(importId)}`
1059
1462
  });
1060
1463
  },
1061
1464
  async exportTableCsv(ref) {
1062
1465
  return client.requestRaw({
1063
1466
  method: "POST",
1064
- service: SERVICE2,
1467
+ service: SERVICE3,
1065
1468
  path: `/table-exports${entityPath(ref)}/csv`
1066
1469
  });
1067
1470
  },
1068
1471
  async exportTableExcel(ref) {
1069
1472
  return client.requestRaw({
1070
1473
  method: "POST",
1071
- service: SERVICE2,
1474
+ service: SERVICE3,
1072
1475
  path: `/table-exports${entityPath(ref)}/excel`
1073
1476
  });
1074
1477
  },
@@ -1076,14 +1479,14 @@ function createStorageService(client) {
1076
1479
  async getProjectBranches(projectId) {
1077
1480
  return client.request({
1078
1481
  method: "GET",
1079
- service: SERVICE2,
1482
+ service: SERVICE3,
1080
1483
  path: `/project-branches/${enc(projectId)}`
1081
1484
  });
1082
1485
  },
1083
1486
  async createProjectBranch(request) {
1084
1487
  return client.request({
1085
1488
  method: "POST",
1086
- service: SERVICE2,
1489
+ service: SERVICE3,
1087
1490
  path: "/project-branches/",
1088
1491
  body: request
1089
1492
  });
@@ -1091,21 +1494,21 @@ function createStorageService(client) {
1091
1494
  async deleteProjectBranch(projectId, projectBranch) {
1092
1495
  return client.request({
1093
1496
  method: "DELETE",
1094
- service: SERVICE2,
1497
+ service: SERVICE3,
1095
1498
  path: `/project-branches/${enc(projectId)}/${enc(projectBranch)}`
1096
1499
  });
1097
1500
  },
1098
1501
  async getEntityBranches(projectId, projectBranch, entityId) {
1099
1502
  return client.request({
1100
1503
  method: "GET",
1101
- service: SERVICE2,
1504
+ service: SERVICE3,
1102
1505
  path: `/entity-branches/${enc(projectId)}/${enc(projectBranch)}/${enc(entityId)}`
1103
1506
  });
1104
1507
  },
1105
1508
  async createEntityBranch(request) {
1106
1509
  return client.request({
1107
1510
  method: "POST",
1108
- service: SERVICE2,
1511
+ service: SERVICE3,
1109
1512
  path: "/entity-branches/",
1110
1513
  body: request
1111
1514
  });
@@ -1114,7 +1517,7 @@ function createStorageService(client) {
1114
1517
  async merge(request) {
1115
1518
  return client.request({
1116
1519
  method: "POST",
1117
- service: SERVICE2,
1520
+ service: SERVICE3,
1118
1521
  path: "/merge/",
1119
1522
  body: request
1120
1523
  });
@@ -1122,7 +1525,7 @@ function createStorageService(client) {
1122
1525
  async fork(request) {
1123
1526
  return client.request({
1124
1527
  method: "POST",
1125
- service: SERVICE2,
1528
+ service: SERVICE3,
1126
1529
  path: "/fork/",
1127
1530
  body: request
1128
1531
  });
@@ -1131,16 +1534,63 @@ function createStorageService(client) {
1131
1534
  async searchProject(projectId, projectBranch, body) {
1132
1535
  return client.request({
1133
1536
  method: "POST",
1134
- service: SERVICE2,
1537
+ service: SERVICE3,
1135
1538
  path: `/project-searches/${enc(projectId)}/${enc(projectBranch)}`,
1136
1539
  body
1137
1540
  });
1541
+ },
1542
+ // --- Backups ---
1543
+ async createShortTermProjectBackup() {
1544
+ return client.request({
1545
+ method: "POST",
1546
+ service: SERVICE3,
1547
+ path: "/backups/project/short-term/create"
1548
+ });
1549
+ },
1550
+ async createLongTermProjectBackup() {
1551
+ return client.request({
1552
+ method: "POST",
1553
+ service: SERVICE3,
1554
+ path: "/backups/project/long-term/create"
1555
+ });
1556
+ },
1557
+ async restoreProjectBackup(request) {
1558
+ return client.request({
1559
+ method: "POST",
1560
+ service: SERVICE3,
1561
+ path: "/backups/project/restore",
1562
+ body: request
1563
+ });
1564
+ },
1565
+ async createShortTermFullBackup() {
1566
+ return client.request({
1567
+ method: "POST",
1568
+ service: SERVICE3,
1569
+ path: "/backups/full/short-term/create"
1570
+ });
1571
+ },
1572
+ async createLongTermFullBackup() {
1573
+ return client.request({
1574
+ method: "POST",
1575
+ service: SERVICE3,
1576
+ path: "/backups/full/long-term/create"
1577
+ });
1578
+ },
1579
+ async restoreFullBackup(request) {
1580
+ return client.request({
1581
+ method: "POST",
1582
+ service: SERVICE3,
1583
+ path: "/backups/full/restore",
1584
+ body: request
1585
+ });
1138
1586
  }
1587
+ // --- Event write ops (moved from read-only block) ---
1588
+ // NOTE: createEvents / consumeEvents already exist above in the Events section.
1139
1589
  };
1140
1590
  }
1141
1591
 
1142
1592
  // src/client/services/evaluation.ts
1143
- var SERVICE3 = "evaluation";
1593
+ var SERVICE4 = "evaluation";
1144
1594
  function enc2(s) {
1145
1595
  return encodeURIComponent(s);
1146
1596
  }
@@ -1150,7 +1600,7 @@ function createEvaluationService(client) {
1150
1600
  async call(request, async = false) {
1151
1601
  return client.request({
1152
1602
  method: "POST",
1153
- service: SERVICE3,
1603
+ service: SERVICE4,
1154
1604
  path: "/calls/",
1155
1605
  body: request,
1156
1606
  query: async ? { async: true } : void 0
@@ -1160,14 +1610,14 @@ function createEvaluationService(client) {
1160
1610
  async getEvaluations(projectId, projectBranch, functionId, functionBranch, year, month, day, hour) {
1161
1611
  return client.request({
1162
1612
  method: "GET",
1163
- service: SERVICE3,
1613
+ service: SERVICE4,
1164
1614
  path: `/evaluations/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}`
1165
1615
  });
1166
1616
  },
1167
1617
  async getEvaluation(projectId, projectBranch, functionId, functionBranch, year, month, day, hour, evaluationId, result = false) {
1168
1618
  return client.request({
1169
1619
  method: "GET",
1170
- service: SERVICE3,
1620
+ service: SERVICE4,
1171
1621
  path: `/evaluations/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}/${enc2(evaluationId)}`,
1172
1622
  query: result ? { result: true } : void 0
1173
1623
  });
@@ -1176,7 +1626,7 @@ function createEvaluationService(client) {
1176
1626
  async getLastEvaluation(projectId, projectBranch, functionId, functionBranch) {
1177
1627
  return client.request({
1178
1628
  method: "GET",
1179
- service: SERVICE3,
1629
+ service: SERVICE4,
1180
1630
  path: `/last-evaluation/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}`
1181
1631
  });
1182
1632
  },
@@ -1184,7 +1634,7 @@ function createEvaluationService(client) {
1184
1634
  async getOutputs(projectId, evaluationId) {
1185
1635
  return client.request({
1186
1636
  method: "GET",
1187
- service: SERVICE3,
1637
+ service: SERVICE4,
1188
1638
  path: `/output/${enc2(projectId)}/${enc2(evaluationId)}`
1189
1639
  });
1190
1640
  },
@@ -1192,7 +1642,7 @@ function createEvaluationService(client) {
1192
1642
  async getLogs(projectId, projectBranch, functionId, functionBranch, year, month, day, hour) {
1193
1643
  return client.request({
1194
1644
  method: "GET",
1195
- service: SERVICE3,
1645
+ service: SERVICE4,
1196
1646
  path: `/log/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}`
1197
1647
  });
1198
1648
  },
@@ -1200,7 +1650,7 @@ function createEvaluationService(client) {
1200
1650
  async getSourceCode(projectId, projectBranch, functionId, functionBranch, sourceCodeHash, sourceCodeId) {
1201
1651
  return client.request({
1202
1652
  method: "GET",
1203
- service: SERVICE3,
1653
+ service: SERVICE4,
1204
1654
  path: `/sourcecodes/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(sourceCodeHash)}/${enc2(sourceCodeId)}`
1205
1655
  });
1206
1656
  },
@@ -1208,7 +1658,7 @@ function createEvaluationService(client) {
1208
1658
  async stopEvaluation(projectId, projectBranch, functionId, functionBranch, year, month, day, hour, evaluationId) {
1209
1659
  return client.request({
1210
1660
  method: "POST",
1211
- service: SERVICE3,
1661
+ service: SERVICE4,
1212
1662
  path: `/stop/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}/${enc2(evaluationId)}`
1213
1663
  });
1214
1664
  },
@@ -1216,21 +1666,21 @@ function createEvaluationService(client) {
1216
1666
  async getTriggers(projectId, projectBranch, functionId, functionBranch) {
1217
1667
  return client.request({
1218
1668
  method: "GET",
1219
- service: SERVICE3,
1669
+ service: SERVICE4,
1220
1670
  path: `/triggers/actual/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}`
1221
1671
  });
1222
1672
  },
1223
1673
  async getTrigger(projectId, projectBranch, functionId, functionBranch, triggerId) {
1224
1674
  return client.request({
1225
1675
  method: "GET",
1226
- service: SERVICE3,
1676
+ service: SERVICE4,
1227
1677
  path: `/triggers/actual/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(triggerId)}`
1228
1678
  });
1229
1679
  },
1230
1680
  async saveTrigger(trigger) {
1231
1681
  return client.request({
1232
1682
  method: "PUT",
1233
- service: SERVICE3,
1683
+ service: SERVICE4,
1234
1684
  path: "/triggers/",
1235
1685
  body: trigger
1236
1686
  });
@@ -1238,7 +1688,7 @@ function createEvaluationService(client) {
1238
1688
  async deleteTrigger(projectId, projectBranch, functionId, functionBranch, triggerId) {
1239
1689
  return client.request({
1240
1690
  method: "DELETE",
1241
- service: SERVICE3,
1691
+ service: SERVICE4,
1242
1692
  path: `/triggers/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(triggerId)}`
1243
1693
  });
1244
1694
  },
@@ -1246,7 +1696,7 @@ function createEvaluationService(client) {
1246
1696
  async getEngines() {
1247
1697
  return client.request({
1248
1698
  method: "GET",
1249
- service: SERVICE3,
1699
+ service: SERVICE4,
1250
1700
  path: "/engines/"
1251
1701
  });
1252
1702
  }
@@ -1254,23 +1704,33 @@ function createEvaluationService(client) {
1254
1704
  }
1255
1705
 
1256
1706
  // src/client/services/scheduler.ts
1257
- var SERVICE4 = "scheduler";
1707
+ var SERVICE5 = "scheduler";
1708
+ function enc3(s) {
1709
+ return encodeURIComponent(s);
1710
+ }
1258
1711
  function createSchedulerService(client) {
1259
1712
  return {
1260
1713
  async scheduleCall(request) {
1261
1714
  return client.request({
1262
1715
  method: "POST",
1263
- service: SERVICE4,
1716
+ service: SERVICE5,
1264
1717
  path: "/calls/",
1265
1718
  body: request
1266
1719
  });
1720
+ },
1721
+ async stopScheduled(projectId, projectBranch, functionId, functionBranch, year, month, day, hour, evaluationId) {
1722
+ return client.request({
1723
+ method: "POST",
1724
+ service: SERVICE5,
1725
+ path: `/stop/${enc3(projectId)}/${enc3(projectBranch)}/${enc3(functionId)}/${enc3(functionBranch)}/${year}/${month}/${day}/${hour}/${enc3(evaluationId)}`
1726
+ });
1267
1727
  }
1268
1728
  };
1269
1729
  }
1270
1730
 
1271
1731
  // src/client/services/language.ts
1272
- var SERVICE5 = "language";
1273
- function enc3(s) {
1732
+ var SERVICE6 = "language";
1733
+ function enc4(s) {
1274
1734
  return encodeURIComponent(s);
1275
1735
  }
1276
1736
  function createLanguageService(client) {
@@ -1279,7 +1739,7 @@ function createLanguageService(client) {
1279
1739
  async chat(request) {
1280
1740
  return client.request({
1281
1741
  method: "POST",
1282
- service: SERVICE5,
1742
+ service: SERVICE6,
1283
1743
  path: "/chat/",
1284
1744
  body: request
1285
1745
  });
@@ -1288,7 +1748,7 @@ function createLanguageService(client) {
1288
1748
  async chatStream(request) {
1289
1749
  return client.requestRaw({
1290
1750
  method: "POST",
1291
- service: SERVICE5,
1751
+ service: SERVICE6,
1292
1752
  path: "/chat/stream",
1293
1753
  body: request
1294
1754
  });
@@ -1297,7 +1757,7 @@ function createLanguageService(client) {
1297
1757
  async upload(formData) {
1298
1758
  return client.request({
1299
1759
  method: "POST",
1300
- service: SERVICE5,
1760
+ service: SERVICE6,
1301
1761
  path: "/upload/",
1302
1762
  rawBody: formData
1303
1763
  });
@@ -1306,7 +1766,7 @@ function createLanguageService(client) {
1306
1766
  async getUsage() {
1307
1767
  return client.request({
1308
1768
  method: "GET",
1309
- service: SERVICE5,
1769
+ service: SERVICE6,
1310
1770
  path: "/usage/"
1311
1771
  });
1312
1772
  },
@@ -1314,36 +1774,36 @@ function createLanguageService(client) {
1314
1774
  async getSessions() {
1315
1775
  return client.request({
1316
1776
  method: "GET",
1317
- service: SERVICE5,
1777
+ service: SERVICE6,
1318
1778
  path: "/sessions/"
1319
1779
  });
1320
1780
  },
1321
1781
  async getSession(sessionId) {
1322
1782
  return client.request({
1323
1783
  method: "GET",
1324
- service: SERVICE5,
1325
- path: `/sessions/${enc3(sessionId)}`
1784
+ service: SERVICE6,
1785
+ path: `/sessions/${enc4(sessionId)}`
1326
1786
  });
1327
1787
  },
1328
1788
  async deleteSession(sessionId) {
1329
1789
  return client.request({
1330
1790
  method: "DELETE",
1331
- service: SERVICE5,
1332
- path: `/sessions/${enc3(sessionId)}`
1791
+ service: SERVICE6,
1792
+ path: `/sessions/${enc4(sessionId)}`
1333
1793
  });
1334
1794
  },
1335
1795
  async getSessionMessages(sessionId) {
1336
1796
  return client.request({
1337
1797
  method: "GET",
1338
- service: SERVICE5,
1339
- path: `/sessions/${enc3(sessionId)}/messages`
1798
+ service: SERVICE6,
1799
+ path: `/sessions/${enc4(sessionId)}/messages`
1340
1800
  });
1341
1801
  },
1342
1802
  async renameSession(sessionId, title) {
1343
1803
  return client.request({
1344
1804
  method: "PUT",
1345
- service: SERVICE5,
1346
- path: `/sessions/${enc3(sessionId)}/title`,
1805
+ service: SERVICE6,
1806
+ path: `/sessions/${enc4(sessionId)}/title`,
1347
1807
  rawBody: title,
1348
1808
  contentType: "text/plain"
1349
1809
  });
@@ -1352,8 +1812,8 @@ function createLanguageService(client) {
1352
1812
  }
1353
1813
 
1354
1814
  // src/client/services/index-search.ts
1355
- var SERVICE6 = "index";
1356
- function enc4(s) {
1815
+ var SERVICE7 = "index";
1816
+ function enc5(s) {
1357
1817
  return encodeURIComponent(s);
1358
1818
  }
1359
1819
  function createIndexService(client) {
@@ -1361,15 +1821,15 @@ function createIndexService(client) {
1361
1821
  async rebuildAll() {
1362
1822
  return client.request({
1363
1823
  method: "POST",
1364
- service: SERVICE6,
1824
+ service: SERVICE7,
1365
1825
  path: "/indexes/rebuild"
1366
1826
  });
1367
1827
  },
1368
1828
  async rebuildProject(projectId) {
1369
1829
  return client.request({
1370
1830
  method: "POST",
1371
- service: SERVICE6,
1372
- path: `/indexes/rebuild/${enc4(projectId)}`
1831
+ service: SERVICE7,
1832
+ path: `/indexes/rebuild/${enc5(projectId)}`
1373
1833
  });
1374
1834
  }
1375
1835
  };
@@ -1381,6 +1841,7 @@ function createApiClient(options = {}) {
1381
1841
  return {
1382
1842
  http,
1383
1843
  admin: createAdminService(http),
1844
+ analysis: createAnalysisService(http),
1384
1845
  storage: createStorageService(http),
1385
1846
  evaluation: createEvaluationService(http),
1386
1847
  scheduler: createSchedulerService(http),
@@ -1572,8 +2033,8 @@ function registerConfigCommands(program) {
1572
2033
  console.log(chalk7.green(`Profile "${name}" removed.`));
1573
2034
  });
1574
2035
  }
1575
- function setNestedValue(obj, path5, value) {
1576
- const keys = path5.split(".");
2036
+ function setNestedValue(obj, path7, value) {
2037
+ const keys = path7.split(".");
1577
2038
  let current = obj;
1578
2039
  for (let i = 0; i < keys.length - 1; i++) {
1579
2040
  const key = keys[i];
@@ -1584,8 +2045,8 @@ function setNestedValue(obj, path5, value) {
1584
2045
  }
1585
2046
  current[keys[keys.length - 1]] = value;
1586
2047
  }
1587
- function getNestedValue(obj, path5) {
1588
- const keys = path5.split(".");
2048
+ function getNestedValue(obj, path7) {
2049
+ const keys = path7.split(".");
1589
2050
  let current = obj;
1590
2051
  for (const key of keys) {
1591
2052
  if (current === null || current === void 0 || typeof current !== "object") {
@@ -1649,6 +2110,36 @@ function registerProjectCommands(program) {
1649
2110
  handleError(error);
1650
2111
  }
1651
2112
  });
2113
+ project.command("update").description("Update a project").argument("<projectId>", "Project ID").option("--visibility <visibility>", "PRIVATE or PUBLIC").option("--language <language>", "Project language").option("--group <groupId>", "Group ID (empty string to unset)").option("--active <bool>", "Whether the project is active (true/false)").action(async (projectId, options) => {
2114
+ try {
2115
+ const api = createApiClient();
2116
+ const current = await api.admin.getProject(projectId);
2117
+ const updated = {
2118
+ ...current,
2119
+ ...options.visibility ? { visibility: options.visibility.toUpperCase() } : {},
2120
+ ...options.language ? { language: options.language } : {},
2121
+ ...options.group !== void 0 ? { groupId: options.group || null } : {},
2122
+ ...options.active !== void 0 ? { active: options.active === "true" } : {}
2123
+ };
2124
+ await api.admin.updateProject(updated);
2125
+ console.log(chalk8.green(`Project "${projectId}" updated.`));
2126
+ } catch (error) {
2127
+ handleError(error);
2128
+ }
2129
+ });
2130
+ project.command("recent").description("List recently accessed projects").action(async (_options, cmd) => {
2131
+ try {
2132
+ const outputFormat = getOutputFormat(cmd);
2133
+ const api = createApiClient();
2134
+ const recent = await api.admin.getRecentProjects();
2135
+ format(recent, {
2136
+ format: outputFormat,
2137
+ columns: ["projectId", "projectBranch", "lastAccessed"]
2138
+ });
2139
+ } catch (error) {
2140
+ handleError(error);
2141
+ }
2142
+ });
1652
2143
  project.command("delete").description("Delete a project").argument("<projectId>", "Project ID").action(async (projectId) => {
1653
2144
  try {
1654
2145
  const api = createApiClient();
@@ -2103,6 +2594,43 @@ function registerEventCommands(program) {
2103
2594
  handleError(error);
2104
2595
  }
2105
2596
  });
2597
+ 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
+ try {
2599
+ const fs9 = await import("fs");
2600
+ const body = file ? fs9.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
2601
+ let data = "";
2602
+ process.stdin.setEncoding("utf-8");
2603
+ process.stdin.on("data", (chunk) => {
2604
+ data += chunk;
2605
+ });
2606
+ process.stdin.on("end", () => resolve(data));
2607
+ process.stdin.on("error", reject);
2608
+ });
2609
+ const events = JSON.parse(body);
2610
+ const api = createApiClient();
2611
+ const arr = Array.isArray(events) ? events : [events];
2612
+ await api.storage.createEvents(arr);
2613
+ console.log(chalk11.green(`${arr.length} event(s) created.`));
2614
+ } catch (error) {
2615
+ handleError(error);
2616
+ }
2617
+ });
2618
+ event.command("consume").description("Consume events for a given project and consumer").argument("<projectRef>", "Project reference (projectId or projectId/branch)").requiredOption("--consumer-type <type>", "Consumer type").requiredOption("--consumer-id <id>", "Consumer ID").option("--events <json>", "Event references as JSON array", "[]").action(async (projectRef, options) => {
2619
+ try {
2620
+ const [projectId, projectBranch = "main"] = projectRef.split("/");
2621
+ const api = createApiClient();
2622
+ const events = await api.storage.consumeEvents({
2623
+ projectId,
2624
+ projectBranch,
2625
+ eventReferences: JSON.parse(options.events),
2626
+ consumerType: options.consumerType,
2627
+ consumerId: options.consumerId
2628
+ });
2629
+ console.log(JSON.stringify(events, null, 2));
2630
+ } catch (error) {
2631
+ handleError(error);
2632
+ }
2633
+ });
2106
2634
  event.command("delete").description("Delete an event").argument("<ref>", "Entity reference").argument("<eventId>", "Event ID").argument("<occurrenceId>", "Occurrence ID").action(async (ref, eventId, occurrenceId, _options, cmd) => {
2107
2635
  try {
2108
2636
  const overrides = getOverrides3(cmd);
@@ -2428,7 +2956,61 @@ function registerTableCommands(program) {
2428
2956
 
2429
2957
  // src/commands/function/index.ts
2430
2958
  import chalk14 from "chalk";
2959
+ import * as fs4 from "fs";
2960
+ import * as os2 from "os";
2961
+ import * as path3 from "path";
2962
+ import { spawn } from "child_process";
2431
2963
  import { randomUUID } from "crypto";
2964
+
2965
+ // src/util/function-content.ts
2966
+ function decodeFunctionSource(entity) {
2967
+ if (!entity.content) return "";
2968
+ const json = Buffer.from(entity.content, "base64").toString("utf-8");
2969
+ try {
2970
+ const parsed = JSON.parse(json);
2971
+ return parsed.sourceCode ?? "";
2972
+ } catch {
2973
+ return json;
2974
+ }
2975
+ }
2976
+ function encodeFunctionSource(sourceCode) {
2977
+ return Buffer.from(JSON.stringify({ sourceCode })).toString("base64");
2978
+ }
2979
+ function buildFunctionEntity(args) {
2980
+ const now = Date.now();
2981
+ const attributes = { language: args.language };
2982
+ const attributeTypes = { language: "text" };
2983
+ if (args.name !== null && args.name !== void 0) {
2984
+ attributes.name = args.name;
2985
+ attributeTypes.name = "text";
2986
+ }
2987
+ return {
2988
+ projectId: args.projectId,
2989
+ projectBranch: args.projectBranch,
2990
+ entityId: args.entityId,
2991
+ entityBranch: args.entityBranch,
2992
+ head: true,
2993
+ version: 1,
2994
+ type: "function",
2995
+ attributes,
2996
+ attributeTypes,
2997
+ metaAttributes: {},
2998
+ metaAttributeTypes: {},
2999
+ tags: [],
3000
+ modified: now,
3001
+ created: now,
3002
+ versioned: false,
3003
+ versionTtl: null,
3004
+ retain: false,
3005
+ contentAvailable: true,
3006
+ contentLoaded: true,
3007
+ contentType: "application/script",
3008
+ contentSize: null,
3009
+ content: encodeFunctionSource(args.sourceCode)
3010
+ };
3011
+ }
3012
+
3013
+ // src/commands/function/index.ts
2432
3014
  function getOutputFormat7(cmd) {
2433
3015
  const config = loadConfig();
2434
3016
  const globalOpts = cmd.optsWithGlobals();
@@ -2641,6 +3223,121 @@ function registerFunctionCommands(program) {
2641
3223
  handleError(error);
2642
3224
  }
2643
3225
  });
3226
+ fn.command("last-evaluation").description("Show the most recent evaluation of a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
3227
+ try {
3228
+ const outputFormat = getOutputFormat7(cmd);
3229
+ const overrides = getOverrides6(cmd);
3230
+ const resolved = parseEntityReference(ref, overrides);
3231
+ const api = createApiClient();
3232
+ const evaluation = await api.evaluation.getLastEvaluation(
3233
+ resolved.projectId,
3234
+ resolved.projectBranch,
3235
+ resolved.entityId,
3236
+ resolved.entityBranch
3237
+ );
3238
+ format(evaluation, { format: outputFormat });
3239
+ } catch (error) {
3240
+ handleError(error);
3241
+ }
3242
+ });
3243
+ fn.command("create").description("Create a new function entity").argument("<ref>", "Function entity reference").option("--language <lang>", "Function language (Java, JavaScript, Kotlin, Python, Scala)", "Java").option("--source <file>", "Initial source code file").option("--name <name>", "Display name (defaults to entityId)").action(async (ref, options, cmd) => {
3244
+ try {
3245
+ const overrides = getOverrides6(cmd);
3246
+ const resolved = parseEntityReference(ref, overrides);
3247
+ const api = createApiClient();
3248
+ const sourceCode = options.source ? fs4.readFileSync(options.source, "utf-8") : "";
3249
+ const entity = buildFunctionEntity({
3250
+ projectId: resolved.projectId,
3251
+ projectBranch: resolved.projectBranch,
3252
+ entityId: resolved.entityId,
3253
+ entityBranch: resolved.entityBranch,
3254
+ name: options.name ?? resolved.entityId,
3255
+ language: options.language,
3256
+ sourceCode
3257
+ });
3258
+ await api.storage.saveEntities([entity]);
3259
+ console.log(chalk14.green(`Function "${resolved.entityId}" created (${options.language}).`));
3260
+ } catch (error) {
3261
+ handleError(error);
3262
+ }
3263
+ });
3264
+ const source = fn.command("source").description("Get or set function source code");
3265
+ source.command("get").description("Print the function source code").argument("<ref>", "Function entity reference").option("--out <file>", "Write source to this file instead of stdout").action(async (ref, options, cmd) => {
3266
+ try {
3267
+ const overrides = getOverrides6(cmd);
3268
+ const resolved = parseEntityReference(ref, overrides);
3269
+ const api = createApiClient();
3270
+ const entity = await api.storage.getEntity(resolved, true);
3271
+ const sourceCode = decodeFunctionSource(entity);
3272
+ if (options.out) {
3273
+ fs4.writeFileSync(options.out, sourceCode);
3274
+ console.log(chalk14.green(`Source written to ${options.out}`));
3275
+ } else {
3276
+ process.stdout.write(sourceCode);
3277
+ if (!sourceCode.endsWith("\n")) process.stdout.write("\n");
3278
+ }
3279
+ } catch (error) {
3280
+ handleError(error);
3281
+ }
3282
+ });
3283
+ source.command("set").description("Replace the function source code from a file or stdin").argument("<ref>", "Function entity reference").argument("[file]", "Source file; defaults to stdin").action(async (ref, file, _options, cmd) => {
3284
+ try {
3285
+ const overrides = getOverrides6(cmd);
3286
+ const resolved = parseEntityReference(ref, overrides);
3287
+ const api = createApiClient();
3288
+ const sourceCode = file ? fs4.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
3289
+ let data = "";
3290
+ process.stdin.setEncoding("utf-8");
3291
+ process.stdin.on("data", (chunk) => {
3292
+ data += chunk;
3293
+ });
3294
+ process.stdin.on("end", () => resolve(data));
3295
+ process.stdin.on("error", reject);
3296
+ });
3297
+ await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(sourceCode));
3298
+ console.log(chalk14.green(`Source updated for "${resolved.entityId}".`));
3299
+ } catch (error) {
3300
+ handleError(error);
3301
+ }
3302
+ });
3303
+ fn.command("edit").description("Open the function source in $EDITOR and save on exit").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
3304
+ try {
3305
+ const overrides = getOverrides6(cmd);
3306
+ const resolved = parseEntityReference(ref, overrides);
3307
+ const api = createApiClient();
3308
+ const entity = await api.storage.getEntity(resolved, true);
3309
+ const currentSource = decodeFunctionSource(entity);
3310
+ const language = entity.attributes?.["language"] ?? "txt";
3311
+ const ext = extensionFor(language);
3312
+ const tmpFile = path3.join(os2.tmpdir(), `diafunc-${resolved.entityId}-${randomUUID()}.${ext}`);
3313
+ fs4.writeFileSync(tmpFile, currentSource);
3314
+ const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
3315
+ await new Promise((resolve, reject) => {
3316
+ const child = spawn(editor, [tmpFile], { stdio: "inherit" });
3317
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`Editor exited with code ${code}`)));
3318
+ child.on("error", reject);
3319
+ });
3320
+ const newSource = fs4.readFileSync(tmpFile, "utf-8");
3321
+ fs4.unlinkSync(tmpFile);
3322
+ if (newSource === currentSource) {
3323
+ console.log(chalk14.dim("No changes."));
3324
+ return;
3325
+ }
3326
+ await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(newSource));
3327
+ console.log(chalk14.green(`Source updated for "${resolved.entityId}".`));
3328
+ } catch (error) {
3329
+ handleError(error);
3330
+ }
3331
+ });
3332
+ }
3333
+ function extensionFor(language) {
3334
+ const l = language.toLowerCase();
3335
+ if (l === "java") return "java";
3336
+ if (l === "javascript" || l === "js") return "js";
3337
+ if (l === "kotlin") return "kt";
3338
+ if (l === "python") return "py";
3339
+ if (l === "scala") return "scala";
3340
+ return "txt";
2644
3341
  }
2645
3342
 
2646
3343
  // src/commands/trigger/index.ts
@@ -2719,6 +3416,54 @@ function registerTriggerCommands(program) {
2719
3416
  handleError(error);
2720
3417
  }
2721
3418
  });
3419
+ trigger.command("create").description("Create or update a trigger on a function").argument("<ref>", "Function entity reference").requiredOption("--type <type>", "Trigger type (SCHEDULE, EVENT, LINK, MANUAL)").option("--trigger-id <id>", "Trigger ID (auto-generated if omitted)").option("--expression <expr>", "Cron expression (for SCHEDULE) or event pattern").option("--origin <ref>", "Origin entity reference (for LINK/EVENT)").option("--persistent", "Persistent trigger (survives after first fire)").option("--inactive", "Create the trigger inactive").option("--max <n>", "Maximum fire count (0 = unlimited)", "0").option("--args <json>", "Arguments passed on fire (JSON object)").action(async (ref, options, cmd) => {
3420
+ try {
3421
+ const overrides = getOverrides7(cmd);
3422
+ const fn = parseEntityReference(ref, overrides);
3423
+ const api = createApiClient();
3424
+ const args = options.args ? JSON.parse(options.args) : null;
3425
+ const types = args ? Object.fromEntries(
3426
+ Object.entries(args).map(([k, v]) => [k, typeof v === "number" ? "number" : typeof v === "boolean" ? "bool" : "string"])
3427
+ ) : null;
3428
+ let originEntityId = null;
3429
+ let originEntityBranch = null;
3430
+ if (options.origin) {
3431
+ const o = parseEntityReference(options.origin, overrides);
3432
+ originEntityId = o.entityId;
3433
+ originEntityBranch = o.entityBranch;
3434
+ }
3435
+ await api.evaluation.saveTrigger({
3436
+ projectId: fn.projectId,
3437
+ projectBranch: fn.projectBranch,
3438
+ functionId: fn.entityId,
3439
+ functionBranch: fn.entityBranch,
3440
+ triggerId: options.triggerId ?? null,
3441
+ bucketId: null,
3442
+ type: options.type.toUpperCase(),
3443
+ expression: options.expression ?? null,
3444
+ conditions: null,
3445
+ conditionTypes: null,
3446
+ originEntityId,
3447
+ originEntityBranch,
3448
+ active: !options.inactive,
3449
+ quantity: 0,
3450
+ fired: 0,
3451
+ maximum: options.max ? parseInt(options.max, 10) || null : null,
3452
+ evaluationIds: null,
3453
+ arguments: args,
3454
+ types,
3455
+ persistent: !!options.persistent,
3456
+ removeFunction: false,
3457
+ modified: null,
3458
+ created: null,
3459
+ scheduler: null,
3460
+ heartbeat: null
3461
+ });
3462
+ console.log(chalk15.green("Trigger saved."));
3463
+ } catch (error) {
3464
+ handleError(error);
3465
+ }
3466
+ });
2722
3467
  }
2723
3468
 
2724
3469
  // src/commands/schedule/index.ts
@@ -2782,19 +3527,182 @@ function registerScheduleCommands(program) {
2782
3527
  handleError(error);
2783
3528
  }
2784
3529
  });
2785
- }
2786
-
2787
- // src/commands/chat/index.ts
2788
- import chalk17 from "chalk";
2789
- import * as fs4 from "fs";
2790
- import * as path3 from "path";
2791
- function getOutputFormat10(cmd) {
3530
+ schedule.command("stop").description("Stop a scheduled function evaluation").argument("<ref>", "Function entity reference").argument("<evaluationId>", "Evaluation ID to stop").requiredOption("--date <date>", "Evaluation date/hour (YYYY-MM-DD-HH in UTC)").action(async (ref, evaluationId, options, cmd) => {
3531
+ try {
3532
+ const overrides = getOverrides8(cmd);
3533
+ const resolved = parseEntityReference(ref, overrides);
3534
+ const api = createApiClient();
3535
+ const [year, month, day, hour] = options.date.split("-").map(Number);
3536
+ await api.scheduler.stopScheduled(
3537
+ resolved.projectId,
3538
+ resolved.projectBranch,
3539
+ resolved.entityId,
3540
+ resolved.entityBranch,
3541
+ year,
3542
+ month,
3543
+ day,
3544
+ hour,
3545
+ evaluationId
3546
+ );
3547
+ console.log(chalk16.green(`Scheduled evaluation ${evaluationId} stopped.`));
3548
+ } catch (error) {
3549
+ handleError(error);
3550
+ }
3551
+ });
3552
+ schedule.command("list").description("List persistent triggers (scheduled functions are modeled as triggers)").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
3553
+ try {
3554
+ const outputFormat = getOutputFormat9(cmd);
3555
+ const overrides = getOverrides8(cmd);
3556
+ const resolved = parseEntityReference(ref, overrides);
3557
+ const api = createApiClient();
3558
+ const triggers = await api.evaluation.getTriggers(
3559
+ resolved.projectId,
3560
+ resolved.projectBranch,
3561
+ resolved.entityId,
3562
+ resolved.entityBranch
3563
+ );
3564
+ const scheduled = triggers.filter((t) => t.type === "SCHEDULE");
3565
+ const rows = scheduled.map((t) => ({
3566
+ triggerId: t.triggerId,
3567
+ expression: t.expression,
3568
+ active: t.active,
3569
+ fired: t.fired,
3570
+ maximum: t.maximum,
3571
+ persistent: t.persistent
3572
+ }));
3573
+ format(rows, {
3574
+ format: outputFormat,
3575
+ columns: ["triggerId", "expression", "active", "fired", "maximum", "persistent"]
3576
+ });
3577
+ } catch (error) {
3578
+ handleError(error);
3579
+ }
3580
+ });
3581
+ }
3582
+
3583
+ // src/commands/chat/index.ts
3584
+ import chalk17 from "chalk";
3585
+ import * as fs5 from "fs";
3586
+ import * as path4 from "path";
3587
+ function getOutputFormat10(cmd) {
2792
3588
  const config = loadConfig();
2793
3589
  const globalOpts = cmd.optsWithGlobals();
2794
3590
  return globalOpts.output ?? config.defaults.output ?? "human";
2795
3591
  }
3592
+ async function streamOneTurn(message, sessionId, projectId, branch) {
3593
+ const api = createApiClient();
3594
+ const response = await api.language.chatStream({
3595
+ message,
3596
+ sessionId,
3597
+ projectId,
3598
+ projectBranch: projectId ? branch : void 0
3599
+ });
3600
+ const reader = response.body.getReader();
3601
+ const decoder = new TextDecoder();
3602
+ let buffer = "";
3603
+ let finalSession = sessionId ?? "";
3604
+ let input = 0;
3605
+ let output = 0;
3606
+ while (true) {
3607
+ const { done, value } = await reader.read();
3608
+ if (done) break;
3609
+ buffer += decoder.decode(value, { stream: true });
3610
+ const lines = buffer.split("\n");
3611
+ buffer = lines.pop() ?? "";
3612
+ for (const line of lines) {
3613
+ if (!line.startsWith("data:")) continue;
3614
+ const data = line.slice(5).trim();
3615
+ if (!data) continue;
3616
+ try {
3617
+ const event = JSON.parse(data);
3618
+ if (event.type === "token" && event.content) {
3619
+ process.stdout.write(event.content);
3620
+ } else if (event.type === "done") {
3621
+ finalSession = event.sessionId ?? finalSession;
3622
+ input = event.inputTokens;
3623
+ output = event.outputTokens;
3624
+ } else if (event.type === "error") {
3625
+ console.error(chalk17.red(`
3626
+ Error: ${event.content}`));
3627
+ }
3628
+ } catch {
3629
+ }
3630
+ }
3631
+ }
3632
+ return { sessionId: finalSession, input, output };
3633
+ }
3634
+ async function runChatRepl(options) {
3635
+ const { input: promptInput } = await import("@inquirer/prompts");
3636
+ let sessionId = options.session;
3637
+ console.log(chalk17.bold("Diafunc chat") + chalk17.dim(" \xB7 /help for commands, /quit to exit"));
3638
+ if (sessionId) {
3639
+ console.log(chalk17.dim(`Continuing session ${sessionId}`));
3640
+ }
3641
+ console.log();
3642
+ for (; ; ) {
3643
+ let line;
3644
+ try {
3645
+ line = await promptInput({ message: chalk17.cyan.bold("you >") });
3646
+ } catch {
3647
+ console.log();
3648
+ return;
3649
+ }
3650
+ const trimmed = line.trim();
3651
+ if (!trimmed) continue;
3652
+ if (trimmed.startsWith("/")) {
3653
+ const [cmd, ...rest] = trimmed.slice(1).split(/\s+/);
3654
+ const arg = rest.join(" ");
3655
+ switch (cmd) {
3656
+ case "quit":
3657
+ case "exit":
3658
+ case "q":
3659
+ return;
3660
+ case "new":
3661
+ sessionId = void 0;
3662
+ console.log(chalk17.dim("Started a new session."));
3663
+ continue;
3664
+ case "session":
3665
+ if (!arg) {
3666
+ console.log(chalk17.dim(`Current session: ${sessionId ?? "(new)"}`));
3667
+ } else {
3668
+ sessionId = arg;
3669
+ console.log(chalk17.dim(`Switched to session ${sessionId}`));
3670
+ }
3671
+ continue;
3672
+ case "help":
3673
+ case "h":
3674
+ case "?":
3675
+ console.log(chalk17.dim(" /new start a new session"));
3676
+ console.log(chalk17.dim(" /session [id] switch to a session (no id = show current)"));
3677
+ console.log(chalk17.dim(" /quit exit the REPL"));
3678
+ continue;
3679
+ default:
3680
+ console.log(chalk17.dim(`Unknown command: /${cmd}. Try /help.`));
3681
+ continue;
3682
+ }
3683
+ }
3684
+ process.stdout.write(chalk17.magenta.bold("diafunc > "));
3685
+ try {
3686
+ const result = await streamOneTurn(trimmed, sessionId, options.project, options.branch);
3687
+ sessionId = result.sessionId || sessionId;
3688
+ console.log();
3689
+ console.log(chalk17.dim(`[session ${sessionId} \xB7 ${result.input} in / ${result.output} out]`));
3690
+ console.log();
3691
+ } catch (error) {
3692
+ console.error(chalk17.red(`
3693
+ Request failed: ${error.message}`));
3694
+ }
3695
+ }
3696
+ }
2796
3697
  function registerChatCommands(program) {
2797
3698
  const chat = program.command("chat").description("AI chat");
3699
+ chat.option("--session <id>", "Continue an existing session").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").action(async (options) => {
3700
+ try {
3701
+ await runChatRepl(options);
3702
+ } catch (error) {
3703
+ handleError(error);
3704
+ }
3705
+ });
2798
3706
  chat.command("send").description("Send a chat message (blocking)").argument("<message>", "Message to send").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
2799
3707
  try {
2800
3708
  const outputFormat = getOutputFormat10(cmd);
@@ -2890,15 +3798,15 @@ Error: ${event.content}`));
2890
3798
  });
2891
3799
  chat.command("upload").description("Upload a file for chat context").argument("<file>", "File to upload").action(async (file) => {
2892
3800
  try {
2893
- if (!fs4.existsSync(file)) {
3801
+ if (!fs5.existsSync(file)) {
2894
3802
  console.error(chalk17.red(`File not found: ${file}`));
2895
3803
  process.exit(1);
2896
3804
  }
2897
3805
  const api = createApiClient();
2898
- const fileBuffer = fs4.readFileSync(file);
3806
+ const fileBuffer = fs5.readFileSync(file);
2899
3807
  const blob = new Blob([fileBuffer]);
2900
3808
  const formData = new FormData();
2901
- formData.append("file", blob, path3.basename(file));
3809
+ formData.append("file", blob, path4.basename(file));
2902
3810
  const result = await api.language.upload(formData);
2903
3811
  console.log(chalk17.green(`File uploaded: ${result}`));
2904
3812
  } catch (error) {
@@ -2928,6 +3836,36 @@ Error: ${event.content}`));
2928
3836
  handleError(error);
2929
3837
  }
2930
3838
  });
3839
+ session.command("show").description("Show the message history of a chat session").argument("<sessionId>", "Session ID").action(async (sessionId, _options, cmd) => {
3840
+ try {
3841
+ const outputFormat = getOutputFormat10(cmd);
3842
+ const api = createApiClient();
3843
+ const detail = await api.language.getSession(sessionId);
3844
+ if (outputFormat === "human") {
3845
+ console.log(chalk17.bold(detail.title) + chalk17.dim(` (${detail.sessionId})`));
3846
+ console.log();
3847
+ for (const msg of detail.messages) {
3848
+ const role = msg.role === "user" ? chalk17.cyan.bold("You") : chalk17.magenta.bold("Diafunc");
3849
+ console.log(`${role} ${chalk17.dim(msg.created)}`);
3850
+ console.log(msg.content);
3851
+ console.log();
3852
+ }
3853
+ } else {
3854
+ format(detail, { format: outputFormat });
3855
+ }
3856
+ } catch (error) {
3857
+ handleError(error);
3858
+ }
3859
+ });
3860
+ session.command("rename").description("Rename a chat session").argument("<sessionId>", "Session ID").argument("<title>", "New title").action(async (sessionId, title) => {
3861
+ try {
3862
+ const api = createApiClient();
3863
+ await api.language.renameSession(sessionId, title);
3864
+ console.log(chalk17.green(`Session "${sessionId}" renamed to "${title}".`));
3865
+ } catch (error) {
3866
+ handleError(error);
3867
+ }
3868
+ });
2931
3869
  chat.command("usage").description("Show token usage").action(async (_options, cmd) => {
2932
3870
  try {
2933
3871
  const outputFormat = getOutputFormat10(cmd);
@@ -3017,6 +3955,15 @@ function registerGroupCommands(program) {
3017
3955
  handleError(error);
3018
3956
  }
3019
3957
  });
3958
+ group.command("update").description("Update a group").argument("<groupId>", "Group ID").requiredOption("--name <name>", "New group name").action(async (groupId, options) => {
3959
+ try {
3960
+ const api = createApiClient();
3961
+ await api.admin.updateGroup({ groupId, name: options.name });
3962
+ console.log(chalk18.green(`Group "${groupId}" updated.`));
3963
+ } catch (error) {
3964
+ handleError(error);
3965
+ }
3966
+ });
3020
3967
  group.command("delete").description("Delete a group").argument("<groupId>", "Group ID").action(async (groupId) => {
3021
3968
  try {
3022
3969
  const api = createApiClient();
@@ -3157,20 +4104,72 @@ function registerAdminCommands(program) {
3157
4104
  }
3158
4105
  });
3159
4106
  const backup = admin.command("backup").description("Manage backups");
3160
- backup.command("create-full").description("Create a full system backup").action(async () => {
4107
+ backup.command("create-full").description("Create a full system short-term backup").option("--long-term", "Create a long-term backup instead").action(async (options) => {
4108
+ try {
4109
+ const api = createApiClient();
4110
+ if (options.longTerm) {
4111
+ await api.storage.createLongTermFullBackup();
4112
+ console.log(chalk19.green("Full long-term backup initiated."));
4113
+ } else {
4114
+ await api.storage.createShortTermFullBackup();
4115
+ console.log(chalk19.green("Full short-term backup initiated."));
4116
+ }
4117
+ } catch (error) {
4118
+ handleError(error);
4119
+ }
4120
+ });
4121
+ backup.command("project").description("Create a project short-term backup (use --long-term for long-term)").option("--long-term", "Create a long-term backup instead").action(async (options) => {
4122
+ try {
4123
+ const api = createApiClient();
4124
+ if (options.longTerm) {
4125
+ await api.storage.createLongTermProjectBackup();
4126
+ console.log(chalk19.green("Project long-term backup initiated."));
4127
+ } else {
4128
+ await api.storage.createShortTermProjectBackup();
4129
+ console.log(chalk19.green("Project short-term backup initiated."));
4130
+ }
4131
+ } catch (error) {
4132
+ handleError(error);
4133
+ }
4134
+ });
4135
+ backup.command("restore-project").description("Restore a project from a backup bucket+object").argument("<projectId>", "Project ID").argument("<projectBranch>", "Project branch").argument("<bucketName>", "Backup bucket name").argument("<objectName>", "Backup object name").action(async (projectId, projectBranch, bucketName, objectName) => {
4136
+ try {
4137
+ const api = createApiClient();
4138
+ await api.storage.restoreProjectBackup({ projectId, projectBranch, bucketName, objectName });
4139
+ console.log(chalk19.green(`Restore initiated for ${projectId}/${projectBranch} from ${bucketName}/${objectName}.`));
4140
+ } catch (error) {
4141
+ handleError(error);
4142
+ }
4143
+ });
4144
+ backup.command("restore-full").description("Restore a full system backup from a bucket+object").argument("<bucketName>", "Backup bucket name").argument("<objectName>", "Backup object name").action(async (bucketName, objectName) => {
4145
+ try {
4146
+ const api = createApiClient();
4147
+ await api.storage.restoreFullBackup({ bucketName, objectName });
4148
+ console.log(chalk19.green(`Full restore initiated from ${bucketName}/${objectName}.`));
4149
+ } catch (error) {
4150
+ handleError(error);
4151
+ }
4152
+ });
4153
+ admin.command("index-rebuild").description("Rebuild all search indexes (or a specific project with --project)").option("--project <id>", "Project ID to rebuild").action(async (options) => {
3161
4154
  try {
3162
4155
  const api = createApiClient();
3163
- await api.admin.createShortTermFullBackup();
3164
- console.log(chalk19.green("Full backup initiated."));
4156
+ if (options.project) {
4157
+ await api.index.rebuildProject(options.project);
4158
+ console.log(chalk19.green(`Index rebuild initiated for project "${options.project}".`));
4159
+ } else {
4160
+ await api.index.rebuildAll();
4161
+ console.log(chalk19.green("Index rebuild initiated for all projects."));
4162
+ }
3165
4163
  } catch (error) {
3166
4164
  handleError(error);
3167
4165
  }
3168
4166
  });
3169
- backup.command("project").description("Create a project backup").argument("<projectId>", "Project ID").action(async (projectId) => {
4167
+ admin.command("permissions").description("Show your permissions on a project").argument("<projectId>", "Project ID").action(async (projectId, _options, cmd) => {
3170
4168
  try {
4169
+ const outputFormat = getOutputFormat13(cmd);
3171
4170
  const api = createApiClient();
3172
- await api.admin.createShortTermProjectBackup({ projectId });
3173
- console.log(chalk19.green(`Project backup for "${projectId}" initiated.`));
4171
+ const perm = await api.admin.getPermissions(projectId);
4172
+ format(perm, { format: outputFormat });
3174
4173
  } catch (error) {
3175
4174
  handleError(error);
3176
4175
  }
@@ -3184,8 +4183,8 @@ import chalk20 from "chalk";
3184
4183
  function createStatusService() {
3185
4184
  const config = loadConfig();
3186
4185
  const endpoint = resolveEndpoint(config);
3187
- async function fetchJson(path5) {
3188
- const url = `${endpoint}/status/v1${path5}`;
4186
+ async function fetchJson(path7) {
4187
+ const url = `${endpoint}/status/v1${path7}`;
3189
4188
  const response = await fetch(url, {
3190
4189
  headers: { "Accept": "application/json" }
3191
4190
  });
@@ -3368,8 +4367,9 @@ function registerStatusCommands(program) {
3368
4367
 
3369
4368
  // src/commands/analyze/index.ts
3370
4369
  import chalk23 from "chalk";
3371
- import * as fs5 from "fs";
3372
- import * as path4 from "path";
4370
+ import * as fs6 from "fs";
4371
+ import * as path5 from "path";
4372
+ import { spawn as spawn2 } from "child_process";
3373
4373
  import { randomUUID as randomUUID3 } from "crypto";
3374
4374
  function createEntity(projectId, entityId, entityType, name, description, attributes, tags, contentType, content) {
3375
4375
  const now = Date.now();
@@ -3418,83 +4418,89 @@ function createEntity(projectId, entityId, entityType, name, description, attrib
3418
4418
  }
3419
4419
  return entity;
3420
4420
  }
3421
- function generateSourceCode(rawDataTableId, analysisChapterId, timeHours) {
3422
- return `var rawDataTable = diafunc.table("${rawDataTableId}");
3423
- var analysisChapter = diafunc.chapter("${analysisChapterId}");
3424
-
3425
- return diafunc
3426
- .analyze()
3427
- .automatic()
3428
- .from(rawDataTable)
3429
- .to(analysisChapter)
3430
- .hours(${timeHours});`;
4421
+ function formatDuration(ms) {
4422
+ const seconds = Math.floor(ms / 1e3);
4423
+ const minutes = Math.floor(seconds / 60);
4424
+ const hours = Math.floor(minutes / 60);
4425
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
4426
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
4427
+ return `${seconds}s`;
3431
4428
  }
3432
- function stringToBinary(str) {
3433
- return Buffer.from(str).toString("base64");
4429
+ function analysisUrl(analysis, endpoint) {
4430
+ return `${endpoint}/lab/${analysis.projectId}/main/entities/${analysis.notebookId}/main`;
3434
4431
  }
3435
- function registerAnalyzeCommand(program) {
3436
- program.command("analyze").description("Run an automatic analysis on a data file").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("--resume [id]", "Resume a previous analysis").option("--open", "Open in browser on completion").action(async (file, options, cmd) => {
3437
- try {
3438
- const api = createApiClient();
3439
- if (options.resume !== void 0) {
3440
- await resumeAnalysis(api, options.resume === true ? void 0 : options.resume, cmd);
3441
- return;
3442
- }
3443
- if (!file) {
3444
- console.error(chalk23.red("Please provide a data file to analyze, or use --resume."));
3445
- process.exit(1);
3446
- }
3447
- if (!fs5.existsSync(file)) {
3448
- console.error(chalk23.red(`File not found: ${file}`));
3449
- process.exit(1);
3450
- }
3451
- const projectName = options.name ?? path4.basename(file, path4.extname(file));
3452
- const visibility = options.visibility.toUpperCase();
3453
- const analysis = {
3454
- userId: null,
3455
- analysisId: randomUUID3(),
3456
- phase: "PREPARATION",
3457
- step: "CREATE_PROJECT",
3458
- projectName,
3459
- projectDescription: options.description,
3460
- visibility,
3461
- time: options.time,
3462
- budget: options.budget,
3463
- projectId: null,
3464
- notebookId: null,
3465
- rawDataTableId: null,
3466
- analysisFunctionId: null,
3467
- analysisChapterId: null,
3468
- year: null,
3469
- month: null,
3470
- day: null,
3471
- hour: null,
3472
- evaluationId: null,
3473
- started: null
3474
- };
3475
- process.stdout.write(`Creating project "${projectName}" ...`);
3476
- await createProjectStructure(api, analysis);
3477
- console.log(chalk23.green(" done"));
3478
- process.stdout.write(`Importing ${path4.basename(file)} ...`);
3479
- await importData(api, analysis, file);
3480
- console.log(chalk23.green(" done"));
3481
- process.stdout.write("Launching analysis ...");
3482
- await launchAnalysis(api, analysis);
3483
- console.log(chalk23.green(" done"));
3484
- console.log();
3485
- await monitorAnalysis(api, analysis, cmd);
3486
- } catch (error) {
3487
- handleError(error);
3488
- }
3489
- });
4432
+ function openUrl(url) {
4433
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
4434
+ const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
4435
+ spawn2(cmd, args, { detached: true, stdio: "ignore" }).unref();
4436
+ }
4437
+ function getOutputFormat14(cmd) {
4438
+ const config = loadConfig();
4439
+ const globalOpts = cmd.optsWithGlobals();
4440
+ return globalOpts.output ?? config.defaults.output ?? "human";
4441
+ }
4442
+ function parseCsv(value) {
4443
+ if (value === void 0) return null;
4444
+ return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4445
+ }
4446
+ function isTerminalState(state) {
4447
+ return state === "COMPLETED" || state === "FAILED" || state === "CANCELLED";
3490
4448
  }
3491
- async function createProjectStructure(api, analysis) {
4449
+ async function runAnalysis(file, options, cmd) {
4450
+ if (!fs6.existsSync(file)) {
4451
+ console.error(chalk23.red(`File not found: ${file}`));
4452
+ process.exit(1);
4453
+ }
4454
+ 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,
4464
+ visibility,
4465
+ time: options.time,
4466
+ 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),
4479
+ questions: parseCsv(options.questions),
4480
+ segmentKey: options.segment ?? null
4481
+ };
4482
+ process.stdout.write(`Creating project "${projectName}" ...`);
4483
+ const { projectId, rawDataTableId } = await provisionProject(api, recipe);
4484
+ recipe.projectId = projectId;
4485
+ recipe.rawDataTableId = rawDataTableId;
4486
+ console.log(chalk23.green(" done"));
4487
+ process.stdout.write(`Importing ${path5.basename(file)} ...`);
4488
+ await importData(api, projectId, rawDataTableId, file);
4489
+ console.log(chalk23.green(" done"));
4490
+ process.stdout.write("Queuing analysis run ...");
4491
+ const run = await api.analysis.createAndRun(recipe);
4492
+ console.log(chalk23.green(" done"));
4493
+ console.log(chalk23.dim(` analysisId: ${run.analysisId}`));
4494
+ console.log(chalk23.dim(` runId: ${run.runId}`));
4495
+ console.log();
4496
+ await monitorRun(api, run.runId, recipe, cmd);
4497
+ }
4498
+ async function provisionProject(api, recipe) {
3492
4499
  const project = await api.admin.createProject({
3493
- visibility: analysis.visibility,
4500
+ visibility: recipe.visibility,
3494
4501
  language: "Java",
3495
4502
  active: true
3496
4503
  });
3497
- analysis.projectId = project.projectId;
3498
4504
  await api.storage.createProjectBranch({
3499
4505
  projectId: project.projectId,
3500
4506
  sourceProjectBranch: null,
@@ -3504,258 +4510,524 @@ async function createProjectStructure(api, analysis) {
3504
4510
  project.projectId,
3505
4511
  project.projectId,
3506
4512
  "project",
3507
- analysis.projectName,
3508
- analysis.projectDescription,
4513
+ recipe.projectName,
4514
+ recipe.projectDescription,
3509
4515
  null,
3510
4516
  [],
3511
4517
  null,
3512
4518
  null
3513
4519
  );
3514
4520
  await api.storage.saveEntities([projectEntity]);
3515
- const notebookId = randomUUID3();
3516
- analysis.notebookId = notebookId;
3517
- const notebookEntity = createEntity(
4521
+ const rawDataTableId = randomUUID3();
4522
+ const rawDataTable = createEntity(
3518
4523
  project.projectId,
3519
- notebookId,
3520
- "notebook",
3521
- analysis.projectName,
4524
+ rawDataTableId,
4525
+ "table",
4526
+ "Raw Data Table",
3522
4527
  null,
3523
4528
  null,
3524
4529
  [],
3525
4530
  null,
3526
4531
  null
3527
4532
  );
3528
- const projectRef = {
3529
- projectId: project.projectId,
3530
- projectBranch: "main",
3531
- entityId: project.projectId,
3532
- entityBranch: "main"
3533
- };
3534
- await api.storage.saveLinkedEntities(projectRef, "main", [notebookEntity]);
3535
- const analysisChapterId = randomUUID3();
3536
- analysis.analysisChapterId = analysisChapterId;
3537
- const foundationChapterId = randomUUID3();
3538
- const notebookRef = {
3539
- projectId: project.projectId,
3540
- projectBranch: "main",
3541
- entityId: notebookId,
3542
- entityBranch: "main"
3543
- };
3544
- await api.storage.saveLinkedEntities(notebookRef, "sections", [
3545
- createEntity(project.projectId, randomUUID3(), "text", null, null, { index: 0, text: "This notebook is an analysis of your data." }, ["introduction"], null, null),
3546
- createEntity(project.projectId, randomUUID3(), "contents", null, null, { index: 1 }, [], null, null),
3547
- createEntity(project.projectId, analysisChapterId, "chapter", "Analysis", null, { index: 2 }, ["analysis"], null, null),
3548
- createEntity(project.projectId, foundationChapterId, "chapter", "Foundation", null, { index: 3 }, ["foundation"], null, null)
3549
- ]);
3550
- const rawDataChapterId = randomUUID3();
3551
- const analysisFunctionChapterId = randomUUID3();
3552
- const foundationRef = {
3553
- projectId: project.projectId,
3554
- projectBranch: "main",
3555
- entityId: foundationChapterId,
3556
- entityBranch: "main"
3557
- };
3558
- await api.storage.saveLinkedEntities(foundationRef, "sections", [
3559
- createEntity(project.projectId, rawDataChapterId, "chapter", "Raw Data", null, { index: 0 }, ["raw-data"], null, null),
3560
- createEntity(project.projectId, analysisFunctionChapterId, "chapter", "Analysis Function", null, { index: 1 }, ["analysis-function"], null, null)
3561
- ]);
3562
- const rawDataTableId = randomUUID3();
3563
- analysis.rawDataTableId = rawDataTableId;
3564
- const rawDataRef = {
3565
- projectId: project.projectId,
3566
- projectBranch: "main",
3567
- entityId: rawDataChapterId,
3568
- entityBranch: "main"
3569
- };
3570
- await api.storage.saveLinkedEntities(rawDataRef, "sections", [
3571
- createEntity(project.projectId, rawDataTableId, "table", "Raw Data Table", null, { index: 0 }, [], null, null)
3572
- ]);
3573
- const analysisFunctionId = randomUUID3();
3574
- analysis.analysisFunctionId = analysisFunctionId;
3575
- const sourceCode = generateSourceCode(rawDataTableId, analysisChapterId, analysis.time);
3576
- const content = stringToBinary(JSON.stringify({ sourceCode }));
3577
- const funcRef = {
3578
- projectId: project.projectId,
3579
- projectBranch: "main",
3580
- entityId: analysisFunctionChapterId,
3581
- entityBranch: "main"
3582
- };
3583
- await api.storage.saveLinkedEntities(funcRef, "sections", [
3584
- createEntity(project.projectId, analysisFunctionId, "function", "Analysis Function", null, { index: 1, language: "Java" }, [], "text/plain", content)
3585
- ]);
3586
- analysis.step = "UPLOAD_DATA";
3587
- await api.admin.saveAnalysis(analysis);
4533
+ await api.storage.saveEntities([rawDataTable]);
4534
+ return { projectId: project.projectId, rawDataTableId };
3588
4535
  }
3589
- async function importData(api, analysis, file) {
4536
+ async function importData(api, projectId, rawDataTableId, file) {
3590
4537
  const ref = {
3591
- projectId: analysis.projectId,
4538
+ projectId,
3592
4539
  projectBranch: "main",
3593
- entityId: analysis.rawDataTableId,
4540
+ entityId: rawDataTableId,
3594
4541
  entityBranch: "main"
3595
4542
  };
3596
- const fileBuffer = fs5.readFileSync(file);
4543
+ const fileBuffer = fs6.readFileSync(file);
3597
4544
  const blob = new Blob([fileBuffer]);
3598
4545
  const formData = new FormData();
3599
- formData.append("content", blob, path4.basename(file));
4546
+ formData.append("content", blob, path5.basename(file));
3600
4547
  const importId = await api.storage.importTable(ref, formData, true);
3601
4548
  for (let i = 0; i < 300; i++) {
3602
4549
  await new Promise((resolve) => setTimeout(resolve, 1e3));
3603
4550
  const imp = await api.storage.getImport(ref, importId);
3604
4551
  if (imp.finished !== null) {
3605
- if (!imp.succeeded) {
3606
- throw new Error(`Import failed: ${imp.error}`);
3607
- }
3608
- break;
4552
+ if (!imp.succeeded) throw new Error(`Import failed: ${imp.error}`);
4553
+ return;
3609
4554
  }
3610
4555
  }
3611
- analysis.step = "LAUNCH_ANALYSIS";
3612
- await api.admin.saveAnalysis(analysis);
3613
- }
3614
- async function launchAnalysis(api, analysis) {
3615
- const funcRef = {
3616
- projectId: analysis.projectId,
3617
- projectBranch: "main",
3618
- entityId: analysis.analysisFunctionId,
3619
- entityBranch: "main"
3620
- };
3621
- const sourceCode = generateSourceCode(analysis.rawDataTableId, analysis.analysisChapterId, analysis.time);
3622
- const content = stringToBinary(JSON.stringify({ sourceCode }));
3623
- await api.storage.saveEntityContentBase64(funcRef, content);
3624
- const now = /* @__PURE__ */ new Date();
3625
- analysis.evaluationId = randomUUID3();
3626
- analysis.year = now.getUTCFullYear();
3627
- analysis.month = now.getUTCMonth() + 1;
3628
- analysis.day = now.getUTCDate();
3629
- analysis.hour = now.getUTCHours();
3630
- await api.evaluation.call({
3631
- evaluationId: analysis.evaluationId,
3632
- projectId: analysis.projectId,
3633
- projectBranch: "main",
3634
- functionId: analysis.analysisFunctionId,
3635
- functionBranch: "main",
3636
- targetEntityId: null,
3637
- targetEntityBranch: null,
3638
- arguments: null,
3639
- types: null,
3640
- requested: Date.now(),
3641
- provideOutputs: true,
3642
- removeFunction: false
3643
- }, true);
3644
- analysis.phase = "ANALYSIS";
3645
- analysis.started = Date.now();
3646
- await api.admin.saveAnalysis(analysis);
4556
+ throw new Error("Import did not finish within 5 minutes");
3647
4557
  }
3648
- async function monitorAnalysis(api, analysis, cmd) {
4558
+ async function monitorRun(api, runId, recipe, cmd) {
3649
4559
  const config = loadConfig();
3650
- const globalOpts = cmd.optsWithGlobals();
3651
- const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
3652
- const computationMs = parseFloat(analysis.time) * 60 * 60 * 1e3;
4560
+ const outputFormat = getOutputFormat14(cmd);
4561
+ const computationMs = parseFloat(recipe.time) * 60 * 60 * 1e3;
4562
+ const startMs = Date.now();
3653
4563
  const seenOutputIds = /* @__PURE__ */ new Set();
4564
+ let observedAnalysisId = recipe.analysisId;
3654
4565
  for (let i = 0; ; i++) {
3655
4566
  await new Promise((resolve) => setTimeout(resolve, 2e3));
4567
+ let run = null;
3656
4568
  try {
3657
- const evaluation = await api.evaluation.getEvaluation(
3658
- analysis.projectId,
3659
- "main",
3660
- analysis.analysisFunctionId,
3661
- "main",
3662
- analysis.year,
3663
- analysis.month,
3664
- analysis.day,
3665
- analysis.hour,
3666
- analysis.evaluationId,
3667
- true
3668
- );
3669
- if (!evaluation.active) {
3670
- analysis.phase = "COMPLETION";
3671
- await api.admin.saveAnalysis(analysis);
3672
- console.log();
3673
- if (evaluation.successful) {
3674
- const duration = evaluation.completed - evaluation.started;
3675
- const durationStr = formatDuration(duration);
3676
- if (outputFormat === "human") {
3677
- console.log(chalk23.green(`Analysis complete! (${durationStr})`));
3678
- if (evaluation.result) {
3679
- console.log(` Result: ${evaluation.result}`);
4569
+ const opt = await api.analysis.getRun(runId);
4570
+ run = opt.run;
4571
+ } catch {
4572
+ }
4573
+ 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}`);
3680
4583
  }
3681
- const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
3682
- console.log(` Project: ${endpoint}/lab/${analysis.projectId}/main/entities/${analysis.notebookId}/main`);
3683
- } else {
3684
- format({
3685
- status: "completed",
3686
- successful: true,
3687
- duration,
3688
- result: evaluation.result,
3689
- projectId: analysis.projectId
3690
- }, { format: outputFormat });
3691
- }
3692
- } else {
3693
- if (outputFormat === "human") {
3694
- console.log(chalk23.red("Analysis failed."));
3695
- console.log(` Error: ${evaluation.error}`);
3696
- } else {
3697
- format({
3698
- status: "failed",
3699
- error: evaluation.error,
3700
- projectId: analysis.projectId
3701
- }, { format: outputFormat });
3702
4584
  }
3703
4585
  }
3704
- return;
4586
+ } catch {
3705
4587
  }
3706
- } catch {
3707
4588
  }
3708
- try {
3709
- const outputs = await api.evaluation.getOutputs(analysis.projectId, analysis.evaluationId);
3710
- for (const out of outputs) {
3711
- if (!seenOutputIds.has(out.outputId)) {
3712
- seenOutputIds.add(out.outputId);
3713
- if (outputFormat === "human") {
3714
- console.log(` ${chalk23.dim("Output:")} ${out.output}`);
4589
+ if (isTerminalState(run.state)) {
4590
+ console.log();
4591
+ const baseStart = run.startedAt ?? run.submittedAt ?? startMs;
4592
+ const duration = (run.endedAt ?? Date.now()) - baseStart;
4593
+ const durationStr = formatDuration(duration);
4594
+ if (run.state === "COMPLETED") {
4595
+ if (outputFormat === "human") {
4596
+ 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
+ }
3715
4606
  }
4607
+ } else {
4608
+ format({
4609
+ status: "completed",
4610
+ runId,
4611
+ analysisId: observedAnalysisId,
4612
+ duration,
4613
+ projectId: recipe.projectId
4614
+ }, { format: outputFormat });
4615
+ }
4616
+ } else if (run.state === "CANCELLED") {
4617
+ if (outputFormat === "human") {
4618
+ console.log(chalk23.yellow("Analysis cancelled."));
4619
+ } else {
4620
+ format({ status: "cancelled", runId, analysisId: observedAnalysisId }, { format: outputFormat });
4621
+ }
4622
+ } else {
4623
+ if (outputFormat === "human") {
4624
+ console.log(chalk23.red("Analysis failed."));
4625
+ if (run.errorMessage) console.log(` Error: ${run.errorMessage}`);
4626
+ } else {
4627
+ format({
4628
+ status: "failed",
4629
+ runId,
4630
+ analysisId: observedAnalysisId,
4631
+ error: run.errorMessage
4632
+ }, { format: outputFormat });
3716
4633
  }
3717
4634
  }
3718
- } catch {
4635
+ return;
3719
4636
  }
3720
4637
  if (outputFormat === "human" && i % 5 === 0) {
3721
- const elapsed = Date.now() - analysis.started;
3722
- const progress = Math.min(elapsed / computationMs, 1);
4638
+ const elapsed = Date.now() - startMs;
4639
+ const progress = run.progressTotal && run.progressTotal > 0 ? (run.progressDone ?? 0) / run.progressTotal : Math.min(elapsed / computationMs, 1);
3723
4640
  const pct = Math.round(progress * 100);
3724
- const bar = "\u2588".repeat(Math.round(progress * 30)) + "\u2591".repeat(30 - Math.round(progress * 30));
3725
- process.stdout.write(`\r Analysis in progress [${bar}] ${pct}% `);
4641
+ const filled = Math.round(progress * 30);
4642
+ const bar = "\u2588".repeat(filled) + "\u2591".repeat(30 - filled);
4643
+ const stateLabel = run.state.toLowerCase().padEnd(11);
4644
+ process.stdout.write(`\r ${stateLabel} [${bar}] ${pct}% `);
3726
4645
  }
3727
4646
  }
3728
4647
  }
3729
- async function resumeAnalysis(api, analysisId, cmd) {
3730
- let analysis;
3731
- if (analysisId) {
3732
- analysis = await api.admin.getAnalysis(analysisId);
3733
- } else {
3734
- const result = await api.admin.getLastAnalysis();
3735
- if (!result.analysis) {
3736
- console.log(chalk23.dim("No previous analysis found."));
3737
- return;
3738
- }
3739
- analysis = result.analysis;
4648
+ async function listAnalyses(limit, cmd) {
4649
+ const outputFormat = getOutputFormat14(cmd);
4650
+ const api = createApiClient();
4651
+ 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, {
4661
+ format: outputFormat,
4662
+ columns: ["analysisId", "projectName", "phase", "step", "started"]
4663
+ });
4664
+ }
4665
+ async function getAnalysisDetails(analysisId, cmd) {
4666
+ const outputFormat = getOutputFormat14(cmd);
4667
+ const api = createApiClient();
4668
+ const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
4669
+ if (!result.analysis) {
4670
+ console.log(chalk23.dim("No analysis found."));
4671
+ return;
4672
+ }
4673
+ format(result.analysis, { format: outputFormat });
4674
+ }
4675
+ async function watchAnalysis(analysisId, cmd) {
4676
+ const api = createApiClient();
4677
+ const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
4678
+ if (!result.analysis) {
4679
+ console.log(chalk23.dim("No analysis found."));
4680
+ return;
3740
4681
  }
3741
- if (analysis.phase === "COMPLETION") {
3742
- console.log(chalk23.dim("Analysis already completed."));
4682
+ const recipe = result.analysis;
4683
+ if (!recipe.analysisId) {
4684
+ console.log(chalk23.dim("Analysis has no analysisId yet."));
3743
4685
  return;
3744
4686
  }
3745
- if (analysis.phase === "ANALYSIS") {
3746
- console.log(`Resuming analysis monitoring for project "${analysis.projectId}" ...`);
3747
- await monitorAnalysis(api, analysis, cmd);
3748
- } else {
3749
- console.log(`Analysis in preparation phase (step: ${analysis.step}). Cannot resume \u2014 start a new analysis.`);
4687
+ const runs = await api.analysis.getRunsForAnalysis(recipe.analysisId, 1);
4688
+ if (runs.length === 0) {
4689
+ console.log(chalk23.dim("No runs for this analysis."));
4690
+ return;
3750
4691
  }
4692
+ const latest = runs[0];
4693
+ if (isTerminalState(latest.state)) {
4694
+ console.log(chalk23.green(`Latest run already in terminal state: ${latest.state}`));
4695
+ if (recipe.projectId && recipe.notebookId) {
4696
+ const config = loadConfig();
4697
+ const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
4698
+ console.log(` Project: ${analysisUrl(recipe, endpoint)}`);
4699
+ }
4700
+ return;
4701
+ }
4702
+ console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
4703
+ await monitorRun(api, latest.runId, recipe, cmd);
3751
4704
  }
3752
- function formatDuration(ms) {
3753
- const seconds = Math.floor(ms / 1e3);
3754
- const minutes = Math.floor(seconds / 60);
3755
- const hours = Math.floor(minutes / 60);
3756
- if (hours > 0) return `${hours}h ${minutes % 60}m`;
3757
- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
3758
- return `${seconds}s`;
4705
+ async function rerunAnalysis(analysisId) {
4706
+ const api = createApiClient();
4707
+ const run = await api.analysis.rerun(analysisId);
4708
+ console.log(chalk23.green(`\u2713 Queued new run ${run.runId} for analysis ${analysisId}`));
4709
+ console.log(chalk23.dim(` State: ${run.state}`));
4710
+ 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}`));
4713
+ }
4714
+ async function openAnalysis(analysisId) {
4715
+ const api = createApiClient();
4716
+ 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)."));
4719
+ return;
4720
+ }
4721
+ const config = loadConfig();
4722
+ 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);
4726
+ }
4727
+ async function createRecipe(options, cmd) {
4728
+ const outputFormat = getOutputFormat14(cmd);
4729
+ 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 ?? "",
4738
+ 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),
4753
+ questions: parseCsv(options.questions),
4754
+ segmentKey: options.segment ?? null
4755
+ };
4756
+ const saved = await api.analysis.save(recipe);
4757
+ format(saved, { format: outputFormat });
4758
+ }
4759
+ async function updateRecipe(analysisId, options, cmd) {
4760
+ const outputFormat = getOutputFormat14(cmd);
4761
+ const api = createApiClient();
4762
+ const opt = await api.analysis.get(analysisId);
4763
+ if (!opt.analysis) {
4764
+ console.error(chalk23.red(`Analysis not found: ${analysisId}`));
4765
+ process.exit(1);
4766
+ }
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 });
4777
+ }
4778
+ async function listRuns(analysisId, count, cmd) {
4779
+ const outputFormat = getOutputFormat14(cmd);
4780
+ const api = createApiClient();
4781
+ const runs = await api.analysis.getRunsForAnalysis(analysisId, count);
4782
+ const rows = runs.map((r) => ({
4783
+ runId: r.runId,
4784
+ state: r.state,
4785
+ submittedAt: r.submittedAt ? new Date(r.submittedAt).toISOString() : "\u2014",
4786
+ startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : "\u2014",
4787
+ endedAt: r.endedAt ? new Date(r.endedAt).toISOString() : "\u2014",
4788
+ evaluationId: r.evaluationId ?? "\u2014"
4789
+ }));
4790
+ format(rows, {
4791
+ format: outputFormat,
4792
+ columns: ["runId", "state", "submittedAt", "endedAt", "evaluationId"]
4793
+ });
4794
+ }
4795
+ async function cancelRun(runId, cmd) {
4796
+ const outputFormat = getOutputFormat14(cmd);
4797
+ const api = createApiClient();
4798
+ const run = await api.analysis.cancelRun(runId);
4799
+ if (outputFormat === "human") {
4800
+ console.log(chalk23.green(`\u2713 Run ${run.runId} state: ${run.state}`));
4801
+ } else {
4802
+ format(run, { format: outputFormat });
4803
+ }
4804
+ }
4805
+ async function listPresets(cmd) {
4806
+ const outputFormat = getOutputFormat14(cmd);
4807
+ const api = createApiClient();
4808
+ const presets = await api.analysis.getPresets();
4809
+ format(presets.map((p) => ({
4810
+ presetId: p.presetId ?? "\u2014",
4811
+ name: p.name,
4812
+ targets: p.targetKeys.join(", "),
4813
+ questions: p.questions.length,
4814
+ segment: p.segmentKey ?? "\u2014",
4815
+ hours: p.time,
4816
+ budget: p.budget
4817
+ })), {
4818
+ format: outputFormat,
4819
+ columns: ["presetId", "name", "targets", "questions", "segment", "hours", "budget"]
4820
+ });
4821
+ }
4822
+ async function getPreset(presetId, cmd) {
4823
+ const outputFormat = getOutputFormat14(cmd);
4824
+ const api = createApiClient();
4825
+ const opt = await api.analysis.getPreset(presetId);
4826
+ if (!opt.preset) {
4827
+ console.log(chalk23.dim("Preset not found."));
4828
+ return;
4829
+ }
4830
+ format(opt.preset, { format: outputFormat });
4831
+ }
4832
+ async function savePreset(options, cmd) {
4833
+ const outputFormat = getOutputFormat14(cmd);
4834
+ const api = createApiClient();
4835
+ const preset = {
4836
+ presetId: options.id ?? null,
4837
+ name: options.name,
4838
+ targetKeys: parseCsv(options.targets) ?? [],
4839
+ questions: parseCsv(options.questions) ?? [],
4840
+ segmentKey: options.segment ?? null,
4841
+ time: options.hours,
4842
+ budget: options.budget
4843
+ };
4844
+ const saved = await api.analysis.savePreset(preset);
4845
+ format(saved, { format: outputFormat });
4846
+ }
4847
+ async function deletePreset(presetId) {
4848
+ const api = createApiClient();
4849
+ await api.analysis.deletePreset(presetId);
4850
+ console.log(chalk23.green(`\u2713 Deleted preset ${presetId}`));
4851
+ }
4852
+ async function listTriggers(analysisId, cmd) {
4853
+ const outputFormat = getOutputFormat14(cmd);
4854
+ const api = createApiClient();
4855
+ const triggers = await api.analysis.listTriggers(analysisId);
4856
+ format(triggers.map((t) => ({
4857
+ triggerId: t.triggerId,
4858
+ kind: t.kind,
4859
+ schedule: t.scheduleSpec,
4860
+ active: t.active,
4861
+ nextFireAt: t.nextFireAt ? new Date(t.nextFireAt).toISOString() : "\u2014"
4862
+ })), {
4863
+ format: outputFormat,
4864
+ columns: ["triggerId", "kind", "schedule", "active", "nextFireAt"]
4865
+ });
4866
+ }
4867
+ async function createTrigger(analysisId, kind, schedule, cmd) {
4868
+ const outputFormat = getOutputFormat14(cmd);
4869
+ const upper = kind.toUpperCase();
4870
+ if (upper !== "ONCE" && upper !== "CRON") {
4871
+ console.error(chalk23.red(`Invalid kind "${kind}" \u2014 must be ONCE or CRON.`));
4872
+ process.exit(1);
4873
+ }
4874
+ const api = createApiClient();
4875
+ const trigger = await api.analysis.createTrigger(analysisId, {
4876
+ kind: upper,
4877
+ scheduleSpec: schedule
4878
+ });
4879
+ format(trigger, { format: outputFormat });
4880
+ }
4881
+ async function deleteTrigger(triggerId) {
4882
+ const api = createApiClient();
4883
+ await api.analysis.deleteTrigger(triggerId);
4884
+ console.log(chalk23.green(`\u2713 Deleted trigger ${triggerId}`));
4885
+ }
4886
+ async function toggleTrigger(triggerId, active, cmd) {
4887
+ const outputFormat = getOutputFormat14(cmd);
4888
+ const lc = active.toLowerCase();
4889
+ if (lc !== "true" && lc !== "false") {
4890
+ console.error(chalk23.red(`Invalid active value "${active}" \u2014 must be true or false.`));
4891
+ process.exit(1);
4892
+ }
4893
+ const api = createApiClient();
4894
+ const trigger = await api.analysis.updateTrigger(triggerId, { active: lc === "true" });
4895
+ format(trigger, { format: outputFormat });
4896
+ }
4897
+ function registerAnalyzeCommand(program) {
4898
+ 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) => {
4900
+ try {
4901
+ if (!file) {
4902
+ analyze.help();
4903
+ return;
4904
+ }
4905
+ await runAnalysis(file, options, cmd);
4906
+ } catch (error) {
4907
+ handleError(error);
4908
+ }
4909
+ });
4910
+ analyze.command("list").description("List recent analyses").option("--limit <n>", "Number of analyses to list", "20").action(async (options, cmd) => {
4911
+ try {
4912
+ await listAnalyses(parseInt(options.limit, 10), cmd);
4913
+ } catch (error) {
4914
+ handleError(error);
4915
+ }
4916
+ });
4917
+ analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
4918
+ try {
4919
+ await getAnalysisDetails(id, cmd);
4920
+ } catch (error) {
4921
+ handleError(error);
4922
+ }
4923
+ });
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) => {
4925
+ try {
4926
+ await watchAnalysis(id, cmd);
4927
+ } catch (error) {
4928
+ handleError(error);
4929
+ }
4930
+ });
4931
+ analyze.command("open").description("Open an analysis project in your browser").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id) => {
4932
+ try {
4933
+ await openAnalysis(id);
4934
+ } catch (error) {
4935
+ handleError(error);
4936
+ }
4937
+ });
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) => {
4939
+ try {
4940
+ await rerunAnalysis(id);
4941
+ } catch (error) {
4942
+ handleError(error);
4943
+ }
4944
+ });
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) => {
4946
+ try {
4947
+ await createRecipe(options, cmd);
4948
+ } catch (error) {
4949
+ handleError(error);
4950
+ }
4951
+ });
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) => {
4953
+ try {
4954
+ await updateRecipe(id, options, cmd);
4955
+ } catch (error) {
4956
+ handleError(error);
4957
+ }
4958
+ });
4959
+ analyze.command("runs").description("List recent runs for an analysis (newest first)").argument("<id>", "Analysis ID").option("--count <n>", "Max number of runs to show", "20").action(async (id, options, cmd) => {
4960
+ try {
4961
+ await listRuns(id, parseInt(options.count, 10), cmd);
4962
+ } catch (error) {
4963
+ handleError(error);
4964
+ }
4965
+ });
4966
+ analyze.command("cancel").description("Cancel a non-terminal run (idempotent on terminal runs)").argument("<runId>", "Run ID to cancel").action(async (runId, _options, cmd) => {
4967
+ try {
4968
+ await cancelRun(runId, cmd);
4969
+ } catch (error) {
4970
+ handleError(error);
4971
+ }
4972
+ });
4973
+ const presets = analyze.command("presets").description("Manage saved analysis presets");
4974
+ presets.command("list").description("List your analysis presets").action(async (_options, cmd) => {
4975
+ try {
4976
+ await listPresets(cmd);
4977
+ } catch (error) {
4978
+ handleError(error);
4979
+ }
4980
+ });
4981
+ presets.command("get").description("Show details of a preset").argument("<id>", "Preset ID").action(async (id, _options, cmd) => {
4982
+ try {
4983
+ await getPreset(id, cmd);
4984
+ } catch (error) {
4985
+ handleError(error);
4986
+ }
4987
+ });
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) => {
4989
+ try {
4990
+ await savePreset(options, cmd);
4991
+ } catch (error) {
4992
+ handleError(error);
4993
+ }
4994
+ });
4995
+ presets.command("delete").description("Delete a preset").argument("<id>", "Preset ID").action(async (id) => {
4996
+ try {
4997
+ await deletePreset(id);
4998
+ } catch (error) {
4999
+ handleError(error);
5000
+ }
5001
+ });
5002
+ const triggers = analyze.command("triggers").description("Manage scheduled triggers on an analysis");
5003
+ triggers.command("list").description("List triggers for an analysis").argument("<analysisId>", "Analysis ID").action(async (analysisId, _options, cmd) => {
5004
+ try {
5005
+ await listTriggers(analysisId, cmd);
5006
+ } catch (error) {
5007
+ handleError(error);
5008
+ }
5009
+ });
5010
+ triggers.command("create").description("Create a trigger (ONCE: ISO-8601 timestamp; CRON: cron expression)").argument("<analysisId>", "Analysis ID").requiredOption("--kind <kind>", "ONCE or CRON").requiredOption("--schedule <spec>", "ISO-8601 timestamp (ONCE) or cron expression (CRON)").action(async (analysisId, options, cmd) => {
5011
+ try {
5012
+ await createTrigger(analysisId, options.kind, options.schedule, cmd);
5013
+ } catch (error) {
5014
+ handleError(error);
5015
+ }
5016
+ });
5017
+ triggers.command("delete").description("Delete a trigger").argument("<triggerId>", "Trigger ID").action(async (triggerId) => {
5018
+ try {
5019
+ await deleteTrigger(triggerId);
5020
+ } catch (error) {
5021
+ handleError(error);
5022
+ }
5023
+ });
5024
+ triggers.command("toggle").description("Activate or deactivate a trigger").argument("<triggerId>", "Trigger ID").requiredOption("--active <bool>", "true or false").action(async (triggerId, options, cmd) => {
5025
+ try {
5026
+ await toggleTrigger(triggerId, options.active, cmd);
5027
+ } catch (error) {
5028
+ handleError(error);
5029
+ }
5030
+ });
3759
5031
  }
3760
5032
 
3761
5033
  // src/commands/completion/index.ts
@@ -4011,10 +5283,406 @@ function registerCompletionCommand(program) {
4011
5283
  });
4012
5284
  }
4013
5285
 
5286
+ // src/commands/whoami/index.ts
5287
+ import chalk24 from "chalk";
5288
+ function registerWhoamiCommand(program) {
5289
+ program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
5290
+ try {
5291
+ const config = loadConfig();
5292
+ const globalOpts = cmd.optsWithGlobals();
5293
+ const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
5294
+ const api = createApiClient();
5295
+ const user = await api.admin.getMyUser();
5296
+ if (outputFormat === "human") {
5297
+ console.log(chalk24.bold(user.name) + chalk24.dim(` <${user.email}>`));
5298
+ console.log(chalk24.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
5299
+ } else {
5300
+ format(user, { format: outputFormat });
5301
+ }
5302
+ } catch (error) {
5303
+ handleError(error);
5304
+ }
5305
+ });
5306
+ }
5307
+
5308
+ // src/commands/utilization/index.ts
5309
+ import chalk25 from "chalk";
5310
+ function getOutputFormat15(cmd) {
5311
+ const config = loadConfig();
5312
+ const globalOpts = cmd.optsWithGlobals();
5313
+ return globalOpts.output ?? config.defaults.output ?? "human";
5314
+ }
5315
+ function printUtilizationHuman(u, label) {
5316
+ const when = u.day !== null && u.day !== void 0 ? `${u.year}-${String(u.month).padStart(2, "0")}-${String(u.day).padStart(2, "0")}` : `${u.year}-${String(u.month).padStart(2, "0")}`;
5317
+ if (label) {
5318
+ console.log(chalk25.bold(label) + " " + chalk25.dim(when));
5319
+ } else {
5320
+ console.log(chalk25.bold(when));
5321
+ }
5322
+ if (u.types.length === 0) {
5323
+ console.log(chalk25.dim(" (no usage)"));
5324
+ return;
5325
+ }
5326
+ for (const t of u.types) {
5327
+ console.log(
5328
+ ` ${t.type.padEnd(24)} ${chalk25.cyan(String(t.quantity).padStart(10))} ${chalk25.dim("credits:")} ${t.credits.toFixed(2)}`
5329
+ );
5330
+ }
5331
+ const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
5332
+ console.log(chalk25.bold(` Total credits: ${total.toFixed(2)}`));
5333
+ }
5334
+ function registerUtilizationCommand(program) {
5335
+ const util = program.command("utilization").description("Show credit utilization");
5336
+ util.command("actual", { isDefault: true }).description("Show current utilization (default subcommand)").action(async (_options, cmd) => {
5337
+ try {
5338
+ const outputFormat = getOutputFormat15(cmd);
5339
+ const api = createApiClient();
5340
+ const utilization = await api.admin.getActualUtilization();
5341
+ if (outputFormat === "human") {
5342
+ printUtilizationHuman(utilization, "Current utilization");
5343
+ } else {
5344
+ format(utilization, { format: outputFormat });
5345
+ }
5346
+ } catch (error) {
5347
+ handleError(error);
5348
+ }
5349
+ });
5350
+ util.command("history").description("Show utilization history").action(async (_options, cmd) => {
5351
+ try {
5352
+ const outputFormat = getOutputFormat15(cmd);
5353
+ const api = createApiClient();
5354
+ const history = await api.admin.getUtilizationHistory();
5355
+ if (outputFormat === "human") {
5356
+ if (history.length === 0) {
5357
+ console.log(chalk25.dim("No usage recorded."));
5358
+ return;
5359
+ }
5360
+ for (const u of history) {
5361
+ printUtilizationHuman(u);
5362
+ console.log();
5363
+ }
5364
+ } else {
5365
+ format(history, { format: outputFormat });
5366
+ }
5367
+ } catch (error) {
5368
+ handleError(error);
5369
+ }
5370
+ });
5371
+ }
5372
+
5373
+ // src/commands/entity-branch/index.ts
5374
+ import chalk26 from "chalk";
5375
+ function getOutputFormat16(cmd) {
5376
+ const config = loadConfig();
5377
+ const globalOpts = cmd.optsWithGlobals();
5378
+ return globalOpts.output ?? config.defaults.output ?? "human";
5379
+ }
5380
+ function getOverrides9(cmd) {
5381
+ const opts = cmd.optsWithGlobals();
5382
+ return { project: opts.project, branch: opts.branch };
5383
+ }
5384
+ function registerEntityBranchCommands(program) {
5385
+ const eb = program.command("entity-branch").description("Manage entity branches (parallel versions of a single entity)");
5386
+ eb.command("list").description("List branches of an entity").argument("<ref>", "Entity reference (projectId/branch/entityId)").action(async (ref, _options, cmd) => {
5387
+ try {
5388
+ const outputFormat = getOutputFormat16(cmd);
5389
+ const overrides = getOverrides9(cmd);
5390
+ const resolved = parseEntityReference(ref, overrides);
5391
+ const api = createApiClient();
5392
+ const branches = await api.storage.getEntityBranches(
5393
+ resolved.projectId,
5394
+ resolved.projectBranch,
5395
+ resolved.entityId
5396
+ );
5397
+ if (outputFormat === "json") {
5398
+ format(branches, { format: outputFormat });
5399
+ } else {
5400
+ for (const b of branches) console.log(b);
5401
+ }
5402
+ } catch (error) {
5403
+ handleError(error);
5404
+ }
5405
+ });
5406
+ eb.command("create").description("Create a new branch of an entity from an existing branch").argument("<ref>", "Source entity reference (projectId/branch/entityId/sourceBranch)").argument("<targetBranch>", "New branch name").action(async (ref, targetBranch, _options, cmd) => {
5407
+ try {
5408
+ const overrides = getOverrides9(cmd);
5409
+ const resolved = parseEntityReference(ref, overrides);
5410
+ const api = createApiClient();
5411
+ await api.storage.createEntityBranch({
5412
+ projectId: resolved.projectId,
5413
+ projectBranch: resolved.projectBranch,
5414
+ entityId: resolved.entityId,
5415
+ sourceEntityBranch: resolved.entityBranch,
5416
+ targetEntityBranch: targetBranch
5417
+ });
5418
+ console.log(chalk26.green(`Entity branch "${targetBranch}" created from "${resolved.entityBranch}".`));
5419
+ } catch (error) {
5420
+ handleError(error);
5421
+ }
5422
+ });
5423
+ }
5424
+
5425
+ // src/commands/subscription/index.ts
5426
+ function getOutputFormat17(cmd) {
5427
+ const config = loadConfig();
5428
+ const globalOpts = cmd.optsWithGlobals();
5429
+ return globalOpts.output ?? config.defaults.output ?? "human";
5430
+ }
5431
+ function registerSubscriptionCommand(program) {
5432
+ const sub = program.command("subscription").description("View subscription info");
5433
+ sub.command("current", { isDefault: true }).description("Show the current subscription").action(async (_options, cmd) => {
5434
+ try {
5435
+ const api = createApiClient();
5436
+ const s = await api.admin.getCurrentSubscription();
5437
+ format(s, { format: getOutputFormat17(cmd) });
5438
+ } catch (error) {
5439
+ handleError(error);
5440
+ }
5441
+ });
5442
+ sub.command("next").description("Show the next (upcoming) subscription").action(async (_options, cmd) => {
5443
+ try {
5444
+ const api = createApiClient();
5445
+ const s = await api.admin.getNextSubscription();
5446
+ format(s, { format: getOutputFormat17(cmd) });
5447
+ } catch (error) {
5448
+ handleError(error);
5449
+ }
5450
+ });
5451
+ sub.command("plans").description("Show subscription plans").argument("<subscriptionToken>", "Subscription token").action(async (subscriptionToken, _options, cmd) => {
5452
+ try {
5453
+ const api = createApiClient();
5454
+ const plans = await api.admin.getSubscriptionPlans(subscriptionToken);
5455
+ format(plans, { format: getOutputFormat17(cmd) });
5456
+ } catch (error) {
5457
+ handleError(error);
5458
+ }
5459
+ });
5460
+ }
5461
+
5462
+ // src/commands/invoice/index.ts
5463
+ import chalk27 from "chalk";
5464
+ import * as fs7 from "fs";
5465
+ function getOutputFormat18(cmd) {
5466
+ const config = loadConfig();
5467
+ const globalOpts = cmd.optsWithGlobals();
5468
+ return globalOpts.output ?? config.defaults.output ?? "human";
5469
+ }
5470
+ function registerInvoiceCommand(program) {
5471
+ const invoice = program.command("invoice").description("View and download invoices");
5472
+ invoice.command("list").description("List your invoices").action(async (_options, cmd) => {
5473
+ try {
5474
+ const api = createApiClient();
5475
+ const invoices = await api.admin.getInvoices();
5476
+ format(invoices, {
5477
+ format: getOutputFormat18(cmd),
5478
+ columns: ["invoiceNumber", "issued", "periodFrom", "periodTo", "total", "status"]
5479
+ });
5480
+ } catch (error) {
5481
+ handleError(error);
5482
+ }
5483
+ });
5484
+ invoice.command("download").description("Download an invoice document").argument("<invoiceNumber>", "Invoice number").argument("<fileName>", "File name of the document").option("--out <path>", "Output file path (defaults to <fileName>)").action(async (invoiceNumber, fileName, options) => {
5485
+ try {
5486
+ const api = createApiClient();
5487
+ const response = await api.admin.downloadInvoice(invoiceNumber, fileName);
5488
+ const buffer = Buffer.from(await response.arrayBuffer());
5489
+ const outPath = options.out ?? fileName;
5490
+ fs7.writeFileSync(outPath, buffer);
5491
+ console.log(chalk27.green(`Invoice saved to ${outPath}`));
5492
+ } catch (error) {
5493
+ handleError(error);
5494
+ }
5495
+ });
5496
+ }
5497
+
5498
+ // src/commands/shell/index.ts
5499
+ import chalk28 from "chalk";
5500
+ import * as fs8 from "fs";
5501
+ import * as os3 from "os";
5502
+ import * as path6 from "path";
5503
+ import { spawn as spawn3 } from "child_process";
5504
+ import { randomUUID as randomUUID4 } from "crypto";
5505
+ function extensionFor2(language) {
5506
+ const l = language.toLowerCase();
5507
+ if (l === "java") return "java";
5508
+ if (l === "javascript" || l === "js") return "js";
5509
+ if (l === "kotlin") return "kt";
5510
+ if (l === "python") return "py";
5511
+ if (l === "scala") return "scala";
5512
+ return "txt";
5513
+ }
5514
+ async function openInEditor(initial, ext) {
5515
+ const tmpFile = path6.join(os3.tmpdir(), `diafunc-shell-${randomUUID4()}.${ext}`);
5516
+ fs8.writeFileSync(tmpFile, initial);
5517
+ const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
5518
+ await new Promise((resolve, reject) => {
5519
+ const child = spawn3(editor, [tmpFile], { stdio: "inherit" });
5520
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`Editor exited with ${code}`)));
5521
+ child.on("error", reject);
5522
+ });
5523
+ const content = fs8.readFileSync(tmpFile, "utf-8");
5524
+ fs8.unlinkSync(tmpFile);
5525
+ return content;
5526
+ }
5527
+ function utcNowParts() {
5528
+ const d = /* @__PURE__ */ new Date();
5529
+ return {
5530
+ year: d.getUTCFullYear(),
5531
+ month: d.getUTCMonth() + 1,
5532
+ day: d.getUTCDate(),
5533
+ hour: d.getUTCHours()
5534
+ };
5535
+ }
5536
+ async function evaluate(api, fnRef, language, sourceCode) {
5537
+ const entity = buildFunctionEntity({
5538
+ projectId: fnRef.projectId,
5539
+ projectBranch: fnRef.projectBranch,
5540
+ entityId: fnRef.entityId,
5541
+ entityBranch: fnRef.entityBranch,
5542
+ name: fnRef.entityId,
5543
+ language,
5544
+ sourceCode
5545
+ });
5546
+ await api.storage.saveEntities([entity]);
5547
+ const evaluationId = randomUUID4();
5548
+ const nowParts = utcNowParts();
5549
+ const result = await api.evaluation.call({
5550
+ evaluationId,
5551
+ projectId: fnRef.projectId,
5552
+ projectBranch: fnRef.projectBranch,
5553
+ functionId: fnRef.entityId,
5554
+ functionBranch: fnRef.entityBranch,
5555
+ targetEntityId: null,
5556
+ targetEntityBranch: null,
5557
+ arguments: null,
5558
+ types: null,
5559
+ requested: Date.now(),
5560
+ provideOutputs: true,
5561
+ removeFunction: true
5562
+ }, false);
5563
+ if (result.outputs?.length) {
5564
+ for (const out of result.outputs) {
5565
+ console.log(chalk28.dim(` [${out.type}]`) + " " + out.output);
5566
+ }
5567
+ }
5568
+ if (result.successful) {
5569
+ if (result.result) {
5570
+ console.log(chalk28.green("=> ") + result.result);
5571
+ } else {
5572
+ console.log(chalk28.dim("=> (no value)"));
5573
+ }
5574
+ const duration = result.completed - result.started;
5575
+ console.log(chalk28.dim(` [${duration}ms \xB7 ${evaluationId}]`));
5576
+ } else {
5577
+ console.log(chalk28.red("error: ") + result.error);
5578
+ if (result.lineNumber > 0) {
5579
+ console.log(chalk28.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
5580
+ }
5581
+ }
5582
+ }
5583
+ function registerShellCommand(program) {
5584
+ program.command("shell").description("Interactive REPL for function code evaluation").option("--function <ref>", "Function entity reference to use as scratch (required)").option("--language <lang>", "Source language", "JavaScript").action(async (options, cmd) => {
5585
+ try {
5586
+ if (!options.function) {
5587
+ console.error(chalk28.red("Missing --function <ref>."));
5588
+ console.error(chalk28.dim("Pass an existing or new function entity reference to use as the shell target."));
5589
+ console.error(chalk28.dim("Example: diafunc shell --function my-project/main/scratch/main --language JavaScript"));
5590
+ process.exit(1);
5591
+ }
5592
+ const config = loadConfig();
5593
+ const globalOpts = cmd.optsWithGlobals();
5594
+ const fnRef = parseEntityReference(options.function, {
5595
+ project: globalOpts.project,
5596
+ branch: globalOpts.branch
5597
+ });
5598
+ const api = createApiClient();
5599
+ const { input: promptInput } = await import("@inquirer/prompts");
5600
+ console.log(chalk28.bold("Diafunc shell") + chalk28.dim(` \xB7 function ${fnRef.entityId} \xB7 ${options.language}`));
5601
+ console.log(chalk28.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
5602
+ console.log(chalk28.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
5603
+ console.log();
5604
+ let language = options.language;
5605
+ for (; ; ) {
5606
+ let line;
5607
+ try {
5608
+ line = await promptInput({ message: chalk28.cyan.bold(`${language} >`) });
5609
+ } catch {
5610
+ console.log();
5611
+ return;
5612
+ }
5613
+ const trimmed = line.trim();
5614
+ if (!trimmed) continue;
5615
+ if (trimmed.startsWith("/")) {
5616
+ const [cmd2, ...rest] = trimmed.slice(1).split(/\s+/);
5617
+ const arg = rest.join(" ");
5618
+ switch (cmd2) {
5619
+ case "quit":
5620
+ case "exit":
5621
+ case "q":
5622
+ return;
5623
+ case "help":
5624
+ case "h":
5625
+ case "?":
5626
+ console.log(chalk28.dim(" /edit open $EDITOR for multi-line code"));
5627
+ console.log(chalk28.dim(" /file <path> evaluate the contents of a file"));
5628
+ console.log(chalk28.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
5629
+ console.log(chalk28.dim(" /quit exit the shell"));
5630
+ continue;
5631
+ case "lang":
5632
+ if (arg) language = arg;
5633
+ console.log(chalk28.dim(`Language: ${language}`));
5634
+ continue;
5635
+ case "edit": {
5636
+ const sourceCode = await openInEditor("", extensionFor2(language));
5637
+ if (!sourceCode.trim()) {
5638
+ console.log(chalk28.dim("(empty \u2014 not evaluated)"));
5639
+ continue;
5640
+ }
5641
+ try {
5642
+ await evaluate(api, fnRef, language, sourceCode);
5643
+ } catch (e) {
5644
+ console.error(chalk28.red(e.message));
5645
+ }
5646
+ continue;
5647
+ }
5648
+ case "file": {
5649
+ if (!arg) {
5650
+ console.log(chalk28.dim("usage: /file <path>"));
5651
+ continue;
5652
+ }
5653
+ if (!fs8.existsSync(arg)) {
5654
+ console.log(chalk28.red(`file not found: ${arg}`));
5655
+ continue;
5656
+ }
5657
+ const sourceCode = fs8.readFileSync(arg, "utf-8");
5658
+ try {
5659
+ await evaluate(api, fnRef, language, sourceCode);
5660
+ } catch (e) {
5661
+ console.error(chalk28.red(e.message));
5662
+ }
5663
+ continue;
5664
+ }
5665
+ default:
5666
+ console.log(chalk28.dim(`Unknown command: /${cmd2}. Try /help.`));
5667
+ continue;
5668
+ }
5669
+ }
5670
+ try {
5671
+ await evaluate(api, fnRef, language, trimmed);
5672
+ } catch (e) {
5673
+ console.error(chalk28.red(e.message));
5674
+ }
5675
+ }
5676
+ } catch (error) {
5677
+ handleError(error);
5678
+ }
5679
+ });
5680
+ }
5681
+
4014
5682
  // src/index.ts
4015
5683
  function createProgram() {
4016
5684
  const program = new Command();
4017
- program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version("0.1.0").option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").hook("preAction", (thisCommand) => {
5685
+ 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").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").hook("preAction", (thisCommand) => {
4018
5686
  const opts = thisCommand.optsWithGlobals();
4019
5687
  if (opts.dryRun) {
4020
5688
  setDryRun(true);
@@ -4038,10 +5706,17 @@ function createProgram() {
4038
5706
  registerStatusCommands(program);
4039
5707
  registerAnalyzeCommand(program);
4040
5708
  registerCompletionCommand(program);
5709
+ registerWhoamiCommand(program);
5710
+ registerUtilizationCommand(program);
5711
+ registerEntityBranchCommands(program);
5712
+ registerSubscriptionCommand(program);
5713
+ registerInvoiceCommand(program);
5714
+ registerShellCommand(program);
4041
5715
  return program;
4042
5716
  }
4043
5717
 
4044
5718
  export {
5719
+ package_default,
4045
5720
  createProgram
4046
5721
  };
4047
- //# sourceMappingURL=chunk-63FZ6EJP.js.map
5722
+ //# sourceMappingURL=chunk-PEFGWCVH.js.map