@inworld/cli 0.2.16 → 0.3.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
  // src/index.ts
5
- import chalk6 from "chalk";
5
+ import chalk5 from "chalk";
6
6
  import { Command as Command22 } from "commander";
7
7
 
8
8
  // src/commands/auth/login_command.ts
@@ -11,179 +11,13 @@ import { Command } from "commander";
11
11
  import * as readline3 from "readline";
12
12
  import { promisify } from "util";
13
13
 
14
- // src/auth/manager.ts
15
- import Conf from "conf";
16
- import { createHash } from "crypto";
17
-
18
- // proto/generated/portal/fetch.pb.ts
19
- var b64 = new Array(64);
20
- var s64 = new Array(123);
21
- for (let i = 0; i < 64; )
22
- s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
23
- function b64Encode(buffer, start, end) {
24
- let parts = null;
25
- const chunk = [];
26
- let i = 0, j = 0, t;
27
- while (start < end) {
28
- const b = buffer[start++];
29
- switch (j) {
30
- case 0:
31
- chunk[i++] = b64[b >> 2];
32
- t = (b & 3) << 4;
33
- j = 1;
34
- break;
35
- case 1:
36
- chunk[i++] = b64[t | b >> 4];
37
- t = (b & 15) << 2;
38
- j = 2;
39
- break;
40
- case 2:
41
- chunk[i++] = b64[t | b >> 6];
42
- chunk[i++] = b64[b & 63];
43
- j = 0;
44
- break;
45
- }
46
- if (i > 8191) {
47
- (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
48
- i = 0;
49
- }
50
- }
51
- if (j) {
52
- chunk[i++] = b64[t];
53
- chunk[i++] = 61;
54
- if (j === 1) chunk[i++] = 61;
55
- }
56
- if (parts) {
57
- if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
58
- return parts.join("");
59
- }
60
- return String.fromCharCode.apply(String, chunk.slice(0, i));
61
- }
62
- function replacer(key, value) {
63
- if (value && value.constructor === Uint8Array) {
64
- return b64Encode(value, 0, value.length);
65
- }
66
- return value;
67
- }
68
- function fetchReq(path6, init) {
69
- const { pathPrefix, ...req } = init || {};
70
- const url = pathPrefix ? `${pathPrefix}${path6}` : path6;
71
- return fetch(url, req).then(
72
- (r) => r.json().then((body) => {
73
- if (!r.ok) {
74
- throw body;
75
- }
76
- return body;
77
- })
78
- );
79
- }
80
- function isPlainObject(value) {
81
- const isObject = Object.prototype.toString.call(value).slice(8, -1) === "Object";
82
- const isObjLike = value !== null && isObject;
83
- if (!isObjLike || !isObject) {
84
- return false;
85
- }
86
- const proto = Object.getPrototypeOf(value);
87
- const hasObjectConstructor = typeof proto === "object" && proto.constructor === Object.prototype.constructor;
88
- return hasObjectConstructor;
89
- }
90
- function isPrimitive(value) {
91
- return ["string", "number", "boolean"].some((t) => typeof value === t);
92
- }
93
- function isZeroValuePrimitive(value) {
94
- return value === false || value === 0 || value === "";
95
- }
96
- function flattenRequestPayload(requestPayload, path6 = "") {
97
- return Object.keys(requestPayload).reduce((acc, key) => {
98
- const value = requestPayload[key];
99
- const newPath = path6 ? [path6, key].join(".") : key;
100
- const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
101
- const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
102
- let objectToMerge = {};
103
- if (isPlainObject(value)) {
104
- objectToMerge = flattenRequestPayload(value, newPath);
105
- } else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
106
- objectToMerge = { [newPath]: value };
107
- }
108
- return { ...acc, ...objectToMerge };
109
- }, {});
110
- }
111
- function renderURLSearchParams(requestPayload, urlPathParams = []) {
112
- const flattenedRequestPayload = flattenRequestPayload(requestPayload);
113
- const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
114
- (acc, key) => {
115
- const value = flattenedRequestPayload[key];
116
- if (urlPathParams.find((f) => f === key)) {
117
- return acc;
118
- }
119
- return Array.isArray(value) ? [...acc, ...value.map((m) => [key, m.toString()])] : acc = [...acc, [key, value.toString()]];
120
- },
121
- []
122
- );
123
- return new URLSearchParams(urlSearchParams).toString();
124
- }
125
-
126
- // proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts
127
- var Users = class {
128
- static GenerateTokenUser(req, initReq) {
129
- return fetchReq(
130
- `/v1alpha/users:generateTokenUser`,
131
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
132
- );
133
- }
134
- static LinkAccountUser(req, initReq) {
135
- return fetchReq(
136
- `/v1alpha/${req["name"]}:link`,
137
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
138
- );
139
- }
140
- static GetUser(req, initReq) {
141
- return fetchReq(
142
- `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameusers"])}`,
143
- { ...initReq, method: "GET" }
144
- );
145
- }
146
- static UpdateUser(req, initReq) {
147
- return fetchReq(
148
- `/v1alpha/${req["user"]["name"]}`,
149
- {
150
- ...initReq,
151
- method: "PATCH",
152
- body: JSON.stringify(req["user"], replacer)
153
- }
154
- );
155
- }
156
- static AcceptTos(req, initReq) {
157
- return fetchReq(
158
- `/v1alpha/${req["user"]}:acceptTos`,
159
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
160
- );
161
- }
162
- static DeleteUser(req, initReq) {
163
- return fetchReq(
164
- `/v1alpha/${req["name"]}`,
165
- { ...initReq, method: "DELETE" }
166
- );
167
- }
168
- static ResolveAzureMarketplaceOfferToken(req, initReq) {
169
- return fetchReq(
170
- `/v1alpha/users:resolveAzureMarketplaceOfferToken?${renderURLSearchParams(req, [])}`,
171
- { ...initReq, method: "GET" }
172
- );
173
- }
174
- static ActivateAzureMarketplaceSubscription(req, initReq) {
175
- return fetchReq(`/v1alpha/users:activateAzureMarketplaceSubscription`, {
176
- ...initReq,
177
- method: "POST",
178
- body: JSON.stringify(req, replacer)
179
- });
180
- }
181
- };
14
+ // src/auth/callback_server.ts
15
+ import * as http from "http";
182
16
 
183
17
  // package.json
184
18
  var package_default = {
185
19
  name: "@inworld/cli",
186
- version: "0.2.16",
20
+ version: "0.3.0-rc.5",
187
21
  type: "module",
188
22
  main: "dist/index.js",
189
23
  bin: {
@@ -198,8 +32,7 @@ var package_default = {
198
32
  dev: "tsx src/index.ts"
199
33
  },
200
34
  files: [
201
- "dist/**/*",
202
- "src/templates/**/*"
35
+ "dist/**/*"
203
36
  ],
204
37
  author: "Inworld AI",
205
38
  license: "MIT",
@@ -215,6 +48,7 @@ var package_default = {
215
48
  },
216
49
  dependencies: {
217
50
  "@zowe/secrets-for-zowe-sdk": "^8.27.0",
51
+ "adm-zip": "^0.5.16",
218
52
  archiver: "^7.0.1",
219
53
  chalk: "^5.3.0",
220
54
  commander: "^12.0.0",
@@ -257,7 +91,24 @@ var INWORLD_CLI_AUTH_CALLBACK_PORT = parseInt(
257
91
  10
258
92
  );
259
93
  var MIXPANEL_TOKEN = process.env.INWORLD_MIXPANEL_TOKEN || "2cf13116e9701343ac27ddc452adfbbc";
260
- var RUNTIME_VERSION = "0.6.4";
94
+ var resolveTemplatesMetadataUrl = () => {
95
+ if (process.env.INWORLD_TEMPLATES_METADATA_URL) {
96
+ return process.env.INWORLD_TEMPLATES_METADATA_URL;
97
+ }
98
+ const env = (process.env.INWORLD_ENV || "").toUpperCase();
99
+ switch (env) {
100
+ case "DEV":
101
+ return "https://storage.googleapis.com/assets-inworld-ai/files/dev/templates-info.json";
102
+ case "STAGE":
103
+ return "https://storage.googleapis.com/assets-inworld-ai/files/stage/templates-info.json";
104
+ case "PROD":
105
+ return "https://storage.googleapis.com/assets-inworld-ai/files/prod/templates-info.json";
106
+ default:
107
+ return "https://storage.googleapis.com/assets-inworld-ai/files/prod/templates-info.json";
108
+ }
109
+ };
110
+ var TEMPLATES_METADATA_URL = resolveTemplatesMetadataUrl();
111
+ var RUNTIME_VERSION = "0.8.0";
261
112
  var CLI_VERSION = package_default.version;
262
113
 
263
114
  // src/utils/ui.ts
@@ -308,7 +159,9 @@ function printBox(lines, options) {
308
159
  const color = options?.color || "yellow";
309
160
  const padding = options?.padding ?? 2;
310
161
  const stripAnsi = (str) => str.replace(/\x1b\[[0-9;]*m/g, "");
311
- const maxContentWidth = Math.max(...lines.map((line) => stripAnsi(line).length));
162
+ const maxContentWidth = Math.max(
163
+ ...lines.map((line) => stripAnsi(line).length)
164
+ );
312
165
  const boxWidth = maxContentWidth + padding * 2;
313
166
  const horizontalLine = "\u2500".repeat(boxWidth);
314
167
  const emptyLine = " ".repeat(boxWidth);
@@ -336,350 +189,25 @@ function workspaceLink(workspaceId) {
336
189
  return link(`${PLATFORM_URL}/v2/workspaces/${workspaceId}`);
337
190
  }
338
191
 
339
- // src/auth/manager.ts
340
- var AuthManager = class _AuthManager {
341
- static SERVICE_NAME = "InworldCLI";
342
- static ACCOUNT_NAME = "default";
343
- static CONFIG_KEY = "credentials";
344
- conf = null;
345
- keyringModule = null;
346
- keyringLoadAttempted = false;
347
- keyringAvailable = false;
348
- constructor() {
349
- }
350
- /**
351
- * Lazily loads the keyring module with fallback if unavailable
352
- */
353
- async getKeyring() {
354
- if (this.keyringLoadAttempted) {
355
- return this.keyringModule;
356
- }
357
- this.keyringLoadAttempted = true;
358
- try {
359
- const module = await import("@zowe/secrets-for-zowe-sdk");
360
- this.keyringModule = module.keyring;
361
- return this.keyringModule;
362
- } catch (error) {
363
- print(`\u26A0\uFE0F Failed to load keychain: ${error.message}`);
364
- this.keyringModule = null;
365
- this.keyringAvailable = false;
366
- return null;
367
- }
368
- }
369
- /**
370
- * Lazily initializes the Conf instance with encrypted storage
371
- */
372
- async getConf() {
373
- if (!this.conf) {
374
- const encryptionKey = await this.generateEncryptionKey();
375
- this.conf = new Conf({
376
- projectName: "inworld-cli",
377
- encryptionKey,
378
- schema: {
379
- credentials: {
380
- type: "object",
381
- properties: {
382
- refreshToken: { type: "string" },
383
- email: { type: "string" },
384
- inworldToken: { type: "string" },
385
- expiresAt: { type: "number" },
386
- workspace: { type: "string" }
387
- }
388
- }
389
- }
390
- });
391
- }
392
- return this.conf;
393
- }
394
- /**
395
- * Generates a machine-specific encryption key for the configuration file
396
- */
397
- async generateEncryptionKey() {
398
- const platform = process.platform;
399
- const arch = process.arch;
400
- const hostname = (await import("os")).hostname();
401
- const username = (await import("os")).userInfo().username;
402
- const data = `${platform}-${arch}-${hostname}-${username}-inworld-cli`;
403
- return createHash("sha256").update(data).digest("hex").substring(0, 32);
404
- }
405
- /**
406
- * Saves credentials securely
407
- */
408
- async saveCredentials(credentials) {
409
- try {
410
- const keyring = await this.getKeyring();
411
- if (keyring) {
412
- try {
413
- const credentialsJsonString = JSON.stringify(credentials);
414
- await keyring.setPassword(
415
- _AuthManager.SERVICE_NAME,
416
- _AuthManager.ACCOUNT_NAME,
417
- credentialsJsonString
418
- );
419
- return;
420
- } catch (_keychainError) {
421
- print(
422
- "\u26A0 Could not save to system keychain, using encrypted file storage"
423
- );
424
- }
425
- }
426
- const conf = await this.getConf();
427
- conf.set(_AuthManager.CONFIG_KEY, credentials);
428
- success("\u2713 Credentials saved to encrypted configuration");
429
- } catch (error) {
430
- throw new Error(`Failed to save credentials: ${error}`);
431
- }
432
- }
433
- /**
434
- * Retrieves stored credentials
435
- */
436
- async getCredentials() {
437
- try {
438
- const keyring = await this.getKeyring();
439
- if (keyring) {
440
- try {
441
- const credentialsJson = await keyring.getPassword(
442
- _AuthManager.SERVICE_NAME,
443
- _AuthManager.ACCOUNT_NAME
444
- );
445
- if (credentialsJson) {
446
- return JSON.parse(credentialsJson);
447
- }
448
- } catch (_keychainError) {
449
- }
450
- }
451
- const conf = await this.getConf();
452
- const credentials = conf.get(_AuthManager.CONFIG_KEY);
453
- return credentials || null;
454
- } catch (error) {
455
- throw new Error(`Failed to retrieve credentials: ${error}`);
456
- }
457
- }
458
- async getApiKey() {
459
- const credentials = await this.getCredentials();
460
- return credentials?.apiKey || null;
461
- }
462
- async getWorkspace() {
463
- const credentials = await this.getCredentials();
464
- return credentials?.workspace || null;
465
- }
466
- /**
467
- * Updates the Inworld token and its expiration
468
- */
469
- async updateInworldToken(token, expirationTime) {
470
- const credentials = await this.getCredentials();
471
- if (!credentials) {
472
- throw new Error("No credentials found to update");
473
- }
474
- credentials.inworldToken = token;
475
- credentials.expiresAt = new Date(expirationTime).getTime();
476
- await this.saveCredentials(credentials);
477
- }
478
- async updateWorkspaceAndApiKey(workspace, apiKey) {
479
- const credentials = await this.getCredentials();
480
- if (!credentials) {
481
- throw new Error("No credentials found to update");
482
- }
483
- credentials.workspace = workspace;
484
- credentials.apiKey = apiKey;
485
- await this.saveCredentials(credentials);
486
- }
487
- /**
488
- * Checks if the stored Inworld token is still valid
489
- */
490
- async isTokenValid() {
491
- const credentials = await this.getCredentials();
492
- if (!credentials || !credentials.inworldToken) {
493
- return false;
494
- }
495
- if (credentials.expiresAt) {
496
- return Date.now() < credentials.expiresAt;
497
- }
498
- return true;
499
- }
500
- /**
501
- * Generates an Inworld token from a Firebase ID token
502
- *
503
- * @param firebaseToken The Firebase ID token
504
- * @returns The generated Inworld token or null if generation fails
505
- */
506
- async generateInworldToken(firebaseToken) {
507
- try {
508
- const tokenResponse = await Users.GenerateTokenUser(
509
- {
510
- type: "AUTH_TYPE_FIREBASE" /* AUTH_TYPE_FIREBASE */,
511
- token: firebaseToken
512
- },
513
- {
514
- headers: {
515
- Authorization: `Bearer ${firebaseToken}`,
516
- "Grpc-Metadata-X-Authorization-Bearer-Type": "firebase"
517
- },
518
- pathPrefix: PLATFORM_URL
519
- }
520
- );
521
- if (tokenResponse?.token) {
522
- return {
523
- token: tokenResponse.token,
524
- expiresAt: tokenResponse.expirationTime
525
- };
526
- }
527
- return null;
528
- } catch (error) {
529
- printError("Failed to generate Inworld token:");
530
- console.error(error);
531
- return null;
532
- }
533
- }
534
- /**
535
- * Refreshes the Inworld token using the stored refresh token
536
- */
537
- async refreshToken() {
538
- const credentials = await this.getCredentials();
539
- if (!credentials || !credentials.refreshToken) {
540
- return null;
541
- }
542
- try {
543
- const firebaseApiKey = FIREBASE_API_KEY;
544
- if (!firebaseApiKey) {
545
- throw new Error("FIREBASE_API_KEY environment variable not set");
546
- }
547
- const tokenFetchResponse = await fetch(
548
- `https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
549
- {
550
- method: "POST",
551
- body: new URLSearchParams({
552
- grant_type: "refresh_token",
553
- refresh_token: credentials.refreshToken
554
- })
555
- }
556
- );
557
- const tokenResponse = await tokenFetchResponse.json();
558
- if (tokenResponse?.id_token) {
559
- const inworldTokenResult = await this.generateInworldToken(
560
- tokenResponse.id_token
561
- );
562
- if (inworldTokenResult) {
563
- await this.updateInworldToken(
564
- inworldTokenResult.token,
565
- inworldTokenResult.expiresAt
566
- );
567
- return inworldTokenResult.token;
568
- }
569
- return null;
570
- }
571
- return null;
572
- } catch (error) {
573
- printError("Failed to refresh token:");
574
- console.error(error);
575
- return null;
576
- }
577
- }
578
- /**
579
- * Gets a valid Inworld token, refreshing if necessary
580
- */
581
- async getValidToken() {
582
- if (await this.isTokenValid()) {
583
- const credentials = await this.getCredentials();
584
- return credentials?.inworldToken || null;
585
- }
586
- return await this.refreshToken();
587
- }
588
- /**
589
- * Authenticates and saves credentials from Firebase auth data
590
- * This is typically called after successful Firebase authentication
591
- *
592
- * @param firebaseToken The Firebase ID token
593
- * @param refreshToken The Firebase refresh token
594
- * @param email The user's email address
595
- * @returns true if successful, false otherwise
596
- */
597
- async authenticateAndSaveCredentials(firebaseToken, refreshToken, email, workspace, env) {
598
- try {
599
- const inworldTokenResult = await this.generateInworldToken(firebaseToken);
600
- if (!inworldTokenResult) {
601
- printError("Failed to generate Inworld token");
602
- return false;
603
- }
604
- const expiresAt = new Date(inworldTokenResult.expiresAt).getTime();
605
- const credentials = {
606
- refreshToken,
607
- email,
608
- inworldToken: inworldTokenResult.token,
609
- workspace,
610
- expiresAt,
611
- env
612
- };
613
- await this.saveCredentials(credentials);
614
- return true;
615
- } catch (error) {
616
- printError("Failed to authenticate and save credentials:");
617
- console.error(error);
618
- return false;
619
- }
620
- }
621
- /**
622
- * Clears all stored credentials
623
- */
624
- async clearCredentials() {
625
- try {
626
- const keyring = await this.getKeyring();
627
- if (keyring) {
628
- try {
629
- await keyring.deletePassword(
630
- _AuthManager.SERVICE_NAME,
631
- _AuthManager.ACCOUNT_NAME
632
- );
633
- } catch (_keychainError) {
634
- }
635
- }
636
- const conf = await this.getConf();
637
- conf.delete(_AuthManager.CONFIG_KEY);
638
- success("\u2713 Credentials cleared");
639
- } catch (error) {
640
- throw new Error(`Failed to clear credentials: ${error}`);
641
- }
642
- }
643
- /**
644
- * Checks if user is authenticated
645
- */
646
- async isAuthenticated() {
647
- const credentials = await this.getCredentials();
648
- if (credentials?.env && credentials?.env !== INWORLD_ENV) {
649
- print(
650
- `Warning: Currently saved credentials might not match current Inworld CLI environment.
651
-
652
- Current Inworld CLI environment is ${INWORLD_ENV}
653
- Environment of current credentials is ${credentials?.env}
654
-
655
- You can run "inworld login --force" to login with the correct environment.`
656
- );
657
- }
658
- return credentials !== null && !!credentials.refreshToken;
659
- }
660
- };
661
- var authManager = new AuthManager();
662
-
663
- // src/auth/callback_server.ts
664
- import * as http from "http";
665
- async function createCallbackServer(options = {}) {
666
- const {
667
- port = 8085,
668
- allowedOrigins = ["http://localhost:3001", "https://cli.inworld.ai"],
669
- firebaseApiKey = FIREBASE_API_KEY
670
- } = options;
671
- return new Promise((resolve2, reject) => {
672
- const httpServer = http.createServer(
673
- {
674
- keepAlive: false
675
- },
676
- (req, res) => {
677
- const origin = req.headers.origin;
678
- if (origin && allowedOrigins.includes(origin)) {
679
- res.setHeader("Access-Control-Allow-Origin", origin);
680
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
681
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
682
- res.setHeader("Access-Control-Max-Age", "86400");
192
+ // src/auth/callback_server.ts
193
+ async function createCallbackServer(options = {}) {
194
+ const {
195
+ port = 8085,
196
+ allowedOrigins = ["http://localhost:3001", "https://cli.inworld.ai"],
197
+ firebaseApiKey = FIREBASE_API_KEY
198
+ } = options;
199
+ return new Promise((resolve2, reject) => {
200
+ const httpServer = http.createServer(
201
+ {
202
+ keepAlive: false
203
+ },
204
+ (req, res) => {
205
+ const origin = req.headers.origin;
206
+ if (origin && allowedOrigins.includes(origin)) {
207
+ res.setHeader("Access-Control-Allow-Origin", origin);
208
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
209
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
210
+ res.setHeader("Access-Control-Max-Age", "86400");
683
211
  }
684
212
  if (req.url?.startsWith("/callback") && req.method === "OPTIONS") {
685
213
  res.writeHead(204);
@@ -761,153 +289,521 @@ async function createCallbackServer(options = {}) {
761
289
  res.writeHead(404, { "Content-Type": "application/json" });
762
290
  res.end(JSON.stringify({ error: "Not found" }));
763
291
  }
764
- }
765
- );
766
- httpServer.on("error", (error) => {
767
- reject(error);
768
- });
769
- httpServer.listen(port, "localhost");
770
- });
771
- }
772
- function stopCallbackServer(server) {
773
- return new Promise((resolve2, reject) => {
774
- server.close((err) => {
775
- if (err) {
776
- reject(err);
777
- } else {
778
- resolve2();
779
- }
780
- });
781
- });
782
- }
783
-
784
- // src/services/workspace_service.ts
785
- import chalk2 from "chalk";
786
-
787
- // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
788
- var ApiKeys = class {
789
- static ListApiKeys(req, initReq) {
790
- return fetchReq(
791
- `/v1alpha/${req["parent"]}/apikeys?${renderURLSearchParams(req, ["parent"])}`,
792
- { ...initReq, method: "GET" }
793
- );
292
+ }
293
+ );
294
+ httpServer.on("error", (error) => {
295
+ reject(error);
296
+ });
297
+ httpServer.listen(port, "localhost");
298
+ });
299
+ }
300
+ function stopCallbackServer(server) {
301
+ return new Promise((resolve2, reject) => {
302
+ server.close((err) => {
303
+ if (err) {
304
+ reject(err);
305
+ } else {
306
+ resolve2();
307
+ }
308
+ });
309
+ });
310
+ }
311
+
312
+ // src/auth/manager.ts
313
+ import Conf from "conf";
314
+ import { createHash } from "crypto";
315
+
316
+ // proto/generated/portal/fetch.pb.ts
317
+ var b64 = new Array(64);
318
+ var s64 = new Array(123);
319
+ for (let i = 0; i < 64; )
320
+ s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
321
+ function b64Encode(buffer, start, end) {
322
+ let parts = null;
323
+ const chunk = [];
324
+ let i = 0, j = 0, t;
325
+ while (start < end) {
326
+ const b = buffer[start++];
327
+ switch (j) {
328
+ case 0:
329
+ chunk[i++] = b64[b >> 2];
330
+ t = (b & 3) << 4;
331
+ j = 1;
332
+ break;
333
+ case 1:
334
+ chunk[i++] = b64[t | b >> 4];
335
+ t = (b & 15) << 2;
336
+ j = 2;
337
+ break;
338
+ case 2:
339
+ chunk[i++] = b64[t | b >> 6];
340
+ chunk[i++] = b64[b & 63];
341
+ j = 0;
342
+ break;
343
+ }
344
+ if (i > 8191) {
345
+ (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
346
+ i = 0;
347
+ }
348
+ }
349
+ if (j) {
350
+ chunk[i++] = b64[t];
351
+ chunk[i++] = 61;
352
+ if (j === 1) chunk[i++] = 61;
353
+ }
354
+ if (parts) {
355
+ if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
356
+ return parts.join("");
357
+ }
358
+ return String.fromCharCode.apply(String, chunk.slice(0, i));
359
+ }
360
+ function replacer(key, value) {
361
+ if (value && value.constructor === Uint8Array) {
362
+ return b64Encode(value, 0, value.length);
363
+ }
364
+ return value;
365
+ }
366
+ function fetchReq(path7, init) {
367
+ const { pathPrefix, ...req } = init || {};
368
+ const url = pathPrefix ? `${pathPrefix}${path7}` : path7;
369
+ return fetch(url, req).then(
370
+ (r) => r.json().then((body) => {
371
+ if (!r.ok) {
372
+ throw body;
373
+ }
374
+ return body;
375
+ })
376
+ );
377
+ }
378
+ function isPlainObject(value) {
379
+ const isObject = Object.prototype.toString.call(value).slice(8, -1) === "Object";
380
+ const isObjLike = value !== null && isObject;
381
+ if (!isObjLike || !isObject) {
382
+ return false;
383
+ }
384
+ const proto = Object.getPrototypeOf(value);
385
+ const hasObjectConstructor = typeof proto === "object" && proto.constructor === Object.prototype.constructor;
386
+ return hasObjectConstructor;
387
+ }
388
+ function isPrimitive(value) {
389
+ return ["string", "number", "boolean"].some((t) => typeof value === t);
390
+ }
391
+ function isZeroValuePrimitive(value) {
392
+ return value === false || value === 0 || value === "";
393
+ }
394
+ function flattenRequestPayload(requestPayload, path7 = "") {
395
+ return Object.keys(requestPayload).reduce((acc, key) => {
396
+ const value = requestPayload[key];
397
+ const newPath = path7 ? [path7, key].join(".") : key;
398
+ const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
399
+ const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
400
+ let objectToMerge = {};
401
+ if (isPlainObject(value)) {
402
+ objectToMerge = flattenRequestPayload(value, newPath);
403
+ } else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
404
+ objectToMerge = { [newPath]: value };
405
+ }
406
+ return { ...acc, ...objectToMerge };
407
+ }, {});
408
+ }
409
+ function renderURLSearchParams(requestPayload, urlPathParams = []) {
410
+ const flattenedRequestPayload = flattenRequestPayload(requestPayload);
411
+ const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
412
+ (acc, key) => {
413
+ const value = flattenedRequestPayload[key];
414
+ if (urlPathParams.find((f) => f === key)) {
415
+ return acc;
416
+ }
417
+ return Array.isArray(value) ? [...acc, ...value.map((m) => [key, m.toString()])] : acc = [...acc, [key, value.toString()]];
418
+ },
419
+ []
420
+ );
421
+ return new URLSearchParams(urlSearchParams).toString();
422
+ }
423
+
424
+ // proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts
425
+ var Users = class {
426
+ static GenerateTokenUser(req, initReq) {
427
+ return fetchReq(
428
+ `/v1alpha/users:generateTokenUser`,
429
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
430
+ );
431
+ }
432
+ static LinkAccountUser(req, initReq) {
433
+ return fetchReq(
434
+ `/v1alpha/${req["name"]}:link`,
435
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
436
+ );
437
+ }
438
+ static GetUser(req, initReq) {
439
+ return fetchReq(
440
+ `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameusers"])}`,
441
+ { ...initReq, method: "GET" }
442
+ );
443
+ }
444
+ static UpdateUser(req, initReq) {
445
+ return fetchReq(
446
+ `/v1alpha/${req["user"]["name"]}`,
447
+ {
448
+ ...initReq,
449
+ method: "PATCH",
450
+ body: JSON.stringify(req["user"], replacer)
451
+ }
452
+ );
453
+ }
454
+ static AcceptTos(req, initReq) {
455
+ return fetchReq(
456
+ `/v1alpha/${req["user"]}:acceptTos`,
457
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
458
+ );
459
+ }
460
+ static DeleteUser(req, initReq) {
461
+ return fetchReq(
462
+ `/v1alpha/${req["name"]}`,
463
+ { ...initReq, method: "DELETE" }
464
+ );
465
+ }
466
+ static ResolveAzureMarketplaceOfferToken(req, initReq) {
467
+ return fetchReq(
468
+ `/v1alpha/users:resolveAzureMarketplaceOfferToken?${renderURLSearchParams(req, [])}`,
469
+ { ...initReq, method: "GET" }
470
+ );
471
+ }
472
+ static ActivateAzureMarketplaceSubscription(req, initReq) {
473
+ return fetchReq(`/v1alpha/users:activateAzureMarketplaceSubscription`, {
474
+ ...initReq,
475
+ method: "POST",
476
+ body: JSON.stringify(req, replacer)
477
+ });
478
+ }
479
+ };
480
+
481
+ // src/auth/manager.ts
482
+ var AuthManager = class _AuthManager {
483
+ static SERVICE_NAME = "InworldCLI";
484
+ static ACCOUNT_NAME = "default";
485
+ static CONFIG_KEY = "credentials";
486
+ conf = null;
487
+ keyringModule = null;
488
+ keyringLoadAttempted = false;
489
+ keyringAvailable = false;
490
+ constructor() {
491
+ }
492
+ /**
493
+ * Lazily loads the keyring module with fallback if unavailable
494
+ */
495
+ async getKeyring() {
496
+ if (this.keyringLoadAttempted) {
497
+ return this.keyringModule;
498
+ }
499
+ this.keyringLoadAttempted = true;
500
+ try {
501
+ const module = await import("@zowe/secrets-for-zowe-sdk");
502
+ this.keyringModule = module.keyring;
503
+ return this.keyringModule;
504
+ } catch (error) {
505
+ print(`\u26A0\uFE0F Failed to load keychain: ${error.message}`);
506
+ this.keyringModule = null;
507
+ this.keyringAvailable = false;
508
+ return null;
509
+ }
510
+ }
511
+ /**
512
+ * Lazily initializes the Conf instance with encrypted storage
513
+ */
514
+ async getConf() {
515
+ if (!this.conf) {
516
+ const encryptionKey = await this.generateEncryptionKey();
517
+ this.conf = new Conf({
518
+ projectName: "inworld-cli",
519
+ encryptionKey,
520
+ schema: {
521
+ credentials: {
522
+ type: "object",
523
+ properties: {
524
+ refreshToken: { type: "string" },
525
+ email: { type: "string" },
526
+ inworldToken: { type: "string" },
527
+ expiresAt: { type: "number" },
528
+ workspace: { type: "string" }
529
+ }
530
+ }
531
+ }
532
+ });
533
+ }
534
+ return this.conf;
794
535
  }
795
- static SuspendApiKey(req, initReq) {
796
- return fetchReq(
797
- `/v1alpha/${req["name"]}:suspend`,
798
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
799
- );
536
+ /**
537
+ * Generates a machine-specific encryption key for the configuration file
538
+ */
539
+ async generateEncryptionKey() {
540
+ const platform = process.platform;
541
+ const arch = process.arch;
542
+ const hostname = (await import("os")).hostname();
543
+ const username = (await import("os")).userInfo().username;
544
+ const data = `${platform}-${arch}-${hostname}-${username}-inworld-cli`;
545
+ return createHash("sha256").update(data).digest("hex").substring(0, 32);
800
546
  }
801
- static ActivateApiKey(req, initReq) {
802
- return fetchReq(
803
- `/v1alpha/${req["name"]}:activate`,
804
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
805
- );
547
+ /**
548
+ * Saves credentials securely
549
+ */
550
+ async saveCredentials(credentials) {
551
+ try {
552
+ const keyring = await this.getKeyring();
553
+ if (keyring) {
554
+ try {
555
+ const credentialsJsonString = JSON.stringify(credentials);
556
+ await keyring.setPassword(
557
+ _AuthManager.SERVICE_NAME,
558
+ _AuthManager.ACCOUNT_NAME,
559
+ credentialsJsonString
560
+ );
561
+ return;
562
+ } catch (_keychainError) {
563
+ print(
564
+ "\u26A0 Could not save to system keychain, using encrypted file storage"
565
+ );
566
+ }
567
+ }
568
+ const conf = await this.getConf();
569
+ conf.set(_AuthManager.CONFIG_KEY, credentials);
570
+ success("\u2713 Credentials saved to encrypted configuration");
571
+ } catch (error) {
572
+ throw new Error(`Failed to save credentials: ${error}`);
573
+ }
806
574
  }
807
- static DeleteApiKey(req, initReq) {
808
- return fetchReq(
809
- `/v1alpha/${req["name"]}`,
810
- { ...initReq, method: "DELETE" }
811
- );
575
+ /**
576
+ * Retrieves stored credentials
577
+ */
578
+ async getCredentials() {
579
+ try {
580
+ const keyring = await this.getKeyring();
581
+ if (keyring) {
582
+ try {
583
+ const credentialsJson = await keyring.getPassword(
584
+ _AuthManager.SERVICE_NAME,
585
+ _AuthManager.ACCOUNT_NAME
586
+ );
587
+ if (credentialsJson) {
588
+ return JSON.parse(credentialsJson);
589
+ }
590
+ } catch (_keychainError) {
591
+ }
592
+ }
593
+ const conf = await this.getConf();
594
+ const credentials = conf.get(_AuthManager.CONFIG_KEY);
595
+ return credentials || null;
596
+ } catch (error) {
597
+ throw new Error(`Failed to retrieve credentials: ${error}`);
598
+ }
812
599
  }
813
- static GenerateApiKey(req, initReq) {
814
- return fetchReq(
815
- `/v1alpha/${req["parent"]}/apikey:generate`,
816
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
817
- );
600
+ async getApiKey() {
601
+ const credentials = await this.getCredentials();
602
+ return credentials?.apiKey || null;
818
603
  }
819
- static ListAuthScopes(req, initReq) {
820
- return fetchReq(
821
- `/v1alpha/${req["parent"]}/auth-scopes?${renderURLSearchParams(req, ["parent"])}`,
822
- { ...initReq, method: "GET" }
823
- );
604
+ async getWorkspace() {
605
+ const credentials = await this.getCredentials();
606
+ return credentials?.workspace || null;
824
607
  }
825
- };
826
-
827
- // proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.ts
828
- var Workspaces = class {
829
- static GetWorkspace(req, initReq) {
830
- return fetchReq(
831
- `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameworkspaces"])}`,
832
- { ...initReq, method: "GET" }
833
- );
608
+ /**
609
+ * Updates the Inworld token and its expiration
610
+ */
611
+ async updateInworldToken(token, expirationTime) {
612
+ const credentials = await this.getCredentials();
613
+ if (!credentials) {
614
+ throw new Error("No credentials found to update");
615
+ }
616
+ credentials.inworldToken = token;
617
+ credentials.expiresAt = new Date(expirationTime).getTime();
618
+ await this.saveCredentials(credentials);
834
619
  }
835
- static ListWorkspaces(req, initReq) {
836
- return fetchReq(
837
- `/v1alpha/workspaces?${renderURLSearchParams(req, [])}`,
838
- { ...initReq, method: "GET" }
839
- );
620
+ async updateWorkspaceAndApiKey(workspace, apiKey) {
621
+ const credentials = await this.getCredentials();
622
+ if (!credentials) {
623
+ throw new Error("No credentials found to update");
624
+ }
625
+ credentials.workspace = workspace;
626
+ credentials.apiKey = apiKey;
627
+ await this.saveCredentials(credentials);
840
628
  }
841
- static UpdateWorkspace(req, initReq) {
842
- return fetchReq(
843
- `/v1alpha/${req["workspace"]["name"]}`,
844
- {
845
- ...initReq,
846
- method: "PATCH",
847
- body: JSON.stringify(req["workspace"], replacer)
629
+ /**
630
+ * Checks if the stored Inworld token is still valid
631
+ */
632
+ async isTokenValid() {
633
+ const credentials = await this.getCredentials();
634
+ if (!credentials || !credentials.inworldToken) {
635
+ return false;
636
+ }
637
+ if (credentials.expiresAt) {
638
+ return Date.now() < credentials.expiresAt;
639
+ }
640
+ return true;
641
+ }
642
+ /**
643
+ * Generates an Inworld token from a Firebase ID token
644
+ *
645
+ * @param firebaseToken The Firebase ID token
646
+ * @returns The generated Inworld token or null if generation fails
647
+ */
648
+ async generateInworldToken(firebaseToken) {
649
+ try {
650
+ const tokenResponse = await Users.GenerateTokenUser(
651
+ {
652
+ type: "AUTH_TYPE_FIREBASE" /* AUTH_TYPE_FIREBASE */,
653
+ token: firebaseToken
654
+ },
655
+ {
656
+ headers: {
657
+ Authorization: `Bearer ${firebaseToken}`,
658
+ "Grpc-Metadata-X-Authorization-Bearer-Type": "firebase"
659
+ },
660
+ pathPrefix: PLATFORM_URL
661
+ }
662
+ );
663
+ if (tokenResponse?.token) {
664
+ return {
665
+ token: tokenResponse.token,
666
+ expiresAt: tokenResponse.expirationTime
667
+ };
848
668
  }
849
- );
669
+ return null;
670
+ } catch (error) {
671
+ printError("Failed to generate Inworld token:");
672
+ console.error(error);
673
+ return null;
674
+ }
850
675
  }
851
- static CreateWorkspace(req, initReq) {
852
- return fetchReq(
853
- `/v1alpha/workspaces`,
854
- {
855
- ...initReq,
856
- method: "POST",
857
- body: JSON.stringify(req["workspace"], replacer)
676
+ /**
677
+ * Refreshes the Inworld token using the stored refresh token
678
+ */
679
+ async refreshToken() {
680
+ const credentials = await this.getCredentials();
681
+ if (!credentials || !credentials.refreshToken) {
682
+ return null;
683
+ }
684
+ try {
685
+ const firebaseApiKey = FIREBASE_API_KEY;
686
+ if (!firebaseApiKey) {
687
+ throw new Error("FIREBASE_API_KEY environment variable not set");
688
+ }
689
+ const tokenFetchResponse = await fetch(
690
+ `https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
691
+ {
692
+ method: "POST",
693
+ body: new URLSearchParams({
694
+ grant_type: "refresh_token",
695
+ refresh_token: credentials.refreshToken
696
+ })
697
+ }
698
+ );
699
+ const tokenResponse = await tokenFetchResponse.json();
700
+ if (tokenResponse?.id_token) {
701
+ const inworldTokenResult = await this.generateInworldToken(
702
+ tokenResponse.id_token
703
+ );
704
+ if (inworldTokenResult) {
705
+ await this.updateInworldToken(
706
+ inworldTokenResult.token,
707
+ inworldTokenResult.expiresAt
708
+ );
709
+ return inworldTokenResult.token;
710
+ }
711
+ return null;
858
712
  }
859
- );
860
- }
861
- static DeleteWorkspace(req, initReq) {
862
- return fetchReq(
863
- `/v1alpha/${req["name"]}`,
864
- { ...initReq, method: "DELETE" }
865
- );
866
- }
867
- static CloneWorkspace(req, initReq) {
868
- return fetchReq(
869
- `/v1alpha/${req["name"]}:clone`,
870
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
871
- );
872
- }
873
- static ShareWorkspace(req, initReq) {
874
- return fetchReq(
875
- `/v1alpha/${req["name"]}:share`,
876
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
877
- );
878
- }
879
- static generateResourceName(req, initReq) {
880
- return fetchReq(`/v1alpha/${req["workspace"]}:generateResourceName`, {
881
- ...initReq,
882
- method: "POST",
883
- body: JSON.stringify(req, replacer)
884
- });
713
+ return null;
714
+ } catch (error) {
715
+ printError("Failed to refresh token:");
716
+ console.error(error);
717
+ return null;
718
+ }
885
719
  }
886
- static GetWorkspaceShareInfo(req, initReq) {
887
- return fetchReq(
888
- `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
889
- { ...initReq, method: "GET" }
890
- );
720
+ /**
721
+ * Gets a valid Inworld token, refreshing if necessary
722
+ */
723
+ async getValidToken() {
724
+ if (await this.isTokenValid()) {
725
+ const credentials = await this.getCredentials();
726
+ return credentials?.inworldToken || null;
727
+ }
728
+ return await this.refreshToken();
891
729
  }
892
- static GetWorkspaceLimitInfo(req, initReq) {
893
- return fetchReq(
894
- `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
895
- { ...initReq, method: "GET" }
896
- );
730
+ /**
731
+ * Authenticates and saves credentials from Firebase auth data
732
+ * This is typically called after successful Firebase authentication
733
+ *
734
+ * @param firebaseToken The Firebase ID token
735
+ * @param refreshToken The Firebase refresh token
736
+ * @param email The user's email address
737
+ * @returns true if successful, false otherwise
738
+ */
739
+ async authenticateAndSaveCredentials(firebaseToken, refreshToken, email, workspace, env) {
740
+ try {
741
+ const inworldTokenResult = await this.generateInworldToken(firebaseToken);
742
+ if (!inworldTokenResult) {
743
+ printError("Failed to generate Inworld token");
744
+ return false;
745
+ }
746
+ const expiresAt = new Date(inworldTokenResult.expiresAt).getTime();
747
+ const credentials = {
748
+ refreshToken,
749
+ email,
750
+ inworldToken: inworldTokenResult.token,
751
+ workspace,
752
+ expiresAt,
753
+ env
754
+ };
755
+ await this.saveCredentials(credentials);
756
+ return true;
757
+ } catch (error) {
758
+ printError("Failed to authenticate and save credentials:");
759
+ console.error(error);
760
+ return false;
761
+ }
897
762
  }
898
- static RemainWorkspaceLimitInfo(req, initReq) {
899
- return fetchReq(
900
- `/v1alpha/${req["name"]}:remain?${renderURLSearchParams(req, ["name"])}`,
901
- { ...initReq, method: "GET" }
902
- );
763
+ /**
764
+ * Clears all stored credentials
765
+ */
766
+ async clearCredentials() {
767
+ try {
768
+ const keyring = await this.getKeyring();
769
+ if (keyring) {
770
+ try {
771
+ await keyring.deletePassword(
772
+ _AuthManager.SERVICE_NAME,
773
+ _AuthManager.ACCOUNT_NAME
774
+ );
775
+ } catch (_keychainError) {
776
+ }
777
+ }
778
+ const conf = await this.getConf();
779
+ conf.delete(_AuthManager.CONFIG_KEY);
780
+ success("\u2713 Credentials cleared");
781
+ } catch (error) {
782
+ throw new Error(`Failed to clear credentials: ${error}`);
783
+ }
903
784
  }
904
- static SendImpressionEvent(req, initReq) {
905
- return fetchReq(
906
- `/v1alpha/${req["name"]}:impression`,
907
- { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
908
- );
785
+ /**
786
+ * Checks if user is authenticated
787
+ */
788
+ async isAuthenticated() {
789
+ const credentials = await this.getCredentials();
790
+ if (credentials?.env && credentials?.env !== INWORLD_ENV) {
791
+ print(
792
+ `Warning: Currently saved credentials might not match current Inworld CLI environment.
793
+
794
+ Current Inworld CLI environment is ${INWORLD_ENV}
795
+ Environment of current credentials is ${credentials?.env}
796
+
797
+ You can run "inworld login --force" to login with the correct environment.`
798
+ );
799
+ }
800
+ return credentials !== null && !!credentials.refreshToken;
909
801
  }
910
802
  };
803
+ var authManager = new AuthManager();
804
+
805
+ // src/services/workspace_service.ts
806
+ import chalk2 from "chalk";
911
807
 
912
808
  // src/utils/array.ts
913
809
  function isArrayOfType(arr, typeGuard) {
@@ -1166,18 +1062,143 @@ var authenticatedInworldRequest = async (pb, req, inworldToken, signal) => {
1166
1062
  requireAuth();
1167
1063
  inworldToken = await authManager.getValidToken() || "";
1168
1064
  }
1169
- if (inworldToken) {
1170
- const request = {
1171
- ...{
1172
- headers: {
1173
- Authorization: `Bearer ${inworldToken}`,
1174
- "Grpc-Metadata-X-Authorization-Bearer-Type": "inworld"
1175
- }
1176
- },
1177
- pathPrefix: PLATFORM_URL,
1178
- signal
1179
- };
1180
- return pb(req, request);
1065
+ if (inworldToken) {
1066
+ const request = {
1067
+ ...{
1068
+ headers: {
1069
+ Authorization: `Bearer ${inworldToken}`,
1070
+ "Grpc-Metadata-X-Authorization-Bearer-Type": "inworld"
1071
+ }
1072
+ },
1073
+ pathPrefix: PLATFORM_URL,
1074
+ signal
1075
+ };
1076
+ return pb(req, request);
1077
+ }
1078
+ };
1079
+
1080
+ // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
1081
+ var ApiKeys = class {
1082
+ static ListApiKeys(req, initReq) {
1083
+ return fetchReq(
1084
+ `/v1alpha/${req["parent"]}/apikeys?${renderURLSearchParams(req, ["parent"])}`,
1085
+ { ...initReq, method: "GET" }
1086
+ );
1087
+ }
1088
+ static SuspendApiKey(req, initReq) {
1089
+ return fetchReq(
1090
+ `/v1alpha/${req["name"]}:suspend`,
1091
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1092
+ );
1093
+ }
1094
+ static ActivateApiKey(req, initReq) {
1095
+ return fetchReq(
1096
+ `/v1alpha/${req["name"]}:activate`,
1097
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1098
+ );
1099
+ }
1100
+ static DeleteApiKey(req, initReq) {
1101
+ return fetchReq(
1102
+ `/v1alpha/${req["name"]}`,
1103
+ { ...initReq, method: "DELETE" }
1104
+ );
1105
+ }
1106
+ static GenerateApiKey(req, initReq) {
1107
+ return fetchReq(
1108
+ `/v1alpha/${req["parent"]}/apikey:generate`,
1109
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1110
+ );
1111
+ }
1112
+ static ListAuthScopes(req, initReq) {
1113
+ return fetchReq(
1114
+ `/v1alpha/${req["parent"]}/auth-scopes?${renderURLSearchParams(req, ["parent"])}`,
1115
+ { ...initReq, method: "GET" }
1116
+ );
1117
+ }
1118
+ };
1119
+
1120
+ // proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.ts
1121
+ var Workspaces = class {
1122
+ static GetWorkspace(req, initReq) {
1123
+ return fetchReq(
1124
+ `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameworkspaces"])}`,
1125
+ { ...initReq, method: "GET" }
1126
+ );
1127
+ }
1128
+ static ListWorkspaces(req, initReq) {
1129
+ return fetchReq(
1130
+ `/v1alpha/workspaces?${renderURLSearchParams(req, [])}`,
1131
+ { ...initReq, method: "GET" }
1132
+ );
1133
+ }
1134
+ static UpdateWorkspace(req, initReq) {
1135
+ return fetchReq(
1136
+ `/v1alpha/${req["workspace"]["name"]}`,
1137
+ {
1138
+ ...initReq,
1139
+ method: "PATCH",
1140
+ body: JSON.stringify(req["workspace"], replacer)
1141
+ }
1142
+ );
1143
+ }
1144
+ static CreateWorkspace(req, initReq) {
1145
+ return fetchReq(
1146
+ `/v1alpha/workspaces`,
1147
+ {
1148
+ ...initReq,
1149
+ method: "POST",
1150
+ body: JSON.stringify(req["workspace"], replacer)
1151
+ }
1152
+ );
1153
+ }
1154
+ static DeleteWorkspace(req, initReq) {
1155
+ return fetchReq(
1156
+ `/v1alpha/${req["name"]}`,
1157
+ { ...initReq, method: "DELETE" }
1158
+ );
1159
+ }
1160
+ static CloneWorkspace(req, initReq) {
1161
+ return fetchReq(
1162
+ `/v1alpha/${req["name"]}:clone`,
1163
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1164
+ );
1165
+ }
1166
+ static ShareWorkspace(req, initReq) {
1167
+ return fetchReq(
1168
+ `/v1alpha/${req["name"]}:share`,
1169
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1170
+ );
1171
+ }
1172
+ static generateResourceName(req, initReq) {
1173
+ return fetchReq(`/v1alpha/${req["workspace"]}:generateResourceName`, {
1174
+ ...initReq,
1175
+ method: "POST",
1176
+ body: JSON.stringify(req, replacer)
1177
+ });
1178
+ }
1179
+ static GetWorkspaceShareInfo(req, initReq) {
1180
+ return fetchReq(
1181
+ `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
1182
+ { ...initReq, method: "GET" }
1183
+ );
1184
+ }
1185
+ static GetWorkspaceLimitInfo(req, initReq) {
1186
+ return fetchReq(
1187
+ `/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
1188
+ { ...initReq, method: "GET" }
1189
+ );
1190
+ }
1191
+ static RemainWorkspaceLimitInfo(req, initReq) {
1192
+ return fetchReq(
1193
+ `/v1alpha/${req["name"]}:remain?${renderURLSearchParams(req, ["name"])}`,
1194
+ { ...initReq, method: "GET" }
1195
+ );
1196
+ }
1197
+ static SendImpressionEvent(req, initReq) {
1198
+ return fetchReq(
1199
+ `/v1alpha/${req["name"]}:impression`,
1200
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
1201
+ );
1181
1202
  }
1182
1203
  };
1183
1204
 
@@ -1260,7 +1281,9 @@ async function selectItem(options) {
1260
1281
  items.forEach((item, idx) => {
1261
1282
  const displayName = getDisplayName(item);
1262
1283
  const identifier = getIdentifier(item);
1263
- printListItem(`${idx + 1}. ${displayName} (ID: ${identifier})`);
1284
+ printListItem(
1285
+ `${idx + 1}. ${bright(displayName)} (ID: ${cyan(identifier)})`
1286
+ );
1264
1287
  });
1265
1288
  const rl = readline2.createInterface({
1266
1289
  input: process.stdin,
@@ -1406,8 +1429,10 @@ Selecting workspace: ${chalk2.whiteBright(workspaceId)}`);
1406
1429
  }
1407
1430
  }
1408
1431
  const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
1409
- print(`
1410
- Selecting API key: ${chalk2.whiteBright(trimBase64Key(base64Key))}`);
1432
+ print(
1433
+ `
1434
+ Selecting API key: ${chalk2.whiteBright(trimBase64Key(base64Key))}`
1435
+ );
1411
1436
  await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);
1412
1437
  success("\nWorkspace and API key selected.");
1413
1438
  }
@@ -1735,25 +1760,19 @@ INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KE
1735
1760
  const expirationDate = credentials.expiresAt ? new Date(credentials.expiresAt).toLocaleString() : "Unknown";
1736
1761
  console.log();
1737
1762
  printBright("Token Status:");
1738
- print(
1739
- ` Inworld Token: ${trimToken(credentials.inworldToken)}`
1740
- );
1763
+ print(` Inworld Token: ${trimToken(credentials.inworldToken)}`);
1741
1764
  print(` Expires At: ${expirationDate}`);
1742
1765
  print(` Status: ${isExpired ? "Expired" : "Valid"}`);
1743
1766
  } else {
1744
1767
  printHeader("\nToken Status:");
1745
1768
  print(` Inworld Token: Not available`);
1746
1769
  }
1747
- print(
1748
- ` Refresh Token: ${trimToken(credentials.refreshToken)}`
1749
- );
1770
+ print(` Refresh Token: ${trimToken(credentials.refreshToken)}`);
1750
1771
  print(` Session Status: Active`);
1751
1772
  printBright("\nActive Workspace:");
1752
1773
  if (credentials.workspace) {
1753
1774
  print(` Workspace id: ${credentials.workspace}`);
1754
- print(
1755
- ` Workspace link: ${workspaceLink(credentials.workspace)}`
1756
- );
1775
+ print(` Workspace link: ${workspaceLink(credentials.workspace)}`);
1757
1776
  } else {
1758
1777
  print(` No workspace activated`);
1759
1778
  print(` Run "inworld workspace activate" to select a workspace`);
@@ -1814,7 +1833,7 @@ var Analytics = class _Analytics {
1814
1833
  }
1815
1834
  /**
1816
1835
  * Initializes Mixpanel with user context (email and CLI version).
1817
- * Only initializes if user is authenticated and hasn't opted out.
1836
+ * Only initializes if the user is authenticated and hasn't opted out.
1818
1837
  */
1819
1838
  async initialize() {
1820
1839
  try {
@@ -1838,7 +1857,7 @@ var Analytics = class _Analytics {
1838
1857
  environment: credentials.env || "PROD"
1839
1858
  });
1840
1859
  }
1841
- } catch (error) {
1860
+ } catch {
1842
1861
  this.initialized = false;
1843
1862
  }
1844
1863
  }
@@ -1871,7 +1890,7 @@ var Analytics = class _Analytics {
1871
1890
  cli_version: CLI_VERSION,
1872
1891
  ...parameters
1873
1892
  });
1874
- } catch (error) {
1893
+ } catch {
1875
1894
  }
1876
1895
  }
1877
1896
  /**
@@ -1892,7 +1911,7 @@ var Analytics = class _Analytics {
1892
1911
  cli_version: CLI_VERSION,
1893
1912
  error_message: errorMessage
1894
1913
  });
1895
- } catch (error) {
1914
+ } catch {
1896
1915
  }
1897
1916
  }
1898
1917
  /**
@@ -2470,7 +2489,9 @@ var loadGraph = async (file) => {
2470
2489
  }
2471
2490
  const graphId = module.graph.graphId;
2472
2491
  if (typeof graphId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(graphId)) {
2473
- printError("Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores.");
2492
+ printError(
2493
+ "Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores."
2494
+ );
2474
2495
  process.exit(1);
2475
2496
  }
2476
2497
  return {
@@ -2646,15 +2667,20 @@ Curl commands to try the graph:`);
2646
2667
  TEMPLATE:
2647
2668
  `);
2648
2669
  printBright(` curl -X POST ${startUrl} \\`);
2649
- printBright(' -H "Authorization: Basic $(inworld auth print-api-key)" \\');
2670
+ printBright(
2671
+ ' -H "Authorization: Basic $(inworld auth print-api-key)" \\'
2672
+ );
2650
2673
  printBright(' -H "Content-Type: application/json" \\');
2651
2674
  printBright(" -d '{<YOUR_INPUT>}'");
2652
2675
  printBright(`
2653
2676
  EXAMPLE (LLM + TTS Pipeline):`);
2654
2677
  printBright(` curl -X POST ${startUrl} \\`);
2655
- printBright(' -H "Authorization: Basic $(inworld auth print-api-key)" \\');
2678
+ printBright(
2679
+ ' -H "Authorization: Basic $(inworld auth print-api-key)" \\'
2680
+ );
2656
2681
  printBright(' -H "Content-Type: application/json" \\');
2657
2682
  printBright(` -d '{"input": {"user_input":"Hello!"}}'`);
2683
+ await graph.stopRuntime();
2658
2684
  try {
2659
2685
  fs2.rmSync(tempBaseDir, { recursive: true, force: true });
2660
2686
  } catch (_error) {
@@ -2680,83 +2706,265 @@ var deployCommandAlias = makeDeployCommand(
2680
2706
  );
2681
2707
 
2682
2708
  // src/commands/graph/graph_init_command.ts
2683
- import chalk4 from "chalk";
2684
2709
  import { Command as Command11 } from "commander";
2710
+ import fs4 from "fs";
2711
+ import path4 from "path";
2712
+ import * as readline4 from "readline";
2713
+
2714
+ // src/services/template_service.ts
2685
2715
  import fs3 from "fs";
2716
+ import { createWriteStream } from "fs";
2717
+ import https from "https";
2718
+ import ora2 from "ora";
2719
+ import os2 from "os";
2686
2720
  import path3 from "path";
2687
- import * as readline4 from "readline";
2688
- import { fileURLToPath } from "url";
2689
- var __filename = fileURLToPath(import.meta.url);
2690
- var __dirname = path3.dirname(__filename);
2691
- function getTemplatePath() {
2692
- const possiblePaths = [
2693
- // Production: templates are copied to dist/templates (when code is bundled in dist/index.js)
2694
- path3.join(__dirname, "templates"),
2695
- // Development: templates are in src/templates (when running from src/)
2696
- path3.join(__dirname, "..", "..", "templates"),
2697
- // Alternative: if running from nested directory structure
2698
- path3.join(__dirname, "..", "..", "..", "templates")
2721
+ var DEFAULT_TEMPLATE_BRANCH = "main";
2722
+ var CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1e3;
2723
+ function getTemplateCachePath() {
2724
+ const cacheDir = path3.join(os2.tmpdir(), "inworld-cli-templates");
2725
+ if (!fs3.existsSync(cacheDir)) {
2726
+ fs3.mkdirSync(cacheDir, { recursive: true });
2727
+ }
2728
+ return cacheDir;
2729
+ }
2730
+ async function fetchTemplatesMetadata() {
2731
+ try {
2732
+ const response = await fetch(TEMPLATES_METADATA_URL);
2733
+ if (!response.ok) {
2734
+ throw new Error(`Failed to fetch templates metadata: ${response.status}`);
2735
+ }
2736
+ const data = await response.json();
2737
+ const templates = data.templates || [];
2738
+ return templates.filter((template) => template.id === "llm-to-tts-node");
2739
+ } catch (error) {
2740
+ throw error;
2741
+ }
2742
+ }
2743
+ function extractRepoFromUrl(githubUrl) {
2744
+ const match = githubUrl.match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);
2745
+ if (match) {
2746
+ return `${match[1]}/${match[2]}`;
2747
+ }
2748
+ return null;
2749
+ }
2750
+ function parseRepository(repoString) {
2751
+ let repo = repoString.replace(/\.git$/, "");
2752
+ const urlMatch = repo.match(/github\.com[/:]([^/]+)\/([^/]+)/);
2753
+ if (urlMatch) {
2754
+ return { owner: urlMatch[1], repo: urlMatch[2] };
2755
+ }
2756
+ const parts = repo.split("/");
2757
+ if (parts.length !== 2) {
2758
+ throw new Error(
2759
+ `Invalid repository format: ${repoString}. Expected 'owner/repo' or GitHub URL.`
2760
+ );
2761
+ }
2762
+ return { owner: parts[0], repo: parts[1] };
2763
+ }
2764
+ function copyDirectory(src, dest) {
2765
+ fs3.mkdirSync(dest, { recursive: true });
2766
+ const entries = fs3.readdirSync(src, { withFileTypes: true });
2767
+ const excludeList = [
2768
+ ".git",
2769
+ ".github",
2770
+ "node_modules",
2771
+ ".DS_Store",
2772
+ ".cache-metadata.json"
2699
2773
  ];
2700
- for (const templatePath of possiblePaths) {
2701
- if (fs3.existsSync(templatePath)) {
2702
- return templatePath;
2774
+ for (const entry of entries) {
2775
+ if (excludeList.includes(entry.name)) {
2776
+ continue;
2777
+ }
2778
+ const srcPath = path3.join(src, entry.name);
2779
+ const destPath = path3.join(dest, entry.name);
2780
+ if (entry.isDirectory()) {
2781
+ copyDirectory(srcPath, destPath);
2782
+ } else {
2783
+ fs3.copyFileSync(srcPath, destPath);
2703
2784
  }
2704
2785
  }
2705
- throw new Error(
2706
- "Template directory not found. Please ensure templates are properly installed."
2707
- );
2708
2786
  }
2709
- var TEMPLATE_PATH = getTemplatePath();
2710
- function loadTemplateMetadata(templateDir, basePath) {
2711
- const metadataPath = path3.join(basePath, templateDir, "metadata.json");
2712
- if (fs3.existsSync(metadataPath)) {
2787
+ async function downloadTemplateFromGitHub(templateName, targetPath, repository, branch) {
2788
+ if (!repository) {
2789
+ throw new Error(
2790
+ `No repository found for template '${templateName}'. Please ensure the template exists in the templates metadata.`
2791
+ );
2792
+ }
2793
+ const { owner, repo } = parseRepository(repository);
2794
+ const repoBranch = branch || DEFAULT_TEMPLATE_BRANCH;
2795
+ const spinner = ora2(
2796
+ `Downloading template '${templateName}' from ${owner}/${repo}...`
2797
+ ).start();
2798
+ try {
2799
+ const tempDir = fs3.mkdtempSync(path3.join(os2.tmpdir(), "inworld-template-"));
2800
+ const zipPath = path3.join(tempDir, `${templateName}.zip`);
2801
+ const archiveUrl = `https://api.github.com/repos/${owner}/${repo}/zipball/${repoBranch}`;
2802
+ spinner.text = `Downloading repository archive from ${owner}/${repo}...`;
2803
+ await new Promise((resolve2, reject) => {
2804
+ https.get(
2805
+ archiveUrl,
2806
+ { headers: { "User-Agent": "inworld-cli" } },
2807
+ (res) => {
2808
+ if (res.statusCode === 302 && res.headers.location) {
2809
+ https.get(
2810
+ res.headers.location,
2811
+ { headers: { "User-Agent": "inworld-cli" } },
2812
+ (redirectRes) => {
2813
+ if (redirectRes.statusCode !== 200) {
2814
+ reject(
2815
+ new Error(
2816
+ `Failed to download: ${redirectRes.statusCode}`
2817
+ )
2818
+ );
2819
+ return;
2820
+ }
2821
+ const fileStream = createWriteStream(zipPath);
2822
+ redirectRes.pipe(fileStream);
2823
+ fileStream.on("finish", resolve2);
2824
+ fileStream.on("error", reject);
2825
+ }
2826
+ ).on("error", reject);
2827
+ } else if (res.statusCode === 200) {
2828
+ const fileStream = createWriteStream(zipPath);
2829
+ res.pipe(fileStream);
2830
+ fileStream.on("finish", resolve2);
2831
+ fileStream.on("error", reject);
2832
+ } else {
2833
+ reject(new Error(`Failed to download: ${res.statusCode}`));
2834
+ }
2835
+ }
2836
+ ).on("error", reject);
2837
+ });
2838
+ spinner.text = `Extracting template files...`;
2839
+ const AdmZip = (await import("adm-zip")).default;
2840
+ const zip = new AdmZip(zipPath);
2841
+ const extractPath = path3.join(tempDir, "extracted");
2842
+ zip.extractAllTo(extractPath, true);
2843
+ const extractedDirs = fs3.readdirSync(extractPath);
2844
+ if (extractedDirs.length === 0) {
2845
+ throw new Error("Failed to extract template from GitHub");
2846
+ }
2847
+ const extractedRoot = path3.join(extractPath, extractedDirs[0]);
2848
+ const entries = fs3.readdirSync(extractedRoot);
2849
+ if (entries.length === 0) {
2850
+ throw new Error(`Repository ${owner}/${repo} appears to be empty.`);
2851
+ }
2852
+ spinner.text = `Copying application files...`;
2853
+ fs3.mkdirSync(targetPath, { recursive: true });
2854
+ copyDirectory(extractedRoot, targetPath);
2855
+ fs3.rmSync(tempDir, { recursive: true, force: true });
2856
+ spinner.stop();
2857
+ } catch (error) {
2858
+ spinner.fail(
2859
+ `Failed to download template: ${error instanceof Error ? error.message : String(error)}`
2860
+ );
2861
+ throw error;
2862
+ }
2863
+ }
2864
+ function isCacheValid(templateDir) {
2865
+ if (!fs3.existsSync(templateDir)) {
2866
+ return false;
2867
+ }
2868
+ const cacheMetadataPath = path3.join(templateDir, ".cache-metadata.json");
2869
+ if (!fs3.existsSync(cacheMetadataPath)) {
2713
2870
  try {
2714
- return JSON.parse(fs3.readFileSync(metadataPath, "utf-8"));
2715
- } catch (err) {
2716
- print(`Failed to parse metadata for ${templateDir}: ${err}`);
2871
+ const stats = fs3.statSync(templateDir);
2872
+ const age = Date.now() - stats.mtimeMs;
2873
+ return age < CACHE_EXPIRATION_MS;
2874
+ } catch {
2875
+ return false;
2717
2876
  }
2718
2877
  }
2719
- return {
2720
- name: templateDir,
2721
- displayName: templateDir.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
2722
- description: `${templateDir} template`,
2723
- tags: [],
2724
- defaultProjectName: templateDir
2878
+ try {
2879
+ const metadata = JSON.parse(
2880
+ fs3.readFileSync(cacheMetadataPath, "utf-8")
2881
+ );
2882
+ const age = Date.now() - metadata.cachedAt;
2883
+ return age < CACHE_EXPIRATION_MS;
2884
+ } catch {
2885
+ return false;
2886
+ }
2887
+ }
2888
+ function isTemplateCached(templateId, forceRefresh) {
2889
+ if (forceRefresh) {
2890
+ return false;
2891
+ }
2892
+ const cachePath = getTemplateCachePath();
2893
+ const templateDir = path3.join(cachePath, templateId);
2894
+ if (!fs3.existsSync(templateDir)) {
2895
+ return false;
2896
+ }
2897
+ const files = fs3.readdirSync(templateDir);
2898
+ return files.length > 0 && isCacheValid(templateDir);
2899
+ }
2900
+ function writeCacheMetadata(templateDir) {
2901
+ const cacheMetadataPath = path3.join(templateDir, ".cache-metadata.json");
2902
+ const metadata = {
2903
+ cachedAt: Date.now()
2725
2904
  };
2905
+ fs3.writeFileSync(cacheMetadataPath, JSON.stringify(metadata, null, 2));
2906
+ }
2907
+ async function downloadAndCacheTemplate(templateId, repository, branch, forceRefresh = false) {
2908
+ const cachePath = getTemplateCachePath();
2909
+ const templateDir = path3.join(cachePath, templateId);
2910
+ if (!forceRefresh && fs3.existsSync(templateDir)) {
2911
+ const files = fs3.readdirSync(templateDir);
2912
+ if (files.length > 0 && isCacheValid(templateDir)) {
2913
+ return { path: templateDir, fromCache: true };
2914
+ }
2915
+ if (fs3.existsSync(templateDir)) {
2916
+ fs3.rmSync(templateDir, { recursive: true, force: true });
2917
+ }
2918
+ }
2919
+ if (!repository) {
2920
+ throw new Error(
2921
+ `No repository found for template '${templateId}'. Please ensure the template exists in the templates metadata.`
2922
+ );
2923
+ }
2924
+ await downloadTemplateFromGitHub(templateId, templateDir, repository, branch);
2925
+ if (!fs3.existsSync(templateDir)) {
2926
+ throw new Error(`Template '${templateId}' was not downloaded correctly.`);
2927
+ }
2928
+ writeCacheMetadata(templateDir);
2929
+ return { path: templateDir, fromCache: false };
2726
2930
  }
2727
- function getAvailableTemplatesWithMetadata() {
2931
+ async function getAvailableTemplatesWithMetadata() {
2728
2932
  const templates = [];
2729
2933
  try {
2730
- const entries = fs3.readdirSync(TEMPLATE_PATH, { withFileTypes: true });
2731
- const templateDirs = entries.filter((entry) => entry.isDirectory()).filter((dir) => {
2732
- const graphPath = path3.join(TEMPLATE_PATH, dir.name, "graph.ts");
2733
- return fs3.existsSync(graphPath);
2734
- });
2735
- for (const dir of templateDirs) {
2736
- const metadata = loadTemplateMetadata(dir.name, TEMPLATE_PATH);
2737
- if (metadata) {
2738
- templates.push({
2739
- directory: dir.name,
2740
- metadata
2741
- });
2742
- }
2934
+ const metadataTemplates = await fetchTemplatesMetadata();
2935
+ for (const template of metadataTemplates) {
2936
+ const templateInfo = {
2937
+ directory: template.id || template.name,
2938
+ metadata: template
2939
+ };
2940
+ templates.push(templateInfo);
2743
2941
  }
2744
- } catch (_err) {
2942
+ } catch (error) {
2943
+ throw error;
2745
2944
  }
2746
- return templates;
2945
+ return templates.filter((template) => template.metadata.id === "llm-to-tts-node");
2946
+ }
2947
+ function copyTemplateDirectory(src, dest) {
2948
+ copyDirectory(src, dest);
2949
+ }
2950
+
2951
+ // src/commands/graph/graph_init_command.ts
2952
+ var DEFAULT_TEMPLATE_BRANCH2 = "main";
2953
+ function hasLockFiles(directory) {
2954
+ const packageLockPath = path4.join(directory, "package-lock.json");
2955
+ return fs4.existsSync(packageLockPath);
2747
2956
  }
2748
- async function promptNpmInstall() {
2957
+ async function promptInstallDependencies() {
2749
2958
  return confirm({
2750
- message: "\nWould you like to install dependencies now? (y/n) ",
2959
+ message: `
2960
+ Would you like to install dependencies now using npm? (y/n) `,
2751
2961
  defaultValue: false
2752
2962
  });
2753
2963
  }
2754
- async function runNpmInstall(directory) {
2964
+ async function runPackageInstall(directory) {
2755
2965
  const { spawn } = await import("child_process");
2756
2966
  return new Promise((resolve2, reject) => {
2757
- console.log();
2758
- print("Installing dependencies...");
2759
- console.log();
2967
+ print(`Installing dependencies using npm...`);
2760
2968
  const install = spawn("npm", ["install"], {
2761
2969
  cwd: directory,
2762
2970
  stdio: "inherit",
@@ -2764,133 +2972,197 @@ async function runNpmInstall(directory) {
2764
2972
  });
2765
2973
  install.on("close", (code) => {
2766
2974
  if (code === 0) {
2767
- console.log();
2768
2975
  success("Dependencies installed successfully!");
2769
2976
  resolve2();
2770
2977
  } else {
2771
- console.log();
2772
2978
  printError(`\u274C npm install failed with code ${code}`);
2773
2979
  reject(new Error(`npm install failed with code ${code}`));
2774
2980
  }
2775
2981
  });
2776
2982
  install.on("error", (err) => {
2777
- console.log();
2778
2983
  printError(`\u274C Failed to run npm install: ${err.message}`);
2779
2984
  reject(err);
2780
2985
  });
2781
2986
  });
2782
2987
  }
2783
- function createPackageJson(graphFileName) {
2784
- const packageJson = {
2785
- name: "inworld-graph-project",
2786
- version: "1.0.0",
2787
- description: "Inworld Runtime Graph Project",
2788
- main: graphFileName,
2789
- scripts: {
2790
- start: `npx inworld serve ${graphFileName}`,
2791
- run: `npx inworld run ${graphFileName}`
2792
- },
2793
- dependencies: {
2794
- "@inworld/runtime": RUNTIME_VERSION
2795
- },
2796
- keywords: ["inworld", "ai", "graph", "runtime"],
2797
- author: "",
2798
- license: "MIT"
2799
- };
2800
- return packageJson;
2801
- }
2802
- function createGraphTemplate(templateName) {
2803
- const availableTemplates = getAvailableTemplatesWithMetadata();
2804
- if (!availableTemplates.find((template) => template.directory === templateName)) {
2805
- throw new Error(
2806
- `Unknown template: ${templateName}. Available templates: ${availableTemplates.map((template) => template.directory).join(", ")}`
2807
- );
2808
- }
2809
- const templateFilePath = path3.join(TEMPLATE_PATH, templateName, "graph.ts");
2810
- if (!fs3.existsSync(templateFilePath)) {
2811
- throw new Error(
2812
- `Template file not found: ${templateName}/graph.ts. Please ensure the template files are in the templates folder.`
2813
- );
2814
- }
2815
- return fs3.readFileSync(templateFilePath, "utf-8");
2816
- }
2817
- function createReadme(templateName, graphFileName) {
2818
- const readmePath = path3.join(TEMPLATE_PATH, templateName, "README.md");
2819
- if (!fs3.existsSync(readmePath)) {
2820
- printError(`README file not found: ${readmePath}`);
2821
- process.exit(1);
2822
- }
2823
- const readmeContent = fs3.readFileSync(readmePath, "utf-8");
2824
- return readmeContent.replace(/\{\{graphFileName\}\}/g, graphFileName);
2825
- }
2826
2988
  var initAction = async (options) => {
2827
2989
  try {
2828
2990
  if (options.listTemplates) {
2829
- const templates2 = getAvailableTemplatesWithMetadata();
2830
- console.log();
2991
+ let templates2;
2992
+ try {
2993
+ templates2 = await getAvailableTemplatesWithMetadata();
2994
+ } catch (error) {
2995
+ print(
2996
+ `Failed to fetch templates metadata: ${error instanceof Error ? error.message : String(error)}`
2997
+ );
2998
+ return;
2999
+ }
2831
3000
  printHeader("\u{1F4DA} Available templates:");
2832
- console.log();
2833
- for (const template of templates2) {
2834
- printListItem(`${chalk4.cyan.bold(template.metadata.name)}`);
2835
- printListItem(` ${template.metadata.description}`);
2836
- if (template.metadata.tags && template.metadata.tags.length > 0) {
2837
- printListItem(` Tags: ${template.metadata.tags.join(", ")}`);
3001
+ if (templates2.length === 0) {
3002
+ print("No templates found.");
3003
+ print(
3004
+ `
3005
+ Use ${bold("inworld init --template <name>")} to download and use a template from GitHub.`
3006
+ );
3007
+ return;
3008
+ }
3009
+ for (const template2 of templates2) {
3010
+ p(
3011
+ `\u2514 ${bold(cyan(template2.metadata.name))} (ID: ${template2.metadata.id})`
3012
+ );
3013
+ print(` ${template2.metadata.description}`);
3014
+ let useCases = [];
3015
+ if (template2.metadata.useCase && Array.isArray(template2.metadata.useCase)) {
3016
+ useCases = template2.metadata.useCase;
3017
+ } else if (template2.metadata.useCases && Array.isArray(template2.metadata.useCases)) {
3018
+ useCases = template2.metadata.useCases.map(
3019
+ (uc) => typeof uc === "string" ? uc : uc.useCase
3020
+ );
3021
+ }
3022
+ if (useCases.length > 0) {
3023
+ printBright(` Use Cases: ${dim(useCases.join(", "))}`);
3024
+ }
3025
+ if (template2.metadata.sdk) {
3026
+ const sdkInfo = template2.metadata.sdkVersion ? `${template2.metadata.sdk} v${template2.metadata.sdkVersion}` : template2.metadata.sdk;
3027
+ printBright(` SDK: ${dim(sdkInfo)}`);
2838
3028
  }
2839
- if (template.metadata.requirements?.apiKeys) {
2840
- printListItem(
2841
- ` Required API Keys: ${template.metadata.requirements.apiKeys.join(", ")}`
3029
+ const modalities = [];
3030
+ if (template2.metadata.inputModality && template2.metadata.inputModality.length > 0) {
3031
+ modalities.push(
3032
+ `Input: ${template2.metadata.inputModality.join(", ")}`
2842
3033
  );
2843
3034
  }
2844
- console.log();
3035
+ if (template2.metadata.outputModality && template2.metadata.outputModality.length > 0) {
3036
+ modalities.push(
3037
+ `Output: ${template2.metadata.outputModality.join(", ")}`
3038
+ );
3039
+ }
3040
+ if (modalities.length > 0) {
3041
+ printBright(` Modalities: ${dim(modalities.join(" | "))}`);
3042
+ }
3043
+ if (template2.metadata.type) {
3044
+ printBright(` Type: ${dim(template2.metadata.type)}`);
3045
+ }
3046
+ if (template2.metadata.docsLink) {
3047
+ printBright(
3048
+ ` Docs: ${dim(link(template2.metadata.docsLink))}`
3049
+ );
3050
+ }
3051
+ if (template2.metadata.webDemo) {
3052
+ printBright(
3053
+ ` Demo: ${dim(link(template2.metadata.webDemo))}`
3054
+ );
3055
+ }
3056
+ if (template2.metadata.videoDemo) {
3057
+ printBright(
3058
+ ` Video: ${dim(link(template2.metadata.videoDemo))}`
3059
+ );
3060
+ }
3061
+ p("");
2845
3062
  }
2846
3063
  print(
2847
- `Use ${chalk4.bold("inworld graph init")} to interactively select a template.`
3064
+ `
3065
+ Note: Templates are downloaded from GitHub repositories as complete applications.`
2848
3066
  );
2849
- console.log();
2850
3067
  return;
2851
3068
  }
2852
- const templates = getAvailableTemplatesWithMetadata();
2853
- if (templates.length === 0) {
2854
- printError(
2855
- "\u274C No templates found. Please ensure templates are properly installed."
2856
- );
2857
- process.exit(1);
2858
- }
2859
- let selectedTemplate = null;
2860
3069
  let projectName;
3070
+ let selectedTemplateId;
3071
+ const templates = await fetchTemplatesMetadata();
2861
3072
  if (!options.template) {
2862
- options.template = "llm_tts";
2863
- }
2864
- if (!options.template) {
2865
- console.log();
2866
- printHeader("\u{1F680} Welcome to Inworld Graph Project Initializer!");
2867
- console.log();
2868
- selectedTemplate = await selectItem({
3073
+ printBright("\u{1F680} Welcome to Inworld Template Initializer!");
3074
+ if (templates.length === 0) {
3075
+ printError("\u274C No templates found.");
3076
+ print(`
3077
+ Please ensure the templates metadata is accessible.`);
3078
+ process.exit(1);
3079
+ }
3080
+ const selectedTemplate2 = await selectItemOrExit({
2869
3081
  items: templates,
2870
- getDisplayName: (item) => `${item.metadata.name} - ${item.metadata.description}`,
2871
- getIdentifier: (item) => item.directory,
2872
- prompt: "Select a template (enter number or id):",
3082
+ getDisplayName: (template2) => {
3083
+ return `${bold(cyan(template2.name))} - ${template2.description}`;
3084
+ },
3085
+ getIdentifier: (template2) => template2.id,
3086
+ prompt: "Select a template (enter number or name)",
2873
3087
  title: "\u{1F4CB} Available Templates:",
2874
- noItemsMessage: "No templates found.",
2875
- invalidSelectionMessage: "Invalid selection. Please try again."
3088
+ exitOnFailure: true
2876
3089
  });
2877
- if (!selectedTemplate) {
2878
- console.log();
2879
- print("No template selected. Exiting.");
2880
- return;
2881
- }
3090
+ selectedTemplateId = selectedTemplate2.id;
2882
3091
  } else {
2883
- selectedTemplate = templates.find((t) => t.directory === options.template) || null;
2884
- if (!selectedTemplate) {
2885
- printError(`\u274C Template not found: ${options.template}`);
3092
+ selectedTemplateId = options.template;
3093
+ }
3094
+ let template = templates.find((t) => t.id === selectedTemplateId);
3095
+ if (!template && !selectedTemplateId.endsWith("-node")) {
3096
+ const nameWithNode = `${selectedTemplateId}-node`;
3097
+ template = templates.find((t) => t.id === nameWithNode);
3098
+ }
3099
+ if (!template) {
3100
+ const normalizedName = selectedTemplateId.toLowerCase().replace(/[-_\s]/g, "");
3101
+ template = templates.find((t) => {
3102
+ const normalizedTemplateName = t.name.toLowerCase().replace(/[-_\s]/g, "");
3103
+ return normalizedTemplateName === normalizedName;
3104
+ });
3105
+ }
3106
+ if (!template) {
3107
+ printError(`\u274C Template '${selectedTemplateId}' not found.`);
3108
+ print(
3109
+ `
3110
+ Use ${bold("inworld init --list-templates")} to see all available templates.`
3111
+ );
3112
+ process.exit(1);
3113
+ }
3114
+ const repoToUse = template.githubRepo ? extractRepoFromUrl(template.githubRepo) : null;
3115
+ if (!repoToUse) {
3116
+ printError(
3117
+ `\u274C No repository found for template '${selectedTemplateId}'.`
3118
+ );
3119
+ print("The template metadata is missing a valid GitHub repository.");
3120
+ process.exit(1);
3121
+ }
3122
+ const branchToUse = template.branch || DEFAULT_TEMPLATE_BRANCH2;
3123
+ let cachedTemplatePath;
3124
+ let templateFromCache = false;
3125
+ try {
3126
+ const isCached = isTemplateCached(template.id, options.force ?? false);
3127
+ if (options.force) {
2886
3128
  print(
2887
- `Available templates: ${templates.map((t) => t.directory).join(", ")}`
3129
+ `Force refreshing template '${selectedTemplateId}' from GitHub...`
2888
3130
  );
2889
- process.exit(1);
3131
+ } else if (isCached) {
3132
+ print(
3133
+ `\u2713 Using cached template '${selectedTemplateId}' (cache expires in 24 hours)`
3134
+ );
3135
+ } else {
3136
+ print(`Downloading template '${selectedTemplateId}' from GitHub...`);
3137
+ }
3138
+ const cacheResult = await downloadAndCacheTemplate(
3139
+ template.id,
3140
+ repoToUse,
3141
+ branchToUse,
3142
+ options.force
3143
+ );
3144
+ cachedTemplatePath = cacheResult.path;
3145
+ templateFromCache = cacheResult.fromCache;
3146
+ if (!isCached && !templateFromCache) {
3147
+ print(`\u2713 Template '${selectedTemplateId}' downloaded successfully`);
2890
3148
  }
3149
+ } catch (error) {
3150
+ printError(`\u274C Failed to download template: ${selectedTemplateId}`);
3151
+ print(
3152
+ `Error: ${error instanceof Error ? error.message : String(error)}`
3153
+ );
3154
+ print(
3155
+ `
3156
+ Please ensure the template exists in the templates metadata and the repository is accessible.`
3157
+ );
3158
+ process.exit(1);
2891
3159
  }
2892
- projectName = options.name || selectedTemplate.metadata.defaultProjectName || selectedTemplate.directory;
2893
- if (!options.template && !options.name) {
3160
+ const selectedTemplate = {
3161
+ directory: template.id || template.name,
3162
+ metadata: template
3163
+ };
3164
+ projectName = options.name || selectedTemplate.metadata.id || selectedTemplate.directory;
3165
+ if (!options.name) {
2894
3166
  const rl = readline4.createInterface({
2895
3167
  input: process.stdin,
2896
3168
  output: process.stdout
@@ -2898,11 +3170,11 @@ var initAction = async (options) => {
2898
3170
  const askProjectName = () => new Promise((resolve2) => {
2899
3171
  rl.question(
2900
3172
  `
2901
- Project name (${selectedTemplate.metadata.defaultProjectName}): `,
3173
+ Project name (${selectedTemplate.metadata.id || selectedTemplate.metadata.name}): `,
2902
3174
  (answer) => {
2903
3175
  rl.close();
2904
3176
  resolve2(
2905
- answer.trim() || selectedTemplate.metadata.defaultProjectName
3177
+ answer.trim() || selectedTemplate.metadata.id || selectedTemplate.metadata.name
2906
3178
  );
2907
3179
  }
2908
3180
  );
@@ -2910,93 +3182,68 @@ Project name (${selectedTemplate.metadata.defaultProjectName}): `,
2910
3182
  projectName = await askProjectName();
2911
3183
  }
2912
3184
  const currentDir = process.cwd();
2913
- const projectDir = path3.join(currentDir, projectName);
2914
- if (fs3.existsSync(projectDir)) {
2915
- console.log();
3185
+ const projectDir = path4.join(currentDir, projectName);
3186
+ if (fs4.existsSync(projectDir)) {
2916
3187
  print(`Directory '${projectName}' already exists.`);
2917
- if (!options.template) {
2918
- const confirmOverwrite = await confirm({
2919
- message: "Do you want to overwrite it? (y/n) ",
2920
- defaultValue: false
2921
- });
2922
- if (!confirmOverwrite) {
2923
- print("Initialization cancelled.");
2924
- return;
2925
- }
2926
- fs3.rmSync(projectDir, { recursive: true, force: true });
2927
- } else {
2928
- print("Overwriting existing directory...");
2929
- fs3.rmSync(projectDir, { recursive: true, force: true });
3188
+ const confirmOverwrite = await confirm({
3189
+ message: "Do you want to overwrite it? (y/n) ",
3190
+ defaultValue: false
3191
+ });
3192
+ if (!confirmOverwrite) {
3193
+ print("Initialization cancelled.");
3194
+ process.exit(0);
2930
3195
  }
3196
+ fs4.rmSync(projectDir, { recursive: true, force: true });
2931
3197
  }
2932
- fs3.mkdirSync(projectDir, { recursive: true });
2933
- const graphFileName = "graph.ts";
2934
- const graphFilePath = path3.join(projectDir, graphFileName);
2935
- const packageJsonPath = path3.join(projectDir, "package.json");
2936
- const readmePath = path3.join(projectDir, "README.md");
2937
- console.log();
2938
- print(`Initializing Inworld graph project: ${bright(projectName)}`);
3198
+ print(
3199
+ `Initializing project from template: ${bright(selectedTemplate.metadata.name || selectedTemplateId)}`
3200
+ );
2939
3201
  print(` Creating project in: ${projectDir}`);
2940
- print(` Using template: ${selectedTemplate.metadata.displayName}`);
2941
- console.log();
2942
- print(" Creating graph file...");
2943
- const graphContent = createGraphTemplate(selectedTemplate.directory);
2944
- fs3.writeFileSync(graphFilePath, graphContent, "utf-8");
2945
- if (!options.skipPackageJson) {
2946
- print(" Creating package.json...");
2947
- const packageJson = createPackageJson(graphFileName);
2948
- packageJson.name = projectName;
2949
- fs3.writeFileSync(
2950
- packageJsonPath,
2951
- JSON.stringify(packageJson, null, 2),
2952
- "utf-8"
2953
- );
2954
- }
2955
- if (!options.skipReadme) {
2956
- print(" Creating README.md...");
2957
- const readmeContent = createReadme(
2958
- selectedTemplate.directory,
2959
- graphFileName
2960
- );
2961
- fs3.writeFileSync(readmePath, readmeContent, "utf-8");
2962
- }
2963
- if (selectedTemplate.metadata.requirements?.apiKeys) {
2964
- console.log();
2965
- print("This template requires the following API keys:");
2966
- for (const key of selectedTemplate.metadata.requirements.apiKeys) {
2967
- print(` \u2022 ${key}`);
2968
- }
2969
- }
2970
- console.log();
2971
- success("Inworld graph project initialized successfully!");
2972
- if (!options.skipInstall && !options.skipPackageJson) {
2973
- const shouldInstall = await promptNpmInstall();
2974
- if (shouldInstall) {
2975
- try {
2976
- await runNpmInstall(projectDir);
2977
- } catch (_err) {
2978
- console.log();
2979
- print("\u26A0\uFE0F You can install dependencies manually by running:");
2980
- print(` cd ${projectName} && npm install`);
3202
+ print(" Copying template files...");
3203
+ copyTemplateDirectory(cachedTemplatePath, projectDir);
3204
+ success("Project initialized successfully!");
3205
+ const hasLock = hasLockFiles(projectDir);
3206
+ if (hasLock) {
3207
+ const installCommand = "npm install";
3208
+ if (!options.skipInstall) {
3209
+ const shouldInstall = await promptInstallDependencies();
3210
+ if (shouldInstall) {
3211
+ try {
3212
+ await runPackageInstall(projectDir);
3213
+ } catch (_err) {
3214
+ print("\u26A0\uFE0F You can install dependencies manually by running:");
3215
+ print(` cd ${projectName} && ${installCommand}`);
3216
+ }
3217
+ } else {
3218
+ printBright(`
3219
+ ${dim("Skipping dependency installation. You can run `")}${installCommand}${dim("` later.")}`);
2981
3220
  }
3221
+ }
3222
+ printHeader("Next steps:\n");
3223
+ printBright(` ${dim("1. Run `")}cd ${projectName}${dim("`")}`);
3224
+ if (!options.skipInstall) {
3225
+ printBright(
3226
+ ` ${dim("2. Run `")}${installCommand}${dim("`")} ${dim("(if not already done)")}`
3227
+ );
3228
+ printBright(
3229
+ ` ${dim("3. Follow the instructions in the README to get started")}`
3230
+ );
2982
3231
  } else {
2983
- printBright(`
2984
- ${dim("Skipping dependency installation. You can run `")}npm install${dim("` later.")}`);
3232
+ printBright(
3233
+ ` ${dim("2. Run `")}${installCommand}${dim("`")} ${dim("to install dependencies")}`
3234
+ );
3235
+ printBright(
3236
+ ` ${dim("3. Follow the instructions in the README to get started")}`
3237
+ );
2985
3238
  }
2986
- }
2987
- console.log();
2988
- printHeader("Next steps:\n");
2989
- printBright(` ${dim("1. Run `")}cd ${projectName}${dim("`")}`);
2990
- if (!options.skipInstall) {
2991
- printBright(` ${dim("2. Run `")}npm install${dim("`")} ${dim("(if not already done)")}`);
2992
- printBright(` ${dim("3. Run `")}npm start${dim("`")} ${dim("or `")}npx inworld serve ./graph.ts${dim("`")}`);
2993
3239
  } else {
2994
- printBright(` ${dim("2. Run `")}npm start${dim("`")} ${dim("or `")}npx inworld serve ./graph.ts${dim("`")}`);
2995
- }
2996
- if (selectedTemplate.metadata.examples?.curlCommand) {
2997
- printBright("\nExample curl command:\n");
2998
- printBright(`$ ${selectedTemplate.metadata.examples.curlCommand}`);
3240
+ printHeader("Next steps:\n");
3241
+ printBright(` ${dim("1. Run `")}cd ${projectName}${dim("`")}`);
3242
+ printBright(
3243
+ ` ${dim("2. Follow the instructions in the README to get started")}`
3244
+ );
2999
3245
  }
3246
+ process.exit(0);
3000
3247
  } catch (error) {
3001
3248
  printError("\u274C Error initializing project:");
3002
3249
  console.error(error);
@@ -3004,14 +3251,19 @@ ${dim("Skipping dependency installation. You can run `")}npm install${dim("` lat
3004
3251
  }
3005
3252
  };
3006
3253
  var makeInitCommand = (description) => {
3007
- const availableTemplates = getAvailableTemplatesWithMetadata();
3008
- return new Command11("init").description(description).option("-n, --name <name>", "Name of the project directory").option("--skip-package-json", "Skip creating package.json file").option("--skip-readme", "Skip creating README.md file").option("--skip-install", "Skip npm install prompt").action(initAction);
3254
+ return new Command11("init").description(description).option("-n, --name <name>", "Name of the project directory").option(
3255
+ "-t, --template <template>",
3256
+ "Template to use (will download from GitHub). Use --list-templates to see available templates."
3257
+ ).option("-l, --list-templates", "List all available templates").option("--skip-install", "Skip dependency installation prompt").option(
3258
+ "--force",
3259
+ "Force refresh template cache (download fresh copy even if cached)"
3260
+ ).action(initAction);
3009
3261
  };
3010
3262
  var initCommand = makeInitCommand(
3011
- "Initialize a new Inworld graph project (interactive if no options provided)"
3263
+ "Initialize a new project from a template (downloads complete app from GitHub)"
3012
3264
  );
3013
3265
  var initCommandAlias = makeInitCommand(
3014
- `Alias for "${chalk4.bold("inworld graph init")}"`
3266
+ `Alias for "${bold("inworld graph init")}"`
3015
3267
  );
3016
3268
 
3017
3269
  // src/commands/graph/graph_run_command.ts
@@ -3172,6 +3424,7 @@ var registerGraphVariant = async (graphId, variantDisplayName, variantConfig, fo
3172
3424
  var listVariantsAction = async (file) => {
3173
3425
  const workspaceId = await requireWorkspace();
3174
3426
  const { graph } = await loadGraph(file);
3427
+ graph.stopRuntime();
3175
3428
  const variants = await listGraphVariants(graph.graphId);
3176
3429
  if (!variants || variants.graphVariants?.length === 0) {
3177
3430
  console.log();
@@ -3192,15 +3445,16 @@ var graphListVariantsCommand = new Command14("list").description("List all regis
3192
3445
 
3193
3446
  // src/commands/graph/variant/graph_variant_print_command.ts
3194
3447
  import { Command as Command15 } from "commander";
3195
- import path4 from "path";
3448
+ import path5 from "path";
3196
3449
  var graphVariantPrintAction = async (file, options) => {
3197
3450
  try {
3198
3451
  const { graph } = await loadGraph(file);
3452
+ graph.stopRuntime();
3199
3453
  const jsonResult = await graph.toJSON();
3200
3454
  if (options.output) {
3201
- const outputPath = path4.resolve(options.output);
3202
- const fs4 = await import("fs/promises");
3203
- await fs4.writeFile(options.output, jsonResult);
3455
+ const outputPath = path5.resolve(options.output);
3456
+ const fs5 = await import("fs/promises");
3457
+ await fs5.writeFile(options.output, jsonResult);
3204
3458
  success(`JSON saved to ${outputPath}`);
3205
3459
  } else {
3206
3460
  console.log(jsonResult);
@@ -3221,6 +3475,7 @@ import { Command as Command16 } from "commander";
3221
3475
  var registerVariantsAction = async (file, options) => {
3222
3476
  const workspaceId = await requireWorkspace();
3223
3477
  const { graph } = await loadGraph(file);
3478
+ graph.stopRuntime();
3224
3479
  let response = await registerGraphVariant(
3225
3480
  graph.graphId,
3226
3481
  options.displayName,
@@ -3269,13 +3524,13 @@ var graphVariantCommand = new Command17("variant").description("Manage Inworld g
3269
3524
 
3270
3525
  // src/commands/graph/graph_visualize_command.ts
3271
3526
  import { Command as Command18 } from "commander";
3272
- import path5 from "path";
3527
+ import path6 from "path";
3273
3528
  var visualizeAction = async (file, options) => {
3274
3529
  try {
3275
3530
  const { graph } = await loadGraph(file);
3276
- const outputPath = path5.resolve(options.output);
3277
- print(`Storing graph visualization to ${outputPath}`);
3278
- await graph.visualize(outputPath);
3531
+ print(`Storing graph visualization to ${path6.resolve(options.output)}`);
3532
+ await graph.visualize(options.output);
3533
+ await graph.stopRuntime();
3279
3534
  } catch (error) {
3280
3535
  printError("Error visualizing graph:");
3281
3536
  console.error(error);
@@ -3294,7 +3549,7 @@ var graphCommand = new Command19("graph").description("Manage Inworld graph proj
3294
3549
  });
3295
3550
 
3296
3551
  // src/commands/tts_commands.ts
3297
- import chalk5 from "chalk";
3552
+ import chalk4 from "chalk";
3298
3553
  import { Command as Command20 } from "commander";
3299
3554
  import { writeFile } from "fs/promises";
3300
3555
  import { resolve } from "path";
@@ -3575,15 +3830,15 @@ var listVoicesCommand = new Command20("list-voices").description("List all avail
3575
3830
  return;
3576
3831
  }
3577
3832
  if (!response.voices || response.voices.length === 0) {
3578
- console.log(chalk5.yellow("\u26A0\uFE0F No voices found"));
3833
+ console.log(chalk4.yellow("\u26A0\uFE0F No voices found"));
3579
3834
  process.exit(0);
3580
3835
  return;
3581
3836
  }
3582
3837
  if (options.compact) {
3583
- console.log("\n" + chalk5.bold.green("\u{1F3A4} Available Voice IDs:"));
3584
- console.log(chalk5.gray("\u2500".repeat(50)));
3838
+ console.log("\n" + chalk4.bold.green("\u{1F3A4} Available Voice IDs:"));
3839
+ console.log(chalk4.gray("\u2500".repeat(50)));
3585
3840
  response.voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
3586
- console.log(` ${chalk5.cyan("\u2022")} ${voice.voiceId}`);
3841
+ console.log(` ${chalk4.cyan("\u2022")} ${voice.voiceId}`);
3587
3842
  });
3588
3843
  console.log();
3589
3844
  process.exit(0);
@@ -3599,13 +3854,13 @@ var listVoicesCommand = new Command20("list-voices").description("List all avail
3599
3854
  voicesByLanguage.get(primaryLang).push(voice);
3600
3855
  });
3601
3856
  const sortedLanguages = Array.from(voicesByLanguage.keys()).sort();
3602
- console.log("\n" + chalk5.bold.green("Available TTS Voices"));
3857
+ console.log("\n" + chalk4.bold.green("Available TTS Voices"));
3603
3858
  console.log(
3604
- chalk5.gray(
3859
+ chalk4.gray(
3605
3860
  `Found ${response.voices.length} voices across ${sortedLanguages.length} languages`
3606
3861
  )
3607
3862
  );
3608
- console.log(chalk5.gray("\u2500".repeat(80)));
3863
+ console.log(chalk4.gray("\u2500".repeat(80)));
3609
3864
  sortedLanguages.forEach((lang, langIndex) => {
3610
3865
  const voices = voicesByLanguage.get(lang);
3611
3866
  const languageFlags = {
@@ -3625,19 +3880,19 @@ var listVoicesCommand = new Command20("list-voices").description("List all avail
3625
3880
  const flag = languageFlags[lang] || "\u{1F310}";
3626
3881
  console.log(
3627
3882
  `
3628
- ${flag} ${chalk5.bold.yellow(lang.toUpperCase())} ${chalk5.gray(`(${voices.length} voices)`)}`
3883
+ ${flag} ${chalk4.bold.yellow(lang.toUpperCase())} ${chalk4.gray(`(${voices.length} voices)`)}`
3629
3884
  );
3630
- console.log(chalk5.gray("\u2500".repeat(80)));
3885
+ console.log(chalk4.gray("\u2500".repeat(80)));
3631
3886
  voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
3632
- const displayName = voice.displayName && voice.displayName !== voice.voiceId ? chalk5.gray(` (${voice.displayName})`) : "";
3887
+ const displayName = voice.displayName && voice.displayName !== voice.voiceId ? chalk4.gray(` (${voice.displayName})`) : "";
3633
3888
  console.log(
3634
- ` ${chalk5.cyan("\u25B8")} ${chalk5.bold.white(voice.voiceId)}${displayName}`
3889
+ ` ${chalk4.cyan("\u25B8")} ${chalk4.bold.white(voice.voiceId)}${displayName}`
3635
3890
  );
3636
3891
  if (voice.description) {
3637
3892
  const maxWidth = 76;
3638
3893
  const descriptionLines = wrapText(voice.description, maxWidth);
3639
3894
  descriptionLines.forEach((line) => {
3640
- console.log(` ${chalk5.gray(line)}`);
3895
+ console.log(` ${chalk4.gray(line)}`);
3641
3896
  });
3642
3897
  }
3643
3898
  });
@@ -3645,21 +3900,21 @@ ${flag} ${chalk5.bold.yellow(lang.toUpperCase())} ${chalk5.gray(`(${voices.leng
3645
3900
  console.log();
3646
3901
  }
3647
3902
  });
3648
- console.log("\n" + chalk5.gray("\u2500".repeat(80)));
3649
- console.log(chalk5.gray("Tips:"));
3903
+ console.log("\n" + chalk4.gray("\u2500".repeat(80)));
3904
+ console.log(chalk4.gray("Tips:"));
3650
3905
  console.log(
3651
- chalk5.gray(' \u2022 Use --filter "language=<code>" to filter by language')
3906
+ chalk4.gray(' \u2022 Use --filter "language=<code>" to filter by language')
3652
3907
  );
3653
3908
  console.log(
3654
- chalk5.gray(" \u2022 Use --compact for a simple list of voice IDs")
3909
+ chalk4.gray(" \u2022 Use --compact for a simple list of voice IDs")
3655
3910
  );
3656
- console.log(chalk5.gray(" \u2022 Use --json for machine-readable output"));
3911
+ console.log(chalk4.gray(" \u2022 Use --json for machine-readable output"));
3657
3912
  console.log(
3658
- chalk5.gray('\nExample: inworld tts list-voices --filter "language=en"')
3913
+ chalk4.gray('\nExample: inworld tts list-voices --filter "language=en"')
3659
3914
  );
3660
3915
  console.log();
3661
3916
  } catch (error) {
3662
- console.error(chalk5.red("\u274C Error listing voices:"), error);
3917
+ console.error(chalk4.red("\u274C Error listing voices:"), error);
3663
3918
  process.exit(1);
3664
3919
  }
3665
3920
  process.exit(0);
@@ -3679,14 +3934,14 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3679
3934
  ).option("--format <format>", "Audio format (MP3, LINEAR16, OGG_OPUS)", "MP3").option("--timestamps <type>", "Include timestamps (WORD or CHARACTER)").option("-j, --json", "Output response as JSON (includes base64 audio)").option("--stats", "Show request performance statistics").option("--stream", "Use streaming API for synthesis").action(async (text, options) => {
3680
3935
  try {
3681
3936
  if (text.length > 2e3) {
3682
- console.error(chalk5.red("\u274C Error: Text exceeds 2000 character limit"));
3683
- console.log(chalk5.gray(`Current length: ${text.length} characters`));
3937
+ console.error(chalk4.red("\u274C Error: Text exceeds 2000 character limit"));
3938
+ console.log(chalk4.gray(`Current length: ${text.length} characters`));
3684
3939
  process.exit(1);
3685
3940
  }
3686
3941
  const temperature = parseFloat(options.temperature);
3687
3942
  if (isNaN(temperature) || temperature < 0 || temperature > 2) {
3688
3943
  console.error(
3689
- chalk5.red("\u274C Error: Temperature must be between 0.0 and 2.0")
3944
+ chalk4.red("\u274C Error: Temperature must be between 0.0 and 2.0")
3690
3945
  );
3691
3946
  process.exit(1);
3692
3947
  }
@@ -3695,10 +3950,10 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3695
3950
  "inworld-tts-1-max": "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */
3696
3951
  };
3697
3952
  const modelId = modelMap[options.model] || "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */;
3698
- console.log(chalk5.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
3699
- console.log(chalk5.gray(`Voice: ${options.voice}`));
3700
- console.log(chalk5.gray(`Model: ${options.model}`));
3701
- console.log(chalk5.gray(`Text length: ${text.length} characters`));
3953
+ console.log(chalk4.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
3954
+ console.log(chalk4.gray(`Voice: ${options.voice}`));
3955
+ console.log(chalk4.gray(`Model: ${options.model}`));
3956
+ console.log(chalk4.gray(`Text length: ${text.length} characters`));
3702
3957
  const request = {
3703
3958
  text,
3704
3959
  voiceId: options.voice,
@@ -3721,15 +3976,15 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3721
3976
  fileExtension = ".wav";
3722
3977
  if (options.format === "MP3") {
3723
3978
  console.log(
3724
- chalk5.yellow(
3979
+ chalk4.yellow(
3725
3980
  "\u26A0\uFE0F Warning: MP3 streaming requires special handling."
3726
3981
  )
3727
3982
  );
3728
3983
  console.log(
3729
- chalk5.yellow(" Audio chunks may not concatenate perfectly.")
3984
+ chalk4.yellow(" Audio chunks may not concatenate perfectly.")
3730
3985
  );
3731
3986
  console.log(
3732
- chalk5.yellow(
3987
+ chalk4.yellow(
3733
3988
  " Consider using LINEAR16 or OGG_OPUS for better streaming."
3734
3989
  )
3735
3990
  );
@@ -3742,8 +3997,8 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3742
3997
  streamFormat = "LINEAR16";
3743
3998
  fileExtension = ".wav";
3744
3999
  }
3745
- console.log(chalk5.cyan("\u{1F504} Using streaming synthesis..."));
3746
- console.log(chalk5.gray(`Format: ${streamFormat}${fileExtension}`));
4000
+ console.log(chalk4.cyan("\u{1F504} Using streaming synthesis..."));
4001
+ console.log(chalk4.gray(`Format: ${streamFormat}${fileExtension}`));
3747
4002
  const streamRequest = {
3748
4003
  ...request,
3749
4004
  audioConfig: {
@@ -3773,7 +4028,7 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3773
4028
  if (chunk.error) {
3774
4029
  streamError = chunk.error;
3775
4030
  console.error(
3776
- chalk5.red(`\u274C Stream error: ${chunk.error.message}`)
4031
+ chalk4.red(`\u274C Stream error: ${chunk.error.message}`)
3777
4032
  );
3778
4033
  } else {
3779
4034
  if (chunk.audioContent) {
@@ -3798,7 +4053,7 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3798
4053
  if (!options.json && !options.stats) {
3799
4054
  const chunkSizeKB = (chunkBuffer.length / 1024).toFixed(2);
3800
4055
  process.stdout.write(
3801
- chalk5.gray(
4056
+ chalk4.gray(
3802
4057
  `\rReceived chunk ${chunkCount} (${chunkSizeKB} KB)...`
3803
4058
  )
3804
4059
  );
@@ -3880,30 +4135,30 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3880
4135
  options.output || `output${fileExtension}`
3881
4136
  );
3882
4137
  await writeFile(outputPath, audioBuffer);
3883
- console.log(chalk5.green(`\u2705 Audio saved to: ${outputPath}`));
4138
+ console.log(chalk4.green(`\u2705 Audio saved to: ${outputPath}`));
3884
4139
  console.log(
3885
- chalk5.gray(
4140
+ chalk4.gray(
3886
4141
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
3887
4142
  )
3888
4143
  );
3889
- console.log(chalk5.gray(`Chunks received: ${chunkCount}`));
4144
+ console.log(chalk4.gray(`Chunks received: ${chunkCount}`));
3890
4145
  if (allWordAlignments.words.length > 0) {
3891
4146
  console.log(
3892
- chalk5.gray(
4147
+ chalk4.gray(
3893
4148
  `Word timestamps collected: ${allWordAlignments.words.length}`
3894
4149
  )
3895
4150
  );
3896
4151
  }
3897
4152
  if (allCharacterAlignments.characters.length > 0) {
3898
4153
  console.log(
3899
- chalk5.gray(
4154
+ chalk4.gray(
3900
4155
  `Character timestamps collected: ${allCharacterAlignments.characters.length}`
3901
4156
  )
3902
4157
  );
3903
4158
  }
3904
4159
  }
3905
4160
  } else {
3906
- console.log(chalk5.gray(`Format: ${options.format || "MP3 (default)"}`));
4161
+ console.log(chalk4.gray(`Format: ${options.format || "MP3 (default)"}`));
3907
4162
  if (options.format === "LINEAR16") {
3908
4163
  fileExtension = ".wav";
3909
4164
  } else if (options.format === "OGG_OPUS") {
@@ -3922,9 +4177,9 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3922
4177
  options.output || `output${fileExtension}`
3923
4178
  );
3924
4179
  await writeFile(outputPath, audioBuffer);
3925
- console.log(chalk5.green(`\u2705 Audio saved to: ${outputPath}`));
4180
+ console.log(chalk4.green(`\u2705 Audio saved to: ${outputPath}`));
3926
4181
  console.log(
3927
- chalk5.gray(
4182
+ chalk4.gray(
3928
4183
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
3929
4184
  )
3930
4185
  );
@@ -3940,25 +4195,25 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3940
4195
  if (isStreaming) {
3941
4196
  const sm = m;
3942
4197
  console.log(
3943
- "\n" + chalk5.cyan("\u{1F4CA} Streaming Performance Statistics:")
4198
+ "\n" + chalk4.cyan("\u{1F4CA} Streaming Performance Statistics:")
3944
4199
  );
3945
- console.log(chalk5.gray("\u2550".repeat(50)));
3946
- console.log(chalk5.bold.white("\n Streaming Timeline:"));
3947
- console.log(chalk5.gray(" \u2500".repeat(23)));
4200
+ console.log(chalk4.gray("\u2550".repeat(50)));
4201
+ console.log(chalk4.bold.white("\n Streaming Timeline:"));
4202
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3948
4203
  console.log(
3949
- chalk5.white(" \u23F1\uFE0F Time to First Chunk: ") + chalk5.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
4204
+ chalk4.white(" \u23F1\uFE0F Time to First Chunk: ") + chalk4.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
3950
4205
  );
3951
4206
  console.log(
3952
- chalk5.white(" \u23F2\uFE0F Total Stream Time: ") + chalk5.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
4207
+ chalk4.white(" \u23F2\uFE0F Total Stream Time: ") + chalk4.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
3953
4208
  );
3954
- console.log(chalk5.bold.white("\n Chunk Statistics:"));
3955
- console.log(chalk5.gray(" \u2500".repeat(23)));
4209
+ console.log(chalk4.bold.white("\n Chunk Statistics:"));
4210
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3956
4211
  console.log(
3957
- chalk5.white(" \u{1F4E6} Chunks Received: ") + chalk5.yellow(`${sm.chunksReceived}`)
4212
+ chalk4.white(" \u{1F4E6} Chunks Received: ") + chalk4.yellow(`${sm.chunksReceived}`)
3958
4213
  );
3959
4214
  if (sm.errorChunks > 0) {
3960
4215
  console.log(
3961
- chalk5.white(" \u26A0\uFE0F Error Chunks: ") + chalk5.red(`${sm.errorChunks}`)
4216
+ chalk4.white(" \u26A0\uFE0F Error Chunks: ") + chalk4.red(`${sm.errorChunks}`)
3962
4217
  );
3963
4218
  }
3964
4219
  if (sm.chunkSizes.length > 0) {
@@ -3966,10 +4221,10 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3966
4221
  const minChunkSize = Math.min(...sm.chunkSizes);
3967
4222
  const maxChunkSize = Math.max(...sm.chunkSizes);
3968
4223
  console.log(
3969
- chalk5.white(" \u{1F4CF} Avg Chunk Size: ") + chalk5.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
4224
+ chalk4.white(" \u{1F4CF} Avg Chunk Size: ") + chalk4.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
3970
4225
  );
3971
4226
  console.log(
3972
- chalk5.gray(" Min/Max: ") + chalk5.gray(
4227
+ chalk4.gray(" Min/Max: ") + chalk4.gray(
3973
4228
  `${(minChunkSize / 1024).toFixed(2)} - ${(maxChunkSize / 1024).toFixed(2)} KB`
3974
4229
  )
3975
4230
  );
@@ -3979,116 +4234,116 @@ var synthesizeCommand = new Command20("synthesize").description("Synthesize text
3979
4234
  const minInterval = Math.min(...sm.chunkIntervals);
3980
4235
  const maxInterval = Math.max(...sm.chunkIntervals);
3981
4236
  console.log(
3982
- chalk5.white(" \u23F3 Avg Chunk Interval: ") + chalk5.yellow(`${avgInterval.toFixed(0)} ms`)
4237
+ chalk4.white(" \u23F3 Avg Chunk Interval: ") + chalk4.yellow(`${avgInterval.toFixed(0)} ms`)
3983
4238
  );
3984
4239
  console.log(
3985
- chalk5.gray(" Min/Max: ") + chalk5.gray(
4240
+ chalk4.gray(" Min/Max: ") + chalk4.gray(
3986
4241
  `${minInterval.toFixed(0)} - ${maxInterval.toFixed(0)} ms`
3987
4242
  )
3988
4243
  );
3989
4244
  }
3990
- console.log(chalk5.bold.white("\n Data Transfer:"));
3991
- console.log(chalk5.gray(" \u2500".repeat(23)));
4245
+ console.log(chalk4.bold.white("\n Data Transfer:"));
4246
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3992
4247
  console.log(
3993
- chalk5.white(" \u{1F4E5} Total Data: ") + chalk5.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
4248
+ chalk4.white(" \u{1F4E5} Total Data: ") + chalk4.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
3994
4249
  );
3995
4250
  console.log(
3996
- chalk5.white(" \u{1F3B5} Audio File: ") + chalk5.yellow(
4251
+ chalk4.white(" \u{1F3B5} Audio File: ") + chalk4.yellow(
3997
4252
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
3998
4253
  )
3999
4254
  );
4000
- console.log(chalk5.bold.white("\n Performance Metrics:"));
4001
- console.log(chalk5.gray(" \u2500".repeat(23)));
4255
+ console.log(chalk4.bold.white("\n Performance Metrics:"));
4256
+ console.log(chalk4.gray(" \u2500".repeat(23)));
4002
4257
  const throughputKBps = sm.totalBytes / 1024 / (sm.totalTime / 1e3);
4003
4258
  console.log(
4004
- chalk5.white(" \u{1F4F6} Stream Throughput: ") + chalk5.yellow(`${throughputKBps.toFixed(2)} KB/s`)
4259
+ chalk4.white(" \u{1F4F6} Stream Throughput: ") + chalk4.yellow(`${throughputKBps.toFixed(2)} KB/s`)
4005
4260
  );
4006
4261
  const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
4007
4262
  const realTimeRatio = audioDuration / (sm.totalTime / 1e3);
4008
4263
  console.log(
4009
- chalk5.white(" \u{1F3B5} Audio Duration: ") + chalk5.yellow(`${audioDuration.toFixed(2)} seconds`)
4264
+ chalk4.white(" \u{1F3B5} Audio Duration: ") + chalk4.yellow(`${audioDuration.toFixed(2)} seconds`)
4010
4265
  );
4011
4266
  console.log(
4012
- chalk5.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk5.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk5.yellow(`${realTimeRatio.toFixed(2)}x`))
4267
+ chalk4.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk4.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk4.yellow(`${realTimeRatio.toFixed(2)}x`))
4013
4268
  );
4014
4269
  const streamingEfficiency = (sm.totalTime - sm.timeToFirstChunk) / sm.totalTime * 100;
4015
4270
  console.log(
4016
- chalk5.white(" \u{1F4C8} Stream Efficiency: ") + chalk5.yellow(`${streamingEfficiency.toFixed(1)}%`)
4271
+ chalk4.white(" \u{1F4C8} Stream Efficiency: ") + chalk4.yellow(`${streamingEfficiency.toFixed(1)}%`)
4017
4272
  );
4018
- console.log(chalk5.gray("\u2550".repeat(50)));
4273
+ console.log(chalk4.gray("\u2550".repeat(50)));
4019
4274
  } else {
4020
- console.log("\n" + chalk5.cyan("\u{1F4CA} Performance Statistics:"));
4021
- console.log(chalk5.gray("\u2550".repeat(50)));
4022
- console.log(chalk5.bold.white("\n Network Timing:"));
4023
- console.log(chalk5.gray(" \u2500".repeat(23)));
4275
+ console.log("\n" + chalk4.cyan("\u{1F4CA} Performance Statistics:"));
4276
+ console.log(chalk4.gray("\u2550".repeat(50)));
4277
+ console.log(chalk4.bold.white("\n Network Timing:"));
4278
+ console.log(chalk4.gray(" \u2500".repeat(23)));
4024
4279
  console.log(
4025
- chalk5.white(" \u23F1\uFE0F Time to First Byte: ") + chalk5.yellow(`${m.ttfb.toFixed(0)} ms`)
4280
+ chalk4.white(" \u23F1\uFE0F Time to First Byte: ") + chalk4.yellow(`${m.ttfb.toFixed(0)} ms`)
4026
4281
  );
4027
4282
  if (m.downloadTime !== void 0) {
4028
4283
  console.log(
4029
- chalk5.white(" \u2B07\uFE0F Content Download: ") + chalk5.yellow(`${m.downloadTime.toFixed(0)} ms`)
4284
+ chalk4.white(" \u2B07\uFE0F Content Download: ") + chalk4.yellow(`${m.downloadTime.toFixed(0)} ms`)
4030
4285
  );
4031
4286
  }
4032
4287
  console.log(
4033
- chalk5.white(" \u23F2\uFE0F Total Time: ") + chalk5.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
4288
+ chalk4.white(" \u23F2\uFE0F Total Time: ") + chalk4.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
4034
4289
  );
4035
- console.log(chalk5.bold.white("\n Data Transfer:"));
4036
- console.log(chalk5.gray(" \u2500".repeat(23)));
4290
+ console.log(chalk4.bold.white("\n Data Transfer:"));
4291
+ console.log(chalk4.gray(" \u2500".repeat(23)));
4037
4292
  if (m.requestSize) {
4038
4293
  console.log(
4039
- chalk5.white(" \u2B06\uFE0F Request Size: ") + chalk5.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
4294
+ chalk4.white(" \u2B06\uFE0F Request Size: ") + chalk4.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
4040
4295
  );
4041
4296
  }
4042
4297
  console.log(
4043
- chalk5.white(" \u2B07\uFE0F Response Size: ") + chalk5.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
4298
+ chalk4.white(" \u2B07\uFE0F Response Size: ") + chalk4.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
4044
4299
  );
4045
4300
  console.log(
4046
- chalk5.white(" \u{1F3B5} Audio File: ") + chalk5.yellow(
4301
+ chalk4.white(" \u{1F3B5} Audio File: ") + chalk4.yellow(
4047
4302
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
4048
4303
  )
4049
4304
  );
4050
- console.log(chalk5.bold.white("\n Performance Metrics:"));
4051
- console.log(chalk5.gray(" \u2500".repeat(23)));
4305
+ console.log(chalk4.bold.white("\n Performance Metrics:"));
4306
+ console.log(chalk4.gray(" \u2500".repeat(23)));
4052
4307
  const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
4053
4308
  const realTimeRatio = audioDuration / (m.totalTime / 1e3);
4054
4309
  const serverTime = m.ttfb;
4055
4310
  console.log(
4056
- chalk5.white(" \u{1F5A5}\uFE0F Server Processing: ") + chalk5.yellow(`${Math.max(0, serverTime).toFixed(0)} ms`)
4311
+ chalk4.white(" \u{1F5A5}\uFE0F Server Processing: ") + chalk4.yellow(`${Math.max(0, serverTime).toFixed(0)} ms`)
4057
4312
  );
4058
4313
  console.log(
4059
- chalk5.white(" \u{1F3B5} Audio Duration: ") + chalk5.yellow(`${audioDuration.toFixed(2)} seconds`)
4314
+ chalk4.white(" \u{1F3B5} Audio Duration: ") + chalk4.yellow(`${audioDuration.toFixed(2)} seconds`)
4060
4315
  );
4061
4316
  console.log(
4062
- chalk5.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk5.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk5.yellow(`${realTimeRatio.toFixed(2)}x`))
4317
+ chalk4.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk4.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk4.yellow(`${realTimeRatio.toFixed(2)}x`))
4063
4318
  );
4064
4319
  const throughputMbps = (m.responseSize + (audioBuffer?.length || 0)) * 8 / (m.totalTime * 1e3);
4065
4320
  console.log(
4066
- chalk5.white(" \u{1F4F6} Throughput: ") + chalk5.yellow(`${throughputMbps.toFixed(2)} Mbps`)
4321
+ chalk4.white(" \u{1F4F6} Throughput: ") + chalk4.yellow(`${throughputMbps.toFixed(2)} Mbps`)
4067
4322
  );
4068
- console.log(chalk5.gray("\u2550".repeat(50)));
4323
+ console.log(chalk4.gray("\u2550".repeat(50)));
4069
4324
  }
4070
4325
  }
4071
4326
  if (response.timestampInfo?.wordAlignment) {
4072
4327
  const alignment = response.timestampInfo.wordAlignment;
4073
- console.log("\n" + chalk5.cyan("\u{1F4DD} Word Timestamps:"));
4328
+ console.log("\n" + chalk4.cyan("\u{1F4DD} Word Timestamps:"));
4074
4329
  alignment.words.forEach((word, i) => {
4075
4330
  const start = alignment.wordStartTimeSeconds[i].toFixed(3);
4076
4331
  const end = alignment.wordEndTimeSeconds[i].toFixed(3);
4077
- console.log(chalk5.gray(` ${start}s - ${end}s: ${word}`));
4332
+ console.log(chalk4.gray(` ${start}s - ${end}s: ${word}`));
4078
4333
  });
4079
4334
  }
4080
4335
  if (response.timestampInfo?.characterAlignment) {
4081
- console.log("\n" + chalk5.cyan("\u{1F4DD} Character Timestamps:"));
4336
+ console.log("\n" + chalk4.cyan("\u{1F4DD} Character Timestamps:"));
4082
4337
  console.log(
4083
- chalk5.gray(
4338
+ chalk4.gray(
4084
4339
  " (Too detailed to display - use --json to see full data)"
4085
4340
  )
4086
4341
  );
4087
4342
  }
4088
4343
  process.exit(0);
4089
4344
  } catch (error) {
4090
- console.error(chalk5.red("\u274C Error synthesizing speech:"));
4091
- console.error(chalk5.red(error.message || error));
4345
+ console.error(chalk4.red("\u274C Error synthesizing speech:"));
4346
+ console.error(chalk4.red(error.message || error));
4092
4347
  process.exit(1);
4093
4348
  }
4094
4349
  });
@@ -4162,7 +4417,7 @@ var UpdateChecker = class _UpdateChecker {
4162
4417
  if (shouldUpdate) {
4163
4418
  this.displayUpdateNotification(latestVersion);
4164
4419
  }
4165
- } catch (error) {
4420
+ } catch (_error) {
4166
4421
  }
4167
4422
  }
4168
4423
  /**
@@ -4200,7 +4455,7 @@ var UpdateChecker = class _UpdateChecker {
4200
4455
  }
4201
4456
  const data = await response.json();
4202
4457
  return data.version || null;
4203
- } catch (error) {
4458
+ } catch (_error) {
4204
4459
  return null;
4205
4460
  }
4206
4461
  }
@@ -4216,7 +4471,7 @@ var UpdateChecker = class _UpdateChecker {
4216
4471
  return false;
4217
4472
  }
4218
4473
  return semver.gt(latestClean, currentClean);
4219
- } catch (error) {
4474
+ } catch (_error) {
4220
4475
  return false;
4221
4476
  }
4222
4477
  }
@@ -4325,7 +4580,7 @@ var InworldCLI = class {
4325
4580
  analytics.trackCommandResult(this.currentCommand, false, errorMessage);
4326
4581
  }
4327
4582
  console.error(
4328
- chalk6.red("Error:"),
4583
+ chalk5.red("Error:"),
4329
4584
  error instanceof Error ? error.message : String(error)
4330
4585
  );
4331
4586
  await analytics.flush();
@@ -4335,6 +4590,6 @@ var InworldCLI = class {
4335
4590
  };
4336
4591
  var cli = new InworldCLI();
4337
4592
  cli.run().catch((error) => {
4338
- console.error(chalk6.red("Fatal error:"), error);
4593
+ console.error(chalk5.red("Fatal error:"), error);
4339
4594
  process.exit(1);
4340
4595
  });