@inworld/cli 0.2.15 → 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.
Files changed (225) hide show
  1. package/dist/index.js +1246 -544
  2. package/dist/index.js.map +4 -4
  3. package/dist/package.json +49 -0
  4. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.d.ts +10 -0
  5. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.d.ts.map +1 -0
  6. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.js +16 -0
  7. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.js.map +1 -0
  8. package/dist/proto/generated/portal/ai/inworld/studio/v1/errors.pb.d.ts +13 -0
  9. package/dist/proto/generated/portal/ai/inworld/studio/v1/errors.pb.d.ts.map +1 -0
  10. package/dist/proto/generated/portal/ai/inworld/studio/v1/errors.pb.js +2 -0
  11. package/dist/proto/generated/portal/ai/inworld/studio/v1/errors.pb.js.map +1 -0
  12. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.d.ts +7 -0
  13. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.d.ts.map +1 -0
  14. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.js +15 -0
  15. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.js.map +1 -0
  16. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.d.ts +14 -0
  17. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.d.ts.map +1 -0
  18. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.js +7 -0
  19. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.js.map +1 -0
  20. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.d.ts +116 -0
  21. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.d.ts.map +1 -0
  22. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.js +71 -0
  23. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.js.map +1 -0
  24. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.d.ts +14 -0
  25. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.d.ts.map +1 -0
  26. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.js +7 -0
  27. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.js.map +1 -0
  28. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.d.ts +76 -0
  29. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.d.ts.map +1 -0
  30. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.js +40 -0
  31. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.js.map +1 -0
  32. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.d.ts +10 -0
  33. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.d.ts.map +1 -0
  34. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.js +7 -0
  35. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.js.map +1 -0
  36. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.d.ts +7 -0
  37. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.d.ts.map +1 -0
  38. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.js +13 -0
  39. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.js.map +1 -0
  40. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.d.ts +115 -0
  41. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.d.ts.map +1 -0
  42. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.js +86 -0
  43. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.js.map +1 -0
  44. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.d.ts +255 -0
  45. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.d.ts.map +1 -0
  46. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.js +88 -0
  47. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.js.map +1 -0
  48. package/dist/proto/generated/portal/fetch.pb.d.ts +26 -0
  49. package/dist/proto/generated/portal/fetch.pb.d.ts.map +1 -0
  50. package/dist/proto/generated/portal/fetch.pb.js +274 -0
  51. package/dist/proto/generated/portal/fetch.pb.js.map +1 -0
  52. package/dist/src/auth/callback_server.d.ts +41 -0
  53. package/dist/src/auth/callback_server.d.ts.map +1 -0
  54. package/dist/src/auth/callback_server.js +136 -0
  55. package/dist/src/auth/callback_server.js.map +1 -0
  56. package/dist/src/auth/manager.d.ts +97 -0
  57. package/dist/src/auth/manager.d.ts.map +1 -0
  58. package/dist/src/auth/manager.js +340 -0
  59. package/dist/src/auth/manager.js.map +1 -0
  60. package/dist/src/auth/utils.d.ts +45 -0
  61. package/dist/src/auth/utils.d.ts.map +1 -0
  62. package/dist/src/auth/utils.js +183 -0
  63. package/dist/src/auth/utils.js.map +1 -0
  64. package/dist/src/commands/auth/disable_telemetry_command.d.ts +3 -0
  65. package/dist/src/commands/auth/disable_telemetry_command.d.ts.map +1 -0
  66. package/dist/src/commands/auth/enable_telemetry_command.d.ts +3 -0
  67. package/dist/src/commands/auth/enable_telemetry_command.d.ts.map +1 -0
  68. package/dist/src/commands/auth/login_ci_command.d.ts +3 -0
  69. package/dist/src/commands/auth/login_ci_command.d.ts.map +1 -0
  70. package/dist/src/commands/auth/login_ci_command.js +41 -0
  71. package/dist/src/commands/auth/login_ci_command.js.map +1 -0
  72. package/dist/src/commands/auth/login_command.d.ts +4 -0
  73. package/dist/src/commands/auth/login_command.d.ts.map +1 -0
  74. package/dist/src/commands/auth/login_command.js +134 -0
  75. package/dist/src/commands/auth/login_command.js.map +1 -0
  76. package/dist/src/commands/auth/logout_command.d.ts +4 -0
  77. package/dist/src/commands/auth/logout_command.d.ts.map +1 -0
  78. package/dist/src/commands/auth/logout_command.js +54 -0
  79. package/dist/src/commands/auth/logout_command.js.map +1 -0
  80. package/dist/src/commands/auth/print_access_token_command.d.ts +3 -0
  81. package/dist/src/commands/auth/print_access_token_command.d.ts.map +1 -0
  82. package/dist/src/commands/auth/print_access_token_command.js +21 -0
  83. package/dist/src/commands/auth/print_access_token_command.js.map +1 -0
  84. package/dist/src/commands/auth/print_api_key_command.d.ts +3 -0
  85. package/dist/src/commands/auth/print_api_key_command.d.ts.map +1 -0
  86. package/dist/src/commands/auth/print_api_key_command.js +26 -0
  87. package/dist/src/commands/auth/print_api_key_command.js.map +1 -0
  88. package/dist/src/commands/auth/status_command.d.ts +4 -0
  89. package/dist/src/commands/auth/status_command.d.ts.map +1 -0
  90. package/dist/src/commands/auth/status_command.js +84 -0
  91. package/dist/src/commands/auth/status_command.js.map +1 -0
  92. package/dist/src/commands/auth_command.d.ts +3 -0
  93. package/dist/src/commands/auth_command.d.ts.map +1 -0
  94. package/dist/src/commands/auth_command.js +20 -0
  95. package/dist/src/commands/auth_command.js.map +1 -0
  96. package/dist/src/commands/graph/graph_deploy_command.d.ts +24 -0
  97. package/dist/src/commands/graph/graph_deploy_command.d.ts.map +1 -0
  98. package/dist/src/commands/graph/graph_deploy_command.js +191 -0
  99. package/dist/src/commands/graph/graph_deploy_command.js.map +1 -0
  100. package/dist/src/commands/graph/graph_init_command.d.ts +4 -0
  101. package/dist/src/commands/graph/graph_init_command.d.ts.map +1 -0
  102. package/dist/src/commands/graph/graph_init_command.js +376 -0
  103. package/dist/src/commands/graph/graph_init_command.js.map +1 -0
  104. package/dist/src/commands/graph/graph_run_command.d.ts +24 -0
  105. package/dist/src/commands/graph/graph_run_command.d.ts.map +1 -0
  106. package/dist/src/commands/graph/graph_run_command.js +50 -0
  107. package/dist/src/commands/graph/graph_run_command.js.map +1 -0
  108. package/dist/src/commands/graph/graph_serve_command.d.ts +4 -0
  109. package/dist/src/commands/graph/graph_serve_command.d.ts.map +1 -0
  110. package/dist/src/commands/graph/graph_serve_command.js +40 -0
  111. package/dist/src/commands/graph/graph_serve_command.js.map +1 -0
  112. package/dist/src/commands/graph/graph_variant_command.d.ts +3 -0
  113. package/dist/src/commands/graph/graph_variant_command.d.ts.map +1 -0
  114. package/dist/src/commands/graph/graph_variant_command.js +13 -0
  115. package/dist/src/commands/graph/graph_variant_command.js.map +1 -0
  116. package/dist/src/commands/graph/graph_visualize_command.d.ts +7 -0
  117. package/dist/src/commands/graph/graph_visualize_command.d.ts.map +1 -0
  118. package/dist/src/commands/graph/graph_visualize_command.js +35 -0
  119. package/dist/src/commands/graph/graph_visualize_command.js.map +1 -0
  120. package/dist/src/commands/graph/variant/graph_variant_list_command.d.ts +3 -0
  121. package/dist/src/commands/graph/variant/graph_variant_list_command.d.ts.map +1 -0
  122. package/dist/src/commands/graph/variant/graph_variant_list_command.js +25 -0
  123. package/dist/src/commands/graph/variant/graph_variant_list_command.js.map +1 -0
  124. package/dist/src/commands/graph/variant/graph_variant_print_command.d.ts +7 -0
  125. package/dist/src/commands/graph/variant/graph_variant_print_command.d.ts.map +1 -0
  126. package/dist/src/commands/graph/variant/graph_variant_print_command.js +45 -0
  127. package/dist/src/commands/graph/variant/graph_variant_print_command.js.map +1 -0
  128. package/dist/src/commands/graph/variant/graph_variant_register_command.d.ts +3 -0
  129. package/dist/src/commands/graph/variant/graph_variant_register_command.d.ts.map +1 -0
  130. package/dist/src/commands/graph/variant/graph_variant_register_command.js +45 -0
  131. package/dist/src/commands/graph/variant/graph_variant_register_command.js.map +1 -0
  132. package/dist/src/commands/graph_command.d.ts +3 -0
  133. package/dist/src/commands/graph_command.d.ts.map +1 -0
  134. package/dist/src/commands/graph_command.js +20 -0
  135. package/dist/src/commands/graph_command.js.map +1 -0
  136. package/dist/src/commands/tts_commands.d.ts +17 -0
  137. package/dist/src/commands/tts_commands.d.ts.map +1 -0
  138. package/dist/src/commands/tts_commands.js +568 -0
  139. package/dist/src/commands/tts_commands.js.map +1 -0
  140. package/dist/src/commands/workspace_command.d.ts +12 -0
  141. package/dist/src/commands/workspace_command.d.ts.map +1 -0
  142. package/dist/src/commands/workspace_command.js +33 -0
  143. package/dist/src/commands/workspace_command.js.map +1 -0
  144. package/dist/src/constants.d.ts +10 -0
  145. package/dist/src/constants.d.ts.map +1 -0
  146. package/dist/src/constants.js +30 -0
  147. package/dist/src/constants.js.map +1 -0
  148. package/dist/src/grpc/core/InworldError.d.ts +30 -0
  149. package/dist/src/grpc/core/InworldError.d.ts.map +1 -0
  150. package/dist/src/grpc/core/InworldError.js +46 -0
  151. package/dist/src/grpc/core/InworldError.js.map +1 -0
  152. package/dist/src/grpc/core/statusCodes.d.ts +122 -0
  153. package/dist/src/grpc/core/statusCodes.d.ts.map +1 -0
  154. package/dist/src/grpc/core/statusCodes.js +133 -0
  155. package/dist/src/grpc/core/statusCodes.js.map +1 -0
  156. package/dist/src/index.d.ts +2 -0
  157. package/dist/src/index.d.ts.map +1 -0
  158. package/dist/src/services/analytics.d.ts +45 -0
  159. package/dist/src/services/analytics.d.ts.map +1 -0
  160. package/dist/src/services/deploy_service.d.ts +4 -0
  161. package/dist/src/services/deploy_service.d.ts.map +1 -0
  162. package/dist/src/services/deploy_service.js +128 -0
  163. package/dist/src/services/deploy_service.js.map +1 -0
  164. package/dist/src/services/graph_loader.d.ts +7 -0
  165. package/dist/src/services/graph_loader.d.ts.map +1 -0
  166. package/dist/src/services/graph_loader.js +103 -0
  167. package/dist/src/services/graph_loader.js.map +1 -0
  168. package/dist/src/services/graph_variant_service.d.ts +12 -0
  169. package/dist/src/services/graph_variant_service.d.ts.map +1 -0
  170. package/dist/src/services/graph_variant_service.js +66 -0
  171. package/dist/src/services/graph_variant_service.js.map +1 -0
  172. package/dist/src/services/tts_service.d.ts +273 -0
  173. package/dist/src/services/tts_service.d.ts.map +1 -0
  174. package/dist/src/services/tts_service.js +299 -0
  175. package/dist/src/services/tts_service.js.map +1 -0
  176. package/dist/src/services/update_checker.d.ts +37 -0
  177. package/dist/src/services/update_checker.d.ts.map +1 -0
  178. package/dist/src/services/workspace_service.d.ts +47 -0
  179. package/dist/src/services/workspace_service.d.ts.map +1 -0
  180. package/dist/src/services/workspace_service.js +222 -0
  181. package/dist/src/services/workspace_service.js.map +1 -0
  182. package/dist/src/templates/llm_tts/graph.d.ts +2 -0
  183. package/dist/src/templates/llm_tts/graph.d.ts.map +1 -0
  184. package/dist/src/utils/array.d.ts +2 -0
  185. package/dist/src/utils/array.d.ts.map +1 -0
  186. package/dist/src/utils/array.js +4 -0
  187. package/dist/src/utils/array.js.map +1 -0
  188. package/dist/src/utils/confirm.d.ts +62 -0
  189. package/dist/src/utils/confirm.d.ts.map +1 -0
  190. package/dist/src/utils/confirm.js +90 -0
  191. package/dist/src/utils/confirm.js.map +1 -0
  192. package/dist/src/utils/long_running_operations.d.ts +38 -0
  193. package/dist/src/utils/long_running_operations.d.ts.map +1 -0
  194. package/dist/src/utils/long_running_operations.js +62 -0
  195. package/dist/src/utils/long_running_operations.js.map +1 -0
  196. package/dist/src/utils/resource_name_helper.d.ts +12 -0
  197. package/dist/src/utils/resource_name_helper.d.ts.map +1 -0
  198. package/dist/src/utils/resource_name_helper.js +29 -0
  199. package/dist/src/utils/resource_name_helper.js.map +1 -0
  200. package/dist/src/utils/selector.d.ts +62 -0
  201. package/dist/src/utils/selector.d.ts.map +1 -0
  202. package/dist/src/utils/selector.js +77 -0
  203. package/dist/src/utils/selector.js.map +1 -0
  204. package/dist/src/utils/spinner.d.ts +75 -0
  205. package/dist/src/utils/spinner.d.ts.map +1 -0
  206. package/dist/src/utils/spinner.js +178 -0
  207. package/dist/src/utils/spinner.js.map +1 -0
  208. package/dist/src/utils/ui.d.ts +27 -0
  209. package/dist/src/utils/ui.d.ts.map +1 -0
  210. package/dist/src/utils/ui.js +83 -0
  211. package/dist/src/utils/ui.js.map +1 -0
  212. package/dist/templates/llm_tts/graph.ts +8 -9
  213. package/package.json +5 -4
  214. package/dist/src/templates/simple/README.md +0 -106
  215. package/dist/src/templates/simple/graph.ts +0 -32
  216. package/dist/src/templates/simple/metadata.json +0 -26
  217. package/dist/templates/simple/README.md +0 -106
  218. package/dist/templates/simple/graph.ts +0 -32
  219. package/dist/templates/simple/metadata.json +0 -26
  220. package/src/templates/llm_tts/README.md +0 -155
  221. package/src/templates/llm_tts/graph.ts +0 -30
  222. package/src/templates/llm_tts/metadata.json +0 -41
  223. package/src/templates/simple/README.md +0 -106
  224. package/src/templates/simple/graph.ts +0 -32
  225. package/src/templates/simple/metadata.json +0 -26
package/dist/index.js CHANGED
@@ -1,20 +1,68 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
 
4
- // index.ts
5
- import chalk14 from "chalk";
6
- import { Command as Command19 } from "commander";
4
+ // src/index.ts
5
+ import chalk5 from "chalk";
6
+ import { Command as Command22 } from "commander";
7
7
 
8
8
  // src/commands/auth/login_command.ts
9
- import chalk3 from "chalk";
10
9
  import { exec } from "child_process";
11
10
  import { Command } from "commander";
12
- import * as readline2 from "readline";
11
+ import * as readline3 from "readline";
13
12
  import { promisify } from "util";
14
13
 
15
- // src/auth/callback-server.ts
14
+ // src/auth/callback_server.ts
16
15
  import * as http from "http";
17
16
 
17
+ // package.json
18
+ var package_default = {
19
+ name: "@inworld/cli",
20
+ version: "0.3.0-rc.5",
21
+ type: "module",
22
+ main: "dist/index.js",
23
+ bin: {
24
+ inworld: "dist/index.js"
25
+ },
26
+ scripts: {
27
+ build: "node esbuild.config.js",
28
+ "build:tsc": "tsc --project tsconfig.json",
29
+ "build:types": "tsc --emitDeclarationOnly",
30
+ "build:all": "npm run build && npm run build:types",
31
+ start: "node dist/index.js",
32
+ dev: "tsx src/index.ts"
33
+ },
34
+ files: [
35
+ "dist/**/*"
36
+ ],
37
+ author: "Inworld AI",
38
+ license: "MIT",
39
+ description: "Inworld CLI",
40
+ devDependencies: {
41
+ "@tsconfig/node-lts": "^22.0.2",
42
+ "@types/archiver": "^6.0.3",
43
+ "@types/express": "^5.0.3",
44
+ "@types/keytar": "^4.4.0",
45
+ "@types/node": "^24.1.0",
46
+ "@types/ora": "^3.1.0",
47
+ "@types/semver": "^7.5.8"
48
+ },
49
+ dependencies: {
50
+ "@zowe/secrets-for-zowe-sdk": "^8.27.0",
51
+ "adm-zip": "^0.5.16",
52
+ archiver: "^7.0.1",
53
+ chalk: "^5.3.0",
54
+ commander: "^12.0.0",
55
+ conf: "^14.0.0",
56
+ esbuild: "^0.25.10",
57
+ "jwt-decode": "^4.0.0",
58
+ mixpanel: "^0.18.1",
59
+ ora: "^8.2.0",
60
+ semver: "^7.6.3",
61
+ tsx: "^4.20.5",
62
+ typescript: "^5.8.3"
63
+ }
64
+ };
65
+
18
66
  // src/constants.ts
19
67
  var DEFAULT_PLATFORM_ENDPOINT = "https://platform.inworld.ai";
20
68
  var resolvePlatformUrl = () => {
@@ -42,16 +90,37 @@ var INWORLD_CLI_AUTH_CALLBACK_PORT = parseInt(
42
90
  process.env.INWORLD_CLI_AUTH_CALLBACK_PORT || "8085",
43
91
  10
44
92
  );
45
- var RUNTIME_VERSION = "0.6.3";
46
- var CLI_VERSION = "0.2.15";
93
+ var MIXPANEL_TOKEN = process.env.INWORLD_MIXPANEL_TOKEN || "2cf13116e9701343ac27ddc452adfbbc";
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";
112
+ var CLI_VERSION = package_default.version;
47
113
 
48
114
  // src/utils/ui.ts
49
115
  import chalk from "chalk";
50
- function header(message) {
116
+ function printHeader(message) {
51
117
  console.log(chalk.bold(message));
52
118
  }
119
+ function p(message) {
120
+ console.log(message);
121
+ }
53
122
  function print(message) {
54
- console.log(chalk.dim.gray(message));
123
+ console.log(chalk.dim.white(message));
55
124
  }
56
125
  function printBright(message) {
57
126
  console.log(chalk.white(message));
@@ -65,11 +134,62 @@ function printError(message) {
65
134
  function success(message) {
66
135
  console.log(chalk.dim.green(message));
67
136
  }
68
- function listItem(message) {
137
+ function printListItem(message) {
69
138
  console.log("\u2514 " + chalk.gray(message));
70
139
  }
140
+ function cyan(message) {
141
+ return chalk.cyan(message);
142
+ }
143
+ function green(message) {
144
+ return chalk.green(message);
145
+ }
146
+ function bold(message) {
147
+ return chalk.bold(message);
148
+ }
149
+ function bright(message) {
150
+ return chalk.whiteBright(message);
151
+ }
152
+ function dim(message) {
153
+ return chalk.dim(message);
154
+ }
155
+ function link(message) {
156
+ return chalk.dim.underline.cyan(message);
157
+ }
158
+ function printBox(lines, options) {
159
+ const color = options?.color || "yellow";
160
+ const padding = options?.padding ?? 2;
161
+ const stripAnsi = (str) => str.replace(/\x1b\[[0-9;]*m/g, "");
162
+ const maxContentWidth = Math.max(
163
+ ...lines.map((line) => stripAnsi(line).length)
164
+ );
165
+ const boxWidth = maxContentWidth + padding * 2;
166
+ const horizontalLine = "\u2500".repeat(boxWidth);
167
+ const emptyLine = " ".repeat(boxWidth);
168
+ const colorFn = chalk[color] || chalk.yellow;
169
+ p("");
170
+ p(colorFn("\u250C" + horizontalLine + "\u2510"));
171
+ p(colorFn("\u2502" + emptyLine + "\u2502"));
172
+ lines.forEach((line) => {
173
+ const actualLength = stripAnsi(line).length;
174
+ const leftPad = " ".repeat(padding);
175
+ const rightPad = " ".repeat(boxWidth - actualLength - padding);
176
+ p(colorFn("\u2502") + leftPad + line + rightPad + colorFn("\u2502"));
177
+ });
178
+ p(colorFn("\u2502" + emptyLine + "\u2502"));
179
+ p(colorFn("\u2514" + horizontalLine + "\u2518"));
180
+ p("");
181
+ }
182
+ function trimBase64Key(key) {
183
+ return key.substring(0, 3) + "..." + key.substring(key.length - 5);
184
+ }
185
+ function trimToken(token) {
186
+ return token.substring(0, 5) + "...";
187
+ }
188
+ function workspaceLink(workspaceId) {
189
+ return link(`${PLATFORM_URL}/v2/workspaces/${workspaceId}`);
190
+ }
71
191
 
72
- // src/auth/callback-server.ts
192
+ // src/auth/callback_server.ts
73
193
  async function createCallbackServer(options = {}) {
74
194
  const {
75
195
  port = 8085,
@@ -243,9 +363,9 @@ function replacer(key, value) {
243
363
  }
244
364
  return value;
245
365
  }
246
- function fetchReq(path6, init) {
366
+ function fetchReq(path7, init) {
247
367
  const { pathPrefix, ...req } = init || {};
248
- const url = pathPrefix ? `${pathPrefix}${path6}` : path6;
368
+ const url = pathPrefix ? `${pathPrefix}${path7}` : path7;
249
369
  return fetch(url, req).then(
250
370
  (r) => r.json().then((body) => {
251
371
  if (!r.ok) {
@@ -271,10 +391,10 @@ function isPrimitive(value) {
271
391
  function isZeroValuePrimitive(value) {
272
392
  return value === false || value === 0 || value === "";
273
393
  }
274
- function flattenRequestPayload(requestPayload, path6 = "") {
394
+ function flattenRequestPayload(requestPayload, path7 = "") {
275
395
  return Object.keys(requestPayload).reduce((acc, key) => {
276
396
  const value = requestPayload[key];
277
- const newPath = path6 ? [path6, key].join(".") : key;
397
+ const newPath = path7 ? [path7, key].join(".") : key;
278
398
  const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
279
399
  const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
280
400
  let objectToMerge = {};
@@ -527,7 +647,6 @@ var AuthManager = class _AuthManager {
527
647
  */
528
648
  async generateInworldToken(firebaseToken) {
529
649
  try {
530
- print("Generating Inworld token...");
531
650
  const tokenResponse = await Users.GenerateTokenUser(
532
651
  {
533
652
  type: "AUTH_TYPE_FIREBASE" /* AUTH_TYPE_FIREBASE */,
@@ -606,7 +725,6 @@ var AuthManager = class _AuthManager {
606
725
  const credentials = await this.getCredentials();
607
726
  return credentials?.inworldToken || null;
608
727
  }
609
- print("Token expired, refreshing...");
610
728
  return await this.refreshToken();
611
729
  }
612
730
  /**
@@ -684,6 +802,9 @@ You can run "inworld login --force" to login with the correct environment.`
684
802
  };
685
803
  var authManager = new AuthManager();
686
804
 
805
+ // src/services/workspace_service.ts
806
+ import chalk2 from "chalk";
807
+
687
808
  // src/utils/array.ts
688
809
  function isArrayOfType(arr, typeGuard) {
689
810
  return typeof arr !== "undefined" && Array.isArray(arr) && arr.every(typeGuard);
@@ -834,8 +955,8 @@ var check = async (operationName, signal, returnWithMetadata) => retryableAuthen
834
955
 
835
956
  // src/auth/utils.ts
836
957
  async function requireAuth() {
837
- const isAuthenticated2 = await authManager.isAuthenticated();
838
- if (!isAuthenticated2) {
958
+ const isAuthenticated = await authManager.isAuthenticated();
959
+ if (!isAuthenticated) {
839
960
  console.log();
840
961
  printError("\u274C Authentication required");
841
962
  print("You must be logged in to use this command.");
@@ -956,9 +1077,6 @@ var authenticatedInworldRequest = async (pb, req, inworldToken, signal) => {
956
1077
  }
957
1078
  };
958
1079
 
959
- // src/services/workspace_service.ts
960
- import chalk2 from "chalk";
961
-
962
1080
  // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
963
1081
  var ApiKeys = class {
964
1082
  static ListApiKeys(req, initReq) {
@@ -1084,6 +1202,42 @@ var Workspaces = class {
1084
1202
  }
1085
1203
  };
1086
1204
 
1205
+ // src/utils/confirm.ts
1206
+ import * as readline from "readline";
1207
+ var globalForceYes = false;
1208
+ function setGlobalForceYes(value) {
1209
+ globalForceYes = value;
1210
+ }
1211
+ async function confirm(options) {
1212
+ const { message, forceYes, defaultValue = false } = options;
1213
+ if (forceYes !== void 0 ? forceYes : globalForceYes) {
1214
+ return true;
1215
+ }
1216
+ const rl = readline.createInterface({
1217
+ input: process.stdin,
1218
+ output: process.stdout
1219
+ });
1220
+ return new Promise((resolve2) => {
1221
+ rl.question(message, (answer) => {
1222
+ rl.close();
1223
+ const trimmedAnswer = answer.trim().toLowerCase();
1224
+ if (trimmedAnswer === "y" || trimmedAnswer === "yes") {
1225
+ resolve2(true);
1226
+ return;
1227
+ }
1228
+ if (trimmedAnswer === "n" || trimmedAnswer === "no") {
1229
+ resolve2(false);
1230
+ return;
1231
+ }
1232
+ if (trimmedAnswer === "") {
1233
+ resolve2(defaultValue);
1234
+ return;
1235
+ }
1236
+ resolve2(false);
1237
+ });
1238
+ });
1239
+ }
1240
+
1087
1241
  // src/utils/resource_name_helper.ts
1088
1242
  var parseWorkspaceResourceName = (resourceName) => {
1089
1243
  const [collection, workspaceId] = resourceName.split("/");
@@ -1103,7 +1257,7 @@ var getWorkspaceResourceName = (workspaceId) => {
1103
1257
  };
1104
1258
 
1105
1259
  // src/utils/selector.ts
1106
- import * as readline from "readline";
1260
+ import * as readline2 from "readline";
1107
1261
  async function selectItem(options) {
1108
1262
  const {
1109
1263
  items,
@@ -1123,13 +1277,15 @@ async function selectItem(options) {
1123
1277
  return items[0];
1124
1278
  }
1125
1279
  console.log();
1126
- header(title);
1280
+ printHeader(title);
1127
1281
  items.forEach((item, idx) => {
1128
1282
  const displayName = getDisplayName(item);
1129
1283
  const identifier = getIdentifier(item);
1130
- listItem(`${idx + 1}. ${displayName} (ID: ${identifier})`);
1284
+ printListItem(
1285
+ `${idx + 1}. ${bright(displayName)} (ID: ${cyan(identifier)})`
1286
+ );
1131
1287
  });
1132
- const rl = readline.createInterface({
1288
+ const rl = readline2.createInterface({
1133
1289
  input: process.stdin,
1134
1290
  output: process.stdout
1135
1291
  });
@@ -1166,9 +1322,6 @@ async function selectItemOrExit(options) {
1166
1322
  }
1167
1323
  return selected;
1168
1324
  }
1169
- function trimBase64Key(key) {
1170
- return key.substring(0, 10) + "..." + key.substring(key.length - 10);
1171
- }
1172
1325
 
1173
1326
  // src/services/workspace_service.ts
1174
1327
  var WorkspaceService = class {
@@ -1238,7 +1391,8 @@ var WorkspaceService = class {
1238
1391
  workspaceResourceName
1239
1392
  ).workspaceId;
1240
1393
  print(`
1241
- Selecting workspace: ${chalk2.white(workspaceId)}...`);
1394
+ Selecting workspace: ${chalk2.whiteBright(workspaceId)}`);
1395
+ print(`Selected workspace link: ${workspaceLink(workspaceId)}`);
1242
1396
  let apiKey = null;
1243
1397
  const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
1244
1398
  parent: workspaceResourceName,
@@ -1252,40 +1406,33 @@ Selecting workspace: ${chalk2.white(workspaceId)}...`);
1252
1406
  apiKey = await this.pickApiKey(response.apiKeys, false);
1253
1407
  }
1254
1408
  } else {
1255
- const readline5 = await import("readline");
1256
- const rl = readline5.createInterface({
1257
- input: process.stdin,
1258
- output: process.stdout
1409
+ const shouldGenerate = await confirm({
1410
+ message: "No API keys found for this workspace. Would you like to generate one? (y/N): ",
1411
+ defaultValue: false
1259
1412
  });
1260
- await new Promise((resolve2) => {
1261
- rl.question(
1262
- "No API keys found for this workspace. Would you like to generate one? (y/N): ",
1263
- async (answer) => {
1264
- if (answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes") {
1265
- print("Generating API key...");
1266
- const generateApiKeyResponse = await authenticatedInworldRequest(
1267
- ApiKeys.GenerateApiKey,
1268
- {
1269
- parent: workspaceResourceName
1270
- }
1271
- );
1272
- if (!generateApiKeyResponse) {
1273
- printError("Failed to generate API key.");
1274
- process.exit(1);
1275
- }
1276
- apiKey = generateApiKeyResponse;
1277
- success("API key generated successfully.");
1278
- } else {
1279
- print("No API key will be generated.");
1280
- }
1281
- rl.close();
1282
- resolve2();
1413
+ if (shouldGenerate) {
1414
+ print("Generating API key...");
1415
+ const generateApiKeyResponse = await authenticatedInworldRequest(
1416
+ ApiKeys.GenerateApiKey,
1417
+ {
1418
+ parent: workspaceResourceName
1283
1419
  }
1284
1420
  );
1285
- });
1421
+ if (!generateApiKeyResponse) {
1422
+ printError("Failed to generate API key.");
1423
+ process.exit(1);
1424
+ }
1425
+ apiKey = generateApiKeyResponse;
1426
+ success("API key generated successfully.");
1427
+ } else {
1428
+ print("No API key will be generated.");
1429
+ }
1286
1430
  }
1287
1431
  const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
1288
- print(`Selecting API key: ${chalk2.white(trimBase64Key(base64Key))}...`);
1432
+ print(
1433
+ `
1434
+ Selecting API key: ${chalk2.whiteBright(trimBase64Key(base64Key))}`
1435
+ );
1289
1436
  await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);
1290
1437
  success("\nWorkspace and API key selected.");
1291
1438
  }
@@ -1310,12 +1457,12 @@ Selecting workspace: ${chalk2.white(workspaceId)}...`);
1310
1457
  return;
1311
1458
  }
1312
1459
  console.log();
1313
- header(`API keys in workspace ${credentials.workspace}:`);
1460
+ printHeader(`API keys in workspace ${credentials.workspace}:`);
1314
1461
  apiKeys.forEach((apiKey, idx) => {
1315
1462
  const name = apiKey.name?.split("/").pop() || "unknown";
1316
1463
  const createdAt = apiKey.createTime ? new Date(apiKey.createTime).toLocaleDateString() : "unknown date";
1317
1464
  const state = apiKey.state || "unknown";
1318
- listItem(
1465
+ printListItem(
1319
1466
  `${idx + 1}. ${name} (created: ${createdAt}, state: ${state})`
1320
1467
  );
1321
1468
  });
@@ -1338,26 +1485,13 @@ Selecting workspace: ${chalk2.white(workspaceId)}...`);
1338
1485
  const apiKeys = response?.apiKeys || [];
1339
1486
  if (apiKeys.length === 0) {
1340
1487
  printError("No API keys found in the active workspace.");
1341
- const readline5 = await import("readline");
1342
- const rl = readline5.createInterface({
1343
- input: process.stdin,
1344
- output: process.stdout
1345
- });
1346
- await new Promise((resolve2) => {
1347
- rl.question(
1348
- "Would you like to generate a new API key? (y/N): ",
1349
- async (answer) => {
1350
- if (answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes") {
1351
- rl.close();
1352
- resolve2();
1353
- await this.generateApiKey();
1354
- } else {
1355
- rl.close();
1356
- resolve2();
1357
- }
1358
- }
1359
- );
1488
+ const shouldGenerate = await confirm({
1489
+ message: "Would you like to generate a new API key? (y/N): ",
1490
+ defaultValue: false
1360
1491
  });
1492
+ if (shouldGenerate) {
1493
+ await this.generateApiKey();
1494
+ }
1361
1495
  return;
1362
1496
  }
1363
1497
  if (apiKeys.length === 1) {
@@ -1417,12 +1551,12 @@ Selecting workspace: ${chalk2.white(workspaceId)}...`);
1417
1551
  success("API key activated successfully.");
1418
1552
  success("API key generated and activated successfully.");
1419
1553
  console.log();
1420
- header("API Key details:");
1421
- listItem(
1554
+ printHeader("API Key details:");
1555
+ printListItem(
1422
1556
  `Name: ${generateApiKeyResponse.name?.split("/").pop() || "unknown"}`
1423
1557
  );
1424
- listItem(`Key: ${generateApiKeyResponse.key}`);
1425
- listItem(`Base64: ${base64Key}`);
1558
+ printListItem(`Key: ${generateApiKeyResponse.key}`);
1559
+ printListItem(`Base64: ${base64Key}`);
1426
1560
  }
1427
1561
  };
1428
1562
 
@@ -1450,7 +1584,7 @@ var loginAction = async (options) => {
1450
1584
  process.exit(0);
1451
1585
  }
1452
1586
  console.log();
1453
- header("\u{1F3AD} Welcome to Inworld CLI!");
1587
+ printHeader("\u{1F3AD} Welcome to Inworld CLI!");
1454
1588
  if (options.force && await authManager.isAuthenticated()) {
1455
1589
  const credentials = await authManager.getCredentials();
1456
1590
  const email = credentials?.email || "Unknown";
@@ -1467,7 +1601,7 @@ var loginAction = async (options) => {
1467
1601
  print("Please visit the following URL to authenticate:");
1468
1602
  printLink(`${INWORLD_CLI_AUTH_URL}
1469
1603
  `);
1470
- const readlineInterface = readline2.createInterface({
1604
+ const readlineInterface = readline3.createInterface({
1471
1605
  input: process.stdin,
1472
1606
  output: process.stdout
1473
1607
  });
@@ -1548,37 +1682,27 @@ var loginCommand = makeLoginCommand(
1548
1682
  "Authenticate with Inworld Platform"
1549
1683
  );
1550
1684
  var loginCommandAlias = makeLoginCommand(
1551
- `Alias for "${chalk3.bold("inworld auth login")}"`
1685
+ `Alias for "${bold("inworld auth login")}"`
1552
1686
  );
1553
1687
 
1554
1688
  // src/commands/auth/logout_command.ts
1555
- import chalk4 from "chalk";
1556
1689
  import { Command as Command2 } from "commander";
1557
- import * as readline3 from "readline";
1558
1690
  var logoutAction = async (options) => {
1559
1691
  try {
1560
- const isAuthenticated2 = await authManager.isAuthenticated();
1561
- if (!isAuthenticated2) {
1692
+ const isAuthenticated = await authManager.isAuthenticated();
1693
+ if (!isAuthenticated) {
1562
1694
  print("You are not currently authenticated.");
1563
1695
  process.exit(0);
1564
1696
  }
1565
1697
  const credentials = await authManager.getCredentials();
1566
1698
  const email = credentials?.email || "Unknown user";
1567
1699
  console.log();
1568
- header("\u{1F3AD} Inworld CLI - Logout");
1700
+ printHeader("\u{1F3AD} Inworld CLI - Logout");
1569
1701
  print(`Current account: ${email}`);
1570
1702
  if (!options.force) {
1571
- const rl = readline3.createInterface({
1572
- input: process.stdin,
1573
- output: process.stdout
1574
- });
1575
- const confirmed = await new Promise((resolve2) => {
1576
- rl.question("\nAre you sure you want to logout? (y/N): ", (answer) => {
1577
- rl.close();
1578
- resolve2(
1579
- answer.toLowerCase() === "y" || answer.toLowerCase() === "yes"
1580
- );
1581
- });
1703
+ const confirmed = await confirm({
1704
+ message: "\nAre you sure you want to logout? (y/N): ",
1705
+ defaultValue: false
1582
1706
  });
1583
1707
  if (!confirmed) {
1584
1708
  console.log();
@@ -1603,22 +1727,21 @@ var makeLogoutCommand = (description) => {
1603
1727
  return new Command2("logout").description(description).option("-f, --force", "Skip confirmation prompt").action(logoutAction);
1604
1728
  };
1605
1729
  var logoutCommandAlias = makeLogoutCommand(
1606
- `Alias for "${chalk4.bold("inworld auth logout")}"`
1730
+ `Alias for "${bold("inworld auth logout")}"`
1607
1731
  );
1608
1732
  var logoutCommand = makeLogoutCommand(
1609
1733
  "Clear stored authentication credentials"
1610
1734
  );
1611
1735
 
1612
1736
  // src/commands/auth/status_command.ts
1613
- import chalk5 from "chalk";
1614
1737
  import { Command as Command3 } from "commander";
1615
1738
  var statusAction = async () => {
1616
1739
  try {
1617
1740
  const credentials = await authManager.getCredentials();
1618
- header("\nInworld CLI Status\n");
1741
+ printHeader("\nInworld CLI Status\n");
1619
1742
  if (!credentials) {
1620
1743
  print("Not authenticated.");
1621
- print(`Run \`${chalk5.white("inworld auth login")}\` to authenticate.`);
1744
+ print(`Run \`${bold("inworld auth login")}\` to authenticate.`);
1622
1745
  if (process.env.INWORLD_API_KEY) {
1623
1746
  print(
1624
1747
  `
@@ -1637,25 +1760,19 @@ INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KE
1637
1760
  const expirationDate = credentials.expiresAt ? new Date(credentials.expiresAt).toLocaleString() : "Unknown";
1638
1761
  console.log();
1639
1762
  printBright("Token Status:");
1640
- print(
1641
- ` Inworld Token: ${credentials.inworldToken.substring(0, 20)}...`
1642
- );
1763
+ print(` Inworld Token: ${trimToken(credentials.inworldToken)}`);
1643
1764
  print(` Expires At: ${expirationDate}`);
1644
1765
  print(` Status: ${isExpired ? "Expired" : "Valid"}`);
1645
1766
  } else {
1646
- header("\nToken Status:");
1767
+ printHeader("\nToken Status:");
1647
1768
  print(` Inworld Token: Not available`);
1648
1769
  }
1649
- print(
1650
- ` Refresh Token: ${credentials.refreshToken.substring(0, 20)}...`
1651
- );
1770
+ print(` Refresh Token: ${trimToken(credentials.refreshToken)}`);
1652
1771
  print(` Session Status: Active`);
1653
1772
  printBright("\nActive Workspace:");
1654
1773
  if (credentials.workspace) {
1655
1774
  print(` Workspace id: ${credentials.workspace}`);
1656
- print(
1657
- ` Workspace link: ${chalk5.underline.dim.cyan(`${PLATFORM_URL}/v2/workspaces/${credentials.workspace}`)}`
1658
- );
1775
+ print(` Workspace link: ${workspaceLink(credentials.workspace)}`);
1659
1776
  } else {
1660
1777
  print(` No workspace activated`);
1661
1778
  print(` Run "inworld workspace activate" to select a workspace`);
@@ -1691,14 +1808,211 @@ var statusCommand = makeStatusCommand(
1691
1808
  "Display current authentication status and configuration"
1692
1809
  );
1693
1810
  var statusCommandAlias = makeStatusCommand(
1694
- `Alias for "${chalk5.bold("inworld auth status")}"`
1811
+ `Alias for "${bold("inworld auth status")}"`
1695
1812
  );
1696
1813
 
1697
1814
  // src/commands/auth_command.ts
1815
+ import { Command as Command9 } from "commander";
1816
+
1817
+ // src/commands/auth/disable_telemetry_command.ts
1818
+ import { Command as Command4 } from "commander";
1819
+
1820
+ // src/services/analytics.ts
1821
+ import Conf2 from "conf";
1822
+ import Mixpanel from "mixpanel";
1823
+ var Analytics = class _Analytics {
1824
+ static CONF_ENTRY_NAME = "analytics";
1825
+ conf;
1826
+ mixpanel = null;
1827
+ userId = null;
1828
+ initialized = false;
1829
+ constructor() {
1830
+ this.conf = new Conf2({
1831
+ projectName: "inworld-cli-config"
1832
+ });
1833
+ }
1834
+ /**
1835
+ * Initializes Mixpanel with user context (email and CLI version).
1836
+ * Only initializes if the user is authenticated and hasn't opted out.
1837
+ */
1838
+ async initialize() {
1839
+ try {
1840
+ if (!this.isTelemetryEnabled()) {
1841
+ return;
1842
+ }
1843
+ if (!MIXPANEL_TOKEN) {
1844
+ return;
1845
+ }
1846
+ const credentials = await authManager.getCredentials();
1847
+ if (!credentials?.email) {
1848
+ return;
1849
+ }
1850
+ this.mixpanel = Mixpanel.init(MIXPANEL_TOKEN);
1851
+ this.userId = credentials.email;
1852
+ this.initialized = true;
1853
+ if (this.mixpanel && this.userId) {
1854
+ this.mixpanel.people.set(this.userId, {
1855
+ $email: credentials.email,
1856
+ cli_version: CLI_VERSION,
1857
+ environment: credentials.env || "PROD"
1858
+ });
1859
+ }
1860
+ } catch {
1861
+ this.initialized = false;
1862
+ }
1863
+ }
1864
+ /**
1865
+ * Checks if telemetry is enabled (opt-in by default)
1866
+ */
1867
+ isTelemetryEnabled() {
1868
+ const config = this.conf.get(_Analytics.CONF_ENTRY_NAME);
1869
+ return config?.telemetryEnabled !== false;
1870
+ }
1871
+ /**
1872
+ * Enables or disables telemetry
1873
+ */
1874
+ setTelemetryEnabled(enabled) {
1875
+ this.conf.set(_Analytics.CONF_ENTRY_NAME, { telemetryEnabled: enabled });
1876
+ }
1877
+ /**
1878
+ * Tracks a command execution event
1879
+ * @param command The command being executed (e.g., 'auth login', 'graph deploy')
1880
+ * @param parameters Command parameters (sanitized, no sensitive data)
1881
+ */
1882
+ trackCommandExecution(command, parameters) {
1883
+ if (!this.initialized || !this.mixpanel || !this.userId) {
1884
+ return;
1885
+ }
1886
+ try {
1887
+ this.mixpanel.track("[inworld cli] command_execution", {
1888
+ distinct_id: this.userId,
1889
+ command,
1890
+ cli_version: CLI_VERSION,
1891
+ ...parameters
1892
+ });
1893
+ } catch {
1894
+ }
1895
+ }
1896
+ /**
1897
+ * Tracks a command result event (success or failure)
1898
+ * @param command The command that was executed
1899
+ * @param success Whether the command succeeded
1900
+ * @param errorMessage Optional error message (sanitized)
1901
+ */
1902
+ trackCommandResult(command, success2, errorMessage) {
1903
+ if (!this.initialized || !this.mixpanel || !this.userId) {
1904
+ return;
1905
+ }
1906
+ try {
1907
+ this.mixpanel.track("[inworld_cli] command_result", {
1908
+ distinct_id: this.userId,
1909
+ command,
1910
+ success: success2,
1911
+ cli_version: CLI_VERSION,
1912
+ error_message: errorMessage
1913
+ });
1914
+ } catch {
1915
+ }
1916
+ }
1917
+ /**
1918
+ * Flushes any pending events to Mixpanel
1919
+ * Should be called before the CLI exits
1920
+ */
1921
+ flush() {
1922
+ return new Promise((resolve2) => {
1923
+ if (!this.initialized || !this.mixpanel) {
1924
+ resolve2();
1925
+ return;
1926
+ }
1927
+ const timeout = setTimeout(() => resolve2(), 500);
1928
+ setTimeout(() => {
1929
+ clearTimeout(timeout);
1930
+ resolve2();
1931
+ }, 100);
1932
+ });
1933
+ }
1934
+ };
1935
+ var analytics = new Analytics();
1936
+
1937
+ // src/commands/auth/disable_telemetry_command.ts
1938
+ var disableTelemetryAction = async () => {
1939
+ try {
1940
+ analytics.setTelemetryEnabled(false);
1941
+ success("Telemetry disabled");
1942
+ print(
1943
+ "\nUsage data will no longer be collected. You can re-enable telemetry by running:"
1944
+ );
1945
+ print(` ${bold("inworld auth enable_telemetry")}`);
1946
+ process.exit(0);
1947
+ } catch (error) {
1948
+ printError("Failed to disable telemetry:");
1949
+ console.error(error);
1950
+ process.exit(1);
1951
+ }
1952
+ };
1953
+ var disableTelemetryCommand = new Command4("disable_cli_telemetry").description("Disable anonymous CLI usage analytics").action(disableTelemetryAction);
1954
+
1955
+ // src/commands/auth/enable_telemetry_command.ts
1956
+ import { Command as Command5 } from "commander";
1957
+ var enableTelemetryAction = async () => {
1958
+ try {
1959
+ analytics.setTelemetryEnabled(true);
1960
+ success("\u2713 Telemetry enabled");
1961
+ print(
1962
+ "\nAnonymous usage data will be collected to help improve the CLI."
1963
+ );
1964
+ print("\nYou can disable telemetry at any time by running:");
1965
+ print(` ${bold("inworld auth disable_telemetry")}`);
1966
+ process.exit(0);
1967
+ } catch (error) {
1968
+ printError("Failed to enable telemetry:");
1969
+ console.error(error);
1970
+ process.exit(1);
1971
+ }
1972
+ };
1973
+ var enableTelemetryCommand = new Command5("enable_cli_telemetry").description("Enable anonymous CLI usage analytics").action(enableTelemetryAction);
1974
+
1975
+ // src/commands/auth/login_ci_command.ts
1698
1976
  import { Command as Command6 } from "commander";
1977
+ var loginCiAction = async (options) => {
1978
+ try {
1979
+ setGlobalForceYes(true);
1980
+ console.log();
1981
+ printHeader("\u{1F3AD} Authenticating with external Firebase token");
1982
+ console.log();
1983
+ const success2 = await authManager.authenticateAndSaveCredentials(
1984
+ options.token,
1985
+ options.refreshToken || options.token,
1986
+ // Use token as fallback if no refresh token
1987
+ options.email,
1988
+ /* workspace */
1989
+ void 0,
1990
+ INWORLD_ENV
1991
+ );
1992
+ if (!success2) {
1993
+ printError("Failed to authenticate with provided token");
1994
+ process.exit(1);
1995
+ }
1996
+ console.log();
1997
+ success("\u2713 Authentication successful!");
1998
+ print(`Email: ${options.email}`);
1999
+ await WorkspaceService.activateWorkspace({ forceFirst: true });
2000
+ print("\nAuthentication completed.");
2001
+ process.exit(0);
2002
+ } catch (error) {
2003
+ console.log();
2004
+ printError("Token-based authentication failed:");
2005
+ console.error(error);
2006
+ process.exit(1);
2007
+ }
2008
+ };
2009
+ var loginCiCommand = new Command6("login-ci").description("Authenticate using Firebase token (for CI/testing)").requiredOption("-t, --token <token>", "Firebase ID token").requiredOption("-e, --email <email>", "Email address").option(
2010
+ "-r, --refresh-token <refreshToken>",
2011
+ "Firebase refresh token (optional, enables token refresh)"
2012
+ ).action(loginCiAction);
1699
2013
 
1700
2014
  // src/commands/auth/print_access_token_command.ts
1701
- import { Command as Command4 } from "commander";
2015
+ import { Command as Command7 } from "commander";
1702
2016
  var printAccessTokenAction = async () => {
1703
2017
  try {
1704
2018
  const token = await authManager.getValidToken();
@@ -1711,10 +2025,10 @@ var printAccessTokenAction = async () => {
1711
2025
  process.exit(1);
1712
2026
  }
1713
2027
  };
1714
- var printAccessTokenCommand = new Command4("print-access-token").description("Print the current Inworld access token").action(printAccessTokenAction);
2028
+ var printAccessTokenCommand = new Command7("print-access-token").description("Print the current Inworld access token").action(printAccessTokenAction);
1715
2029
 
1716
2030
  // src/commands/auth/print_api_key_command.ts
1717
- import { Command as Command5 } from "commander";
2031
+ import { Command as Command8 } from "commander";
1718
2032
  var printApiKeyAction = async () => {
1719
2033
  try {
1720
2034
  if (process.env.INWORLD_API_KEY) {
@@ -1731,17 +2045,16 @@ var printApiKeyAction = async () => {
1731
2045
  process.exit(1);
1732
2046
  }
1733
2047
  };
1734
- var printApiKeyCommand = new Command5("print-api-key").description("Print the current API key").action(printApiKeyAction);
2048
+ var printApiKeyCommand = new Command8("print-api-key").description("Print the current API key").action(printApiKeyAction);
1735
2049
 
1736
2050
  // src/commands/auth_command.ts
1737
- var authCommand = new Command6("auth").description("Manage Inworld authentication").addCommand(loginCommand).addCommand(logoutCommand).addCommand(printAccessTokenCommand).addCommand(printApiKeyCommand).addCommand(statusCommand).action(() => {
2051
+ var authCommand = new Command9("auth").description("Manage Inworld authentication").addCommand(loginCommand).addCommand(loginCiCommand).addCommand(logoutCommand).addCommand(printAccessTokenCommand).addCommand(printApiKeyCommand).addCommand(statusCommand).addCommand(disableTelemetryCommand).addCommand(enableTelemetryCommand).action(() => {
1738
2052
  authCommand.help();
1739
2053
  });
1740
2054
 
1741
2055
  // src/commands/graph/graph_deploy_command.ts
1742
2056
  import archiver from "archiver";
1743
- import chalk8 from "chalk";
1744
- import { Command as Command7 } from "commander";
2057
+ import { Command as Command10 } from "commander";
1745
2058
  import fs2 from "fs";
1746
2059
  import os from "os";
1747
2060
  import path2 from "path";
@@ -1828,7 +2141,7 @@ var GraphsService = class {
1828
2141
  };
1829
2142
 
1830
2143
  // src/utils/spinner.ts
1831
- import chalk6 from "chalk";
2144
+ import chalk3 from "chalk";
1832
2145
  import ora from "ora";
1833
2146
  var PHRASES = [
1834
2147
  "Condensing time-space matter",
@@ -1894,13 +2207,13 @@ var LROSpinner = class _LROSpinner {
1894
2207
  updateText() {
1895
2208
  const phrase = _LROSpinner.getRandomPhrase();
1896
2209
  const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1e3);
1897
- let text = chalk6.cyan(phrase);
2210
+ let text = chalk3.cyan(phrase);
1898
2211
  if (this.config.showIterations && this.iterationCount > 0) {
1899
- text += chalk6.gray(
2212
+ text += chalk3.gray(
1900
2213
  ` (iteration ${this.iterationCount}, ${elapsedSeconds}s)`
1901
2214
  );
1902
2215
  } else if (elapsedSeconds > 0) {
1903
- text += chalk6.gray(` (${elapsedSeconds}s)`);
2216
+ text += chalk3.gray(` (${elapsedSeconds}s)`);
1904
2217
  }
1905
2218
  this.spinner.text = text;
1906
2219
  }
@@ -1915,7 +2228,7 @@ var LROSpinner = class _LROSpinner {
1915
2228
  * Updates spinner with custom text temporarily
1916
2229
  */
1917
2230
  updateCustomText(text) {
1918
- this.spinner.text = chalk6.yellow(text);
2231
+ this.spinner.text = chalk3.yellow(text);
1919
2232
  }
1920
2233
  /**
1921
2234
  * Succeeds the spinner with a success message
@@ -1924,7 +2237,7 @@ var LROSpinner = class _LROSpinner {
1924
2237
  this.cleanup();
1925
2238
  const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1e3);
1926
2239
  const successText = text || `Deployment completed successfully in ${elapsedSeconds}s`;
1927
- this.spinner.succeed(chalk6.green(successText));
2240
+ this.spinner.succeed(chalk3.green(successText));
1928
2241
  }
1929
2242
  /**
1930
2243
  * Fails the spinner with an error message
@@ -1932,7 +2245,7 @@ var LROSpinner = class _LROSpinner {
1932
2245
  fail(text) {
1933
2246
  this.cleanup();
1934
2247
  const errorText = text || "Deployment failed";
1935
- this.spinner.fail(chalk6.red(errorText));
2248
+ this.spinner.fail(chalk3.red(errorText));
1936
2249
  }
1937
2250
  /**
1938
2251
  * Warns the spinner with a warning message
@@ -1940,7 +2253,7 @@ var LROSpinner = class _LROSpinner {
1940
2253
  warn(text) {
1941
2254
  this.cleanup();
1942
2255
  const warnText = text || "Deployment completed with warnings";
1943
- this.spinner.warn(chalk6.yellow(warnText));
2256
+ this.spinner.warn(chalk3.yellow(warnText));
1944
2257
  }
1945
2258
  /**
1946
2259
  * Stops the spinner without any status
@@ -1980,7 +2293,7 @@ function createLROSpinnerCallbacks(config) {
1980
2293
  spinner.updateIteration(checkData.checkIteration);
1981
2294
  if (checkData.checkIteration > checkData.checkLimit * 0.8) {
1982
2295
  spinner.updateCustomText(
1983
- chalk6.yellow(
2296
+ chalk3.yellow(
1984
2297
  `\u26A0\uFE0F Taking longer than expected... (${checkData.checkIteration}/${checkData.checkLimit})`
1985
2298
  )
1986
2299
  );
@@ -2115,7 +2428,6 @@ var registerGraph = async (workspaceId, graphId) => {
2115
2428
  };
2116
2429
 
2117
2430
  // src/services/graph_loader.ts
2118
- import chalk7 from "chalk";
2119
2431
  import * as esbuild from "esbuild";
2120
2432
  import fs from "fs";
2121
2433
  import { Module } from "module";
@@ -2177,10 +2489,8 @@ var loadGraph = async (file) => {
2177
2489
  }
2178
2490
  const graphId = module.graph.graphId;
2179
2491
  if (typeof graphId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(graphId)) {
2180
- console.error(
2181
- chalk7.red(
2182
- "Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores."
2183
- )
2492
+ printError(
2493
+ "Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores."
2184
2494
  );
2185
2495
  process.exit(1);
2186
2496
  }
@@ -2347,11 +2657,30 @@ inworld run ${graphFileName}
2347
2657
  }
2348
2658
  process.exit(1);
2349
2659
  }
2660
+ const startUrl = `${PLATFORM_URL.replace("platform", "api")}/cloud/${graphResourceName}/v1/graph:start`;
2350
2661
  success("Deployment successful!");
2351
2662
  success("Inworld Cloud URI:");
2352
- print(
2353
- `${PLATFORM_URL.replace("platform", "api")}/cloud/${graphResourceName}/v1/graph:start`
2663
+ print(startUrl);
2664
+ print(`
2665
+ Curl commands to try the graph:`);
2666
+ printBright(`
2667
+ TEMPLATE:
2668
+ `);
2669
+ printBright(` curl -X POST ${startUrl} \\`);
2670
+ printBright(
2671
+ ' -H "Authorization: Basic $(inworld auth print-api-key)" \\'
2354
2672
  );
2673
+ printBright(' -H "Content-Type: application/json" \\');
2674
+ printBright(" -d '{<YOUR_INPUT>}'");
2675
+ printBright(`
2676
+ EXAMPLE (LLM + TTS Pipeline):`);
2677
+ printBright(` curl -X POST ${startUrl} \\`);
2678
+ printBright(
2679
+ ' -H "Authorization: Basic $(inworld auth print-api-key)" \\'
2680
+ );
2681
+ printBright(' -H "Content-Type: application/json" \\');
2682
+ printBright(` -d '{"input": {"user_input":"Hello!"}}'`);
2683
+ await graph.stopRuntime();
2355
2684
  try {
2356
2685
  fs2.rmSync(tempBaseDir, { recursive: true, force: true });
2357
2686
  } catch (_error) {
@@ -2364,105 +2693,278 @@ inworld run ${graphFileName}
2364
2693
  }
2365
2694
  };
2366
2695
  var makeDeployCommand = (description) => {
2367
- return new Command7("deploy").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-i, --info", "Shows deployment info if any").option(
2696
+ return new Command10("deploy").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-i, --info", "Shows deployment info if any").option(
2368
2697
  "-p, --package-only [file]",
2369
2698
  "Output file path (if not specified, outputs to graph-deployment.zip in current directory)"
2370
2699
  ).action(deployAction);
2371
2700
  };
2372
2701
  var deployCommand = makeDeployCommand(
2373
- "Packages a graph for deployment to the Inworld Cloud."
2702
+ "[preview] Packages a graph for deployment to the Inworld Cloud."
2374
2703
  );
2375
2704
  var deployCommandAlias = makeDeployCommand(
2376
- `Alias for "${chalk8.bold("inworld graph deploy")}"`
2705
+ `[preview] Alias for "${bold("inworld graph deploy")}"`
2377
2706
  );
2378
2707
 
2379
2708
  // src/commands/graph/graph_init_command.ts
2380
- import chalk9 from "chalk";
2381
- import { Command as Command8 } from "commander";
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
2382
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";
2383
2720
  import path3 from "path";
2384
- import * as readline4 from "readline";
2385
- import { fileURLToPath } from "url";
2386
- var __filename = fileURLToPath(import.meta.url);
2387
- var __dirname = path3.dirname(__filename);
2388
- function getTemplatePath() {
2389
- const possiblePaths = [
2390
- // Production: templates are copied to dist/templates (when code is bundled in dist/index.js)
2391
- path3.join(__dirname, "templates"),
2392
- // Development: templates are in src/templates (when running from src/)
2393
- path3.join(__dirname, "..", "..", "templates"),
2394
- // Alternative: if running from nested directory structure
2395
- 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"
2396
2773
  ];
2397
- for (const templatePath of possiblePaths) {
2398
- if (fs3.existsSync(templatePath)) {
2399
- 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);
2400
2784
  }
2401
2785
  }
2402
- throw new Error(
2403
- "Template directory not found. Please ensure templates are properly installed."
2404
- );
2405
2786
  }
2406
- var TEMPLATE_PATH = getTemplatePath();
2407
- function loadTemplateMetadata(templateDir, basePath) {
2408
- const metadataPath = path3.join(basePath, templateDir, "metadata.json");
2409
- 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)) {
2410
2870
  try {
2411
- return JSON.parse(fs3.readFileSync(metadataPath, "utf-8"));
2412
- } catch (err) {
2413
- 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;
2414
2876
  }
2415
2877
  }
2416
- return {
2417
- name: templateDir,
2418
- displayName: templateDir.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
2419
- description: `${templateDir} template`,
2420
- tags: [],
2421
- 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()
2422
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 };
2423
2930
  }
2424
- function getAvailableTemplatesWithMetadata() {
2931
+ async function getAvailableTemplatesWithMetadata() {
2425
2932
  const templates = [];
2426
2933
  try {
2427
- const entries = fs3.readdirSync(TEMPLATE_PATH, { withFileTypes: true });
2428
- const templateDirs = entries.filter((entry) => entry.isDirectory()).filter((dir) => {
2429
- const graphPath = path3.join(TEMPLATE_PATH, dir.name, "graph.ts");
2430
- return fs3.existsSync(graphPath);
2431
- });
2432
- for (const dir of templateDirs) {
2433
- const metadata = loadTemplateMetadata(dir.name, TEMPLATE_PATH);
2434
- if (metadata) {
2435
- templates.push({
2436
- directory: dir.name,
2437
- metadata
2438
- });
2439
- }
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);
2440
2941
  }
2441
- } catch (_err) {
2942
+ } catch (error) {
2943
+ throw error;
2442
2944
  }
2443
- return templates;
2945
+ return templates.filter((template) => template.metadata.id === "llm-to-tts-node");
2444
2946
  }
2445
- async function promptNpmInstall() {
2446
- const rl = readline4.createInterface({
2447
- input: process.stdin,
2448
- output: process.stdout
2449
- });
2450
- return new Promise((resolve2) => {
2451
- rl.question(
2452
- "\n\u{1F4E6} Would you like to install dependencies now? (y/n) ",
2453
- (answer) => {
2454
- rl.close();
2455
- resolve2(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
2456
- }
2457
- );
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);
2956
+ }
2957
+ async function promptInstallDependencies() {
2958
+ return confirm({
2959
+ message: `
2960
+ Would you like to install dependencies now using npm? (y/n) `,
2961
+ defaultValue: false
2458
2962
  });
2459
2963
  }
2460
- async function runNpmInstall(directory) {
2964
+ async function runPackageInstall(directory) {
2461
2965
  const { spawn } = await import("child_process");
2462
2966
  return new Promise((resolve2, reject) => {
2463
- console.log();
2464
- print("\u{1F4E6} Installing dependencies...");
2465
- console.log();
2967
+ print(`Installing dependencies using npm...`);
2466
2968
  const install = spawn("npm", ["install"], {
2467
2969
  cwd: directory,
2468
2970
  stdio: "inherit",
@@ -2470,130 +2972,197 @@ async function runNpmInstall(directory) {
2470
2972
  });
2471
2973
  install.on("close", (code) => {
2472
2974
  if (code === 0) {
2473
- console.log();
2474
- success("\u2705 Dependencies installed successfully!");
2975
+ success("Dependencies installed successfully!");
2475
2976
  resolve2();
2476
2977
  } else {
2477
- console.log();
2478
2978
  printError(`\u274C npm install failed with code ${code}`);
2479
2979
  reject(new Error(`npm install failed with code ${code}`));
2480
2980
  }
2481
2981
  });
2482
2982
  install.on("error", (err) => {
2483
- console.log();
2484
2983
  printError(`\u274C Failed to run npm install: ${err.message}`);
2485
2984
  reject(err);
2486
2985
  });
2487
2986
  });
2488
2987
  }
2489
- function createPackageJson(graphFileName) {
2490
- const packageJson = {
2491
- name: "inworld-graph-project",
2492
- version: "1.0.0",
2493
- description: "Inworld Runtime Graph Project",
2494
- main: graphFileName,
2495
- scripts: {
2496
- start: `npx inworld serve ${graphFileName}`,
2497
- run: `npx inworld run ${graphFileName}`
2498
- },
2499
- dependencies: {
2500
- "@inworld/runtime": RUNTIME_VERSION
2501
- },
2502
- keywords: ["inworld", "ai", "graph", "runtime"],
2503
- author: "",
2504
- license: "MIT"
2505
- };
2506
- return packageJson;
2507
- }
2508
- function createGraphTemplate(templateName) {
2509
- const availableTemplates = getAvailableTemplatesWithMetadata();
2510
- if (!availableTemplates.find((template) => template.directory === templateName)) {
2511
- throw new Error(
2512
- `Unknown template: ${templateName}. Available templates: ${availableTemplates.map((template) => template.directory).join(", ")}`
2513
- );
2514
- }
2515
- const templateFilePath = path3.join(TEMPLATE_PATH, templateName, "graph.ts");
2516
- if (!fs3.existsSync(templateFilePath)) {
2517
- throw new Error(
2518
- `Template file not found: ${templateName}/graph.ts. Please ensure the template files are in the templates folder.`
2519
- );
2520
- }
2521
- return fs3.readFileSync(templateFilePath, "utf-8");
2522
- }
2523
- function createReadme(templateName, graphFileName) {
2524
- const readmePath = path3.join(TEMPLATE_PATH, templateName, "README.md");
2525
- if (!fs3.existsSync(readmePath)) {
2526
- printError(`README file not found: ${readmePath}`);
2527
- process.exit(1);
2528
- }
2529
- const readmeContent = fs3.readFileSync(readmePath, "utf-8");
2530
- return readmeContent.replace(/\{\{graphFileName\}\}/g, graphFileName);
2531
- }
2532
2988
  var initAction = async (options) => {
2533
2989
  try {
2534
2990
  if (options.listTemplates) {
2535
- const templates2 = getAvailableTemplatesWithMetadata();
2536
- console.log();
2537
- header("\u{1F4DA} Available templates:");
2538
- console.log();
2539
- for (const template of templates2) {
2540
- listItem(`${chalk9.cyan.bold(template.metadata.name)}`);
2541
- listItem(` ${template.metadata.description}`);
2542
- if (template.metadata.tags && template.metadata.tags.length > 0) {
2543
- listItem(` Tags: ${template.metadata.tags.join(", ")}`);
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
+ }
3000
+ printHeader("\u{1F4DA} Available templates:");
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)}`);
2544
3028
  }
2545
- if (template.metadata.requirements?.apiKeys) {
2546
- listItem(
2547
- ` 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(", ")}`
2548
3033
  );
2549
3034
  }
2550
- 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("");
2551
3062
  }
2552
3063
  print(
2553
- `Use ${chalk9.bold("inworld graph init")} to interactively select a template.`
3064
+ `
3065
+ Note: Templates are downloaded from GitHub repositories as complete applications.`
2554
3066
  );
2555
- console.log();
2556
3067
  return;
2557
3068
  }
2558
- const templates = getAvailableTemplatesWithMetadata();
2559
- if (templates.length === 0) {
2560
- printError(
2561
- "\u274C No templates found. Please ensure templates are properly installed."
2562
- );
2563
- process.exit(1);
2564
- }
2565
- let selectedTemplate = null;
2566
3069
  let projectName;
3070
+ let selectedTemplateId;
3071
+ const templates = await fetchTemplatesMetadata();
2567
3072
  if (!options.template) {
2568
- console.log();
2569
- header("\u{1F680} Welcome to Inworld Graph Project Initializer!");
2570
- console.log();
2571
- 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({
2572
3081
  items: templates,
2573
- getDisplayName: (item) => `${item.metadata.name} - ${item.metadata.description}`,
2574
- getIdentifier: (item) => item.directory,
2575
- 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)",
2576
3087
  title: "\u{1F4CB} Available Templates:",
2577
- noItemsMessage: "No templates found.",
2578
- invalidSelectionMessage: "Invalid selection. Please try again."
3088
+ exitOnFailure: true
2579
3089
  });
2580
- if (!selectedTemplate) {
2581
- console.log();
2582
- print("\u26A0\uFE0F No template selected. Exiting.");
2583
- return;
2584
- }
3090
+ selectedTemplateId = selectedTemplate2.id;
2585
3091
  } else {
2586
- selectedTemplate = templates.find((t) => t.directory === options.template) || null;
2587
- if (!selectedTemplate) {
2588
- 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) {
2589
3128
  print(
2590
- `Available templates: ${templates.map((t) => t.directory).join(", ")}`
3129
+ `Force refreshing template '${selectedTemplateId}' from GitHub...`
2591
3130
  );
2592
- 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`);
2593
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);
2594
3159
  }
2595
- projectName = options.name || selectedTemplate.metadata.defaultProjectName || selectedTemplate.directory;
2596
- 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) {
2597
3166
  const rl = readline4.createInterface({
2598
3167
  input: process.stdin,
2599
3168
  output: process.stdout
@@ -2601,11 +3170,11 @@ var initAction = async (options) => {
2601
3170
  const askProjectName = () => new Promise((resolve2) => {
2602
3171
  rl.question(
2603
3172
  `
2604
- Project name (${selectedTemplate.metadata.defaultProjectName}): `,
3173
+ Project name (${selectedTemplate.metadata.id || selectedTemplate.metadata.name}): `,
2605
3174
  (answer) => {
2606
3175
  rl.close();
2607
3176
  resolve2(
2608
- answer.trim() || selectedTemplate.metadata.defaultProjectName
3177
+ answer.trim() || selectedTemplate.metadata.id || selectedTemplate.metadata.name
2609
3178
  );
2610
3179
  }
2611
3180
  );
@@ -2613,107 +3182,68 @@ Project name (${selectedTemplate.metadata.defaultProjectName}): `,
2613
3182
  projectName = await askProjectName();
2614
3183
  }
2615
3184
  const currentDir = process.cwd();
2616
- const projectDir = path3.join(currentDir, projectName);
2617
- if (fs3.existsSync(projectDir)) {
2618
- console.log();
2619
- print(`\u26A0\uFE0F Directory '${projectName}' already exists.`);
2620
- if (!options.template) {
2621
- const rl = readline4.createInterface({
2622
- input: process.stdin,
2623
- output: process.stdout
2624
- });
2625
- const confirmOverwrite = await new Promise((resolve2) => {
2626
- rl.question("Do you want to overwrite it? (y/n) ", (answer) => {
2627
- rl.close();
2628
- resolve2(
2629
- answer.toLowerCase() === "y" || answer.toLowerCase() === "yes"
2630
- );
2631
- });
2632
- });
2633
- if (!confirmOverwrite) {
2634
- print("\u26A0\uFE0F Initialization cancelled.");
2635
- return;
2636
- }
2637
- fs3.rmSync(projectDir, { recursive: true, force: true });
2638
- } else {
2639
- print("Overwriting existing directory...");
2640
- fs3.rmSync(projectDir, { recursive: true, force: true });
2641
- }
2642
- }
2643
- fs3.mkdirSync(projectDir, { recursive: true });
2644
- const graphFileName = "graph.ts";
2645
- const graphFilePath = path3.join(projectDir, graphFileName);
2646
- const packageJsonPath = path3.join(projectDir, "package.json");
2647
- const readmePath = path3.join(projectDir, "README.md");
2648
- console.log();
2649
- header(`\u{1F680} Initializing Inworld graph project: ${projectName}`);
2650
- print(`\u{1F4C2} Creating project in: ${projectDir}`);
2651
- print(`\u{1F4CB} Using template: ${selectedTemplate.metadata.displayName}`);
2652
- console.log();
2653
- print("\u{1F4DD} Creating graph file...");
2654
- const graphContent = createGraphTemplate(selectedTemplate.directory);
2655
- fs3.writeFileSync(graphFilePath, graphContent, "utf-8");
2656
- if (!options.skipPackageJson) {
2657
- print("\u{1F4E6} Creating package.json...");
2658
- const packageJson = createPackageJson(graphFileName);
2659
- packageJson.name = projectName;
2660
- fs3.writeFileSync(
2661
- packageJsonPath,
2662
- JSON.stringify(packageJson, null, 2),
2663
- "utf-8"
2664
- );
2665
- }
2666
- if (!options.skipReadme) {
2667
- print("\u{1F4DA} Creating README.md...");
2668
- const readmeContent = createReadme(
2669
- selectedTemplate.directory,
2670
- graphFileName
2671
- );
2672
- fs3.writeFileSync(readmePath, readmeContent, "utf-8");
2673
- }
2674
- if (selectedTemplate.metadata.requirements?.apiKeys) {
2675
- console.log();
2676
- print("\u26A0\uFE0F This template requires the following API keys:");
2677
- for (const key of selectedTemplate.metadata.requirements.apiKeys) {
2678
- print(` \u2022 ${key}`);
3185
+ const projectDir = path4.join(currentDir, projectName);
3186
+ if (fs4.existsSync(projectDir)) {
3187
+ print(`Directory '${projectName}' already exists.`);
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);
2679
3195
  }
3196
+ fs4.rmSync(projectDir, { recursive: true, force: true });
2680
3197
  }
2681
- if (selectedTemplate.metadata.examples?.curlCommand) {
2682
- console.log();
2683
- header("\u{1F4DD} Example usage:");
2684
- print(` ${selectedTemplate.metadata.examples.curlCommand}`);
2685
- }
2686
- console.log();
2687
- success("\u2705 Inworld graph project initialized successfully!");
2688
- if (!options.skipInstall && !options.skipPackageJson) {
2689
- const shouldInstall = await promptNpmInstall();
2690
- if (shouldInstall) {
2691
- try {
2692
- await runNpmInstall(projectDir);
2693
- } catch (_err) {
2694
- console.log();
2695
- print("\u26A0\uFE0F You can install dependencies manually by running:");
2696
- print(` cd ${projectName} && npm install`);
3198
+ print(
3199
+ `Initializing project from template: ${bright(selectedTemplate.metadata.name || selectedTemplateId)}`
3200
+ );
3201
+ print(` Creating project in: ${projectDir}`);
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.")}`);
2697
3220
  }
2698
3221
  }
2699
- }
2700
- console.log();
2701
- header("\u{1F4CC} Next steps:");
2702
- print(` 1. ${chalk9.bold(`cd ${projectName}`)}`);
2703
- if (!options.skipInstall) {
2704
- print(` 2. ${chalk9.bold("npm install")} (if not already done)`);
2705
- print(
2706
- ` 3. ${chalk9.bold("npm start")} or ${chalk9.bold("npx inworld serve graph.ts")}`
2707
- );
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
+ );
3231
+ } else {
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
+ );
3238
+ }
2708
3239
  } else {
2709
- print(
2710
- ` 2. ${chalk9.bold("npm start")} or ${chalk9.bold("npx inworld serve graph.ts")}`
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")}`
2711
3244
  );
2712
3245
  }
2713
- if (selectedTemplate.metadata.requirements?.apiKeys) {
2714
- console.log();
2715
- print("\u{1F4A1} Remember to set your API keys before running!");
2716
- }
3246
+ process.exit(0);
2717
3247
  } catch (error) {
2718
3248
  printError("\u274C Error initializing project:");
2719
3249
  console.error(error);
@@ -2721,22 +3251,23 @@ Project name (${selectedTemplate.metadata.defaultProjectName}): `,
2721
3251
  }
2722
3252
  };
2723
3253
  var makeInitCommand = (description) => {
2724
- const availableTemplates = getAvailableTemplatesWithMetadata();
2725
- return new Command8("init").description(description).option("-n, --name <name>", "Name of the project directory").option(
3254
+ return new Command11("init").description(description).option("-n, --name <name>", "Name of the project directory").option(
2726
3255
  "-t, --template <template>",
2727
- `Template to use: ${availableTemplates.map((t) => `"${t.directory}"`).join(" or ")}`
2728
- ).option("-l, --list-templates", "List all available templates").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);
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);
2729
3261
  };
2730
3262
  var initCommand = makeInitCommand(
2731
- "Initialize a new Inworld graph project (interactive if no options provided)"
3263
+ "Initialize a new project from a template (downloads complete app from GitHub)"
2732
3264
  );
2733
3265
  var initCommandAlias = makeInitCommand(
2734
- `Alias for "${chalk9.bold("inworld graph init")}"`
3266
+ `Alias for "${bold("inworld graph init")}"`
2735
3267
  );
2736
3268
 
2737
3269
  // src/commands/graph/graph_run_command.ts
2738
- import chalk10 from "chalk";
2739
- import { Command as Command9 } from "commander";
3270
+ import { Command as Command12 } from "commander";
2740
3271
  var runAction = async (file, request) => {
2741
3272
  try {
2742
3273
  const { graph } = await loadGraph(file);
@@ -2756,7 +3287,7 @@ var runAction = async (file, request) => {
2756
3287
  }
2757
3288
  };
2758
3289
  var makeRunCommand = (description) => {
2759
- return new Command9("run").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").argument(
3290
+ return new Command12("run").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").argument(
2760
3291
  "<request>",
2761
3292
  `
2762
3293
  Graph input, heavily depends on the exact graph. E.g.:
@@ -2780,12 +3311,11 @@ var runCommand = makeRunCommand(
2780
3311
  "Runs single execution against provided Inworld graph. Uses same input and output protocol as http server."
2781
3312
  );
2782
3313
  var runCommandAlias = makeRunCommand(
2783
- `Alias for "${chalk10.bold("inworld graph run")}"`
3314
+ `Alias for "${bold("inworld graph run")}"`
2784
3315
  );
2785
3316
 
2786
3317
  // src/commands/graph/graph_serve_command.ts
2787
- import chalk11 from "chalk";
2788
- import { Command as Command10 } from "commander";
3318
+ import { Command as Command13 } from "commander";
2789
3319
  var serveAction = async (file, options) => {
2790
3320
  try {
2791
3321
  const { graph } = await loadGraph(file);
@@ -2808,7 +3338,7 @@ var serveAction = async (file, options) => {
2808
3338
  }
2809
3339
  };
2810
3340
  var makeServeCommand = (description) => {
2811
- return new Command10("serve").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-p, --port <port>", "Port to run the server on", "3000").option("--host <host>", "Host to bind the server to", "localhost").option(
3341
+ return new Command13("serve").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-p, --port <port>", "Port to run the server on", "3000").option("--host <host>", "Host to bind the server to", "localhost").option(
2812
3342
  "-t, --transport <transport>",
2813
3343
  "Transport protocol (http or grpc)",
2814
3344
  "http"
@@ -2822,17 +3352,17 @@ var serveCommand = makeServeCommand(
2822
3352
  "Start a server that wraps an Inworld Runtime graph"
2823
3353
  );
2824
3354
  var serveCommandAlias = makeServeCommand(
2825
- `Alias for "${chalk11.bold("inworld graph serve")}"`
3355
+ `Alias for "${bold("inworld graph serve")}"`
2826
3356
  );
2827
3357
 
2828
3358
  // src/commands/graph_command.ts
2829
- import { Command as Command16 } from "commander";
3359
+ import { Command as Command19 } from "commander";
2830
3360
 
2831
3361
  // src/commands/graph/graph_variant_command.ts
2832
- import { Command as Command14 } from "commander";
3362
+ import { Command as Command17 } from "commander";
2833
3363
 
2834
3364
  // src/commands/graph/variant/graph_variant_list_command.ts
2835
- import { Command as Command11 } from "commander";
3365
+ import { Command as Command14 } from "commander";
2836
3366
 
2837
3367
  // src/services/graph_variant_service.ts
2838
3368
  var listGraphVariants = async (graphId) => {
@@ -2894,6 +3424,7 @@ var registerGraphVariant = async (graphId, variantDisplayName, variantConfig, fo
2894
3424
  var listVariantsAction = async (file) => {
2895
3425
  const workspaceId = await requireWorkspace();
2896
3426
  const { graph } = await loadGraph(file);
3427
+ graph.stopRuntime();
2897
3428
  const variants = await listGraphVariants(graph.graphId);
2898
3429
  if (!variants || variants.graphVariants?.length === 0) {
2899
3430
  console.log();
@@ -2903,26 +3434,27 @@ var listVariantsAction = async (file) => {
2903
3434
  return;
2904
3435
  }
2905
3436
  console.log();
2906
- header(
3437
+ printHeader(
2907
3438
  `Registered variants of the graph "${graph.graphId}" in workspace "${workspaceId}":`
2908
3439
  );
2909
3440
  variants.graphVariants?.forEach((variant) => {
2910
- listItem(`${variant.name} - ${variant.displayName}`);
3441
+ printListItem(`${variant.name} - ${variant.displayName}`);
2911
3442
  });
2912
3443
  };
2913
- var graphListVariantsCommand = new Command11("list").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").action(listVariantsAction);
3444
+ var graphListVariantsCommand = new Command14("list").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").action(listVariantsAction);
2914
3445
 
2915
3446
  // src/commands/graph/variant/graph_variant_print_command.ts
2916
- import { Command as Command12 } from "commander";
2917
- import path4 from "path";
3447
+ import { Command as Command15 } from "commander";
3448
+ import path5 from "path";
2918
3449
  var graphVariantPrintAction = async (file, options) => {
2919
3450
  try {
2920
3451
  const { graph } = await loadGraph(file);
3452
+ graph.stopRuntime();
2921
3453
  const jsonResult = await graph.toJSON();
2922
3454
  if (options.output) {
2923
- const outputPath = path4.resolve(options.output);
2924
- const fs4 = await import("fs/promises");
2925
- 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);
2926
3458
  success(`JSON saved to ${outputPath}`);
2927
3459
  } else {
2928
3460
  console.log(jsonResult);
@@ -2933,17 +3465,17 @@ var graphVariantPrintAction = async (file, options) => {
2933
3465
  process.exit(1);
2934
3466
  }
2935
3467
  };
2936
- var graphVariantPrintCommand = new Command12("print").description("Print JSON representation of the graph variant").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
3468
+ var graphVariantPrintCommand = new Command15("print").description("Print JSON representation of the graph variant").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
2937
3469
  "-o, --output <file>",
2938
3470
  "Output file path (if not specified, outputs to console)"
2939
3471
  ).action(graphVariantPrintAction);
2940
3472
 
2941
3473
  // src/commands/graph/variant/graph_variant_register_command.ts
2942
- import chalk12 from "chalk";
2943
- import { Command as Command13 } from "commander";
3474
+ import { Command as Command16 } from "commander";
2944
3475
  var registerVariantsAction = async (file, options) => {
2945
3476
  const workspaceId = await requireWorkspace();
2946
3477
  const { graph } = await loadGraph(file);
3478
+ graph.stopRuntime();
2947
3479
  let response = await registerGraphVariant(
2948
3480
  graph.graphId,
2949
3481
  options.displayName,
@@ -2967,7 +3499,7 @@ var registerVariantsAction = async (file, options) => {
2967
3499
  );
2968
3500
  console.log();
2969
3501
  print(
2970
- `Now you can open ${chalk12.cyan.underline(uri)} and setup targeting for different variants`
3502
+ `Now you can open ${link(uri)} and setup targeting for different variants`
2971
3503
  );
2972
3504
  } else {
2973
3505
  if (isGrpcError(response) && response.code === 6 /* ALREADY_EXISTS */) {
@@ -2980,45 +3512,45 @@ var registerVariantsAction = async (file, options) => {
2980
3512
  }
2981
3513
  }
2982
3514
  };
2983
- var graphVariantRegisterCommand = new Command13("register").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").requiredOption(
3515
+ var graphVariantRegisterCommand = new Command16("register").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").requiredOption(
2984
3516
  "-d, --display-name <variantDisplayName>",
2985
3517
  "The display name of the variant"
2986
3518
  ).option("-f, --force", "Updates the variant if it already exists", false).action(registerVariantsAction);
2987
3519
 
2988
3520
  // src/commands/graph/graph_variant_command.ts
2989
- var graphVariantCommand = new Command14("variant").description("Manage Inworld graph variants").addCommand(graphListVariantsCommand).addCommand(graphVariantRegisterCommand).addCommand(graphVariantPrintCommand).action(() => {
3521
+ var graphVariantCommand = new Command17("variant").description("Manage Inworld graph variants").addCommand(graphListVariantsCommand).addCommand(graphVariantRegisterCommand).addCommand(graphVariantPrintCommand).action(() => {
2990
3522
  graphVariantCommand.help();
2991
3523
  });
2992
3524
 
2993
3525
  // src/commands/graph/graph_visualize_command.ts
2994
- import { Command as Command15 } from "commander";
2995
- import path5 from "path";
3526
+ import { Command as Command18 } from "commander";
3527
+ import path6 from "path";
2996
3528
  var visualizeAction = async (file, options) => {
2997
3529
  try {
2998
3530
  const { graph } = await loadGraph(file);
2999
- const outputPath = path5.resolve(options.output);
3000
- print(`Storing graph visualization to ${outputPath}`);
3001
- await graph.visualize(outputPath);
3531
+ print(`Storing graph visualization to ${path6.resolve(options.output)}`);
3532
+ await graph.visualize(options.output);
3533
+ await graph.stopRuntime();
3002
3534
  } catch (error) {
3003
3535
  printError("Error visualizing graph:");
3004
3536
  console.error(error);
3005
3537
  process.exit(1);
3006
3538
  }
3007
3539
  };
3008
- var visualizeCommand = new Command15("visualize").description("Generate a visualization of an Inworld Runtime graph").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
3540
+ var visualizeCommand = new Command18("visualize").description("Generate a visualization of an Inworld Runtime graph").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
3009
3541
  "-o, --output <file>",
3010
3542
  "Output file path (if not specified, outputs to graph.png in current directory)",
3011
3543
  "./graph.png"
3012
3544
  ).action(visualizeAction);
3013
3545
 
3014
3546
  // src/commands/graph_command.ts
3015
- var graphCommand = new Command16("graph").description("Manage Inworld graph projects").addCommand(initCommand).addCommand(serveCommand).addCommand(runCommand).addCommand(deployCommand).addCommand(visualizeCommand).addCommand(graphVariantCommand).action(() => {
3547
+ var graphCommand = new Command19("graph").description("Manage Inworld graph projects").addCommand(initCommand).addCommand(serveCommand).addCommand(runCommand).addCommand(deployCommand).addCommand(visualizeCommand).addCommand(graphVariantCommand).action(() => {
3016
3548
  graphCommand.help();
3017
3549
  });
3018
3550
 
3019
3551
  // src/commands/tts_commands.ts
3020
- import chalk13 from "chalk";
3021
- import { Command as Command17 } from "commander";
3552
+ import chalk4 from "chalk";
3553
+ import { Command as Command20 } from "commander";
3022
3554
  import { writeFile } from "fs/promises";
3023
3555
  import { resolve } from "path";
3024
3556
 
@@ -3289,7 +3821,7 @@ function wrapText(text, maxWidth) {
3289
3821
  if (currentLine) lines.push(currentLine);
3290
3822
  return lines;
3291
3823
  }
3292
- var listVoicesCommand = new Command17("list-voices").description("List all available voices from the workspace").option("-f, --filter <filter>", 'Filter voices (e.g., "language=en")').option("-j, --json", "Output as JSON").option("-c, --compact", "Compact output (voice IDs only)").action(async (options) => {
3824
+ var listVoicesCommand = new Command20("list-voices").description("List all available voices from the workspace").option("-f, --filter <filter>", 'Filter voices (e.g., "language=en")').option("-j, --json", "Output as JSON").option("-c, --compact", "Compact output (voice IDs only)").action(async (options) => {
3293
3825
  try {
3294
3826
  const response = await ttsService.listVoices(options.filter);
3295
3827
  if (options.json) {
@@ -3298,15 +3830,15 @@ var listVoicesCommand = new Command17("list-voices").description("List all avail
3298
3830
  return;
3299
3831
  }
3300
3832
  if (!response.voices || response.voices.length === 0) {
3301
- console.log(chalk13.yellow("\u26A0\uFE0F No voices found"));
3833
+ console.log(chalk4.yellow("\u26A0\uFE0F No voices found"));
3302
3834
  process.exit(0);
3303
3835
  return;
3304
3836
  }
3305
3837
  if (options.compact) {
3306
- console.log("\n" + chalk13.bold.green("\u{1F3A4} Available Voice IDs:"));
3307
- console.log(chalk13.gray("\u2500".repeat(50)));
3838
+ console.log("\n" + chalk4.bold.green("\u{1F3A4} Available Voice IDs:"));
3839
+ console.log(chalk4.gray("\u2500".repeat(50)));
3308
3840
  response.voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
3309
- console.log(` ${chalk13.cyan("\u2022")} ${voice.voiceId}`);
3841
+ console.log(` ${chalk4.cyan("\u2022")} ${voice.voiceId}`);
3310
3842
  });
3311
3843
  console.log();
3312
3844
  process.exit(0);
@@ -3322,13 +3854,13 @@ var listVoicesCommand = new Command17("list-voices").description("List all avail
3322
3854
  voicesByLanguage.get(primaryLang).push(voice);
3323
3855
  });
3324
3856
  const sortedLanguages = Array.from(voicesByLanguage.keys()).sort();
3325
- console.log("\n" + chalk13.bold.green("Available TTS Voices"));
3857
+ console.log("\n" + chalk4.bold.green("Available TTS Voices"));
3326
3858
  console.log(
3327
- chalk13.gray(
3859
+ chalk4.gray(
3328
3860
  `Found ${response.voices.length} voices across ${sortedLanguages.length} languages`
3329
3861
  )
3330
3862
  );
3331
- console.log(chalk13.gray("\u2500".repeat(80)));
3863
+ console.log(chalk4.gray("\u2500".repeat(80)));
3332
3864
  sortedLanguages.forEach((lang, langIndex) => {
3333
3865
  const voices = voicesByLanguage.get(lang);
3334
3866
  const languageFlags = {
@@ -3348,19 +3880,19 @@ var listVoicesCommand = new Command17("list-voices").description("List all avail
3348
3880
  const flag = languageFlags[lang] || "\u{1F310}";
3349
3881
  console.log(
3350
3882
  `
3351
- ${flag} ${chalk13.bold.yellow(lang.toUpperCase())} ${chalk13.gray(`(${voices.length} voices)`)}`
3883
+ ${flag} ${chalk4.bold.yellow(lang.toUpperCase())} ${chalk4.gray(`(${voices.length} voices)`)}`
3352
3884
  );
3353
- console.log(chalk13.gray("\u2500".repeat(80)));
3885
+ console.log(chalk4.gray("\u2500".repeat(80)));
3354
3886
  voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
3355
- const displayName = voice.displayName && voice.displayName !== voice.voiceId ? chalk13.gray(` (${voice.displayName})`) : "";
3887
+ const displayName = voice.displayName && voice.displayName !== voice.voiceId ? chalk4.gray(` (${voice.displayName})`) : "";
3356
3888
  console.log(
3357
- ` ${chalk13.cyan("\u25B8")} ${chalk13.bold.white(voice.voiceId)}${displayName}`
3889
+ ` ${chalk4.cyan("\u25B8")} ${chalk4.bold.white(voice.voiceId)}${displayName}`
3358
3890
  );
3359
3891
  if (voice.description) {
3360
3892
  const maxWidth = 76;
3361
3893
  const descriptionLines = wrapText(voice.description, maxWidth);
3362
3894
  descriptionLines.forEach((line) => {
3363
- console.log(` ${chalk13.gray(line)}`);
3895
+ console.log(` ${chalk4.gray(line)}`);
3364
3896
  });
3365
3897
  }
3366
3898
  });
@@ -3368,26 +3900,26 @@ ${flag} ${chalk13.bold.yellow(lang.toUpperCase())} ${chalk13.gray(`(${voices.le
3368
3900
  console.log();
3369
3901
  }
3370
3902
  });
3371
- console.log("\n" + chalk13.gray("\u2500".repeat(80)));
3372
- console.log(chalk13.gray("Tips:"));
3903
+ console.log("\n" + chalk4.gray("\u2500".repeat(80)));
3904
+ console.log(chalk4.gray("Tips:"));
3373
3905
  console.log(
3374
- chalk13.gray(' \u2022 Use --filter "language=<code>" to filter by language')
3906
+ chalk4.gray(' \u2022 Use --filter "language=<code>" to filter by language')
3375
3907
  );
3376
3908
  console.log(
3377
- chalk13.gray(" \u2022 Use --compact for a simple list of voice IDs")
3909
+ chalk4.gray(" \u2022 Use --compact for a simple list of voice IDs")
3378
3910
  );
3379
- console.log(chalk13.gray(" \u2022 Use --json for machine-readable output"));
3911
+ console.log(chalk4.gray(" \u2022 Use --json for machine-readable output"));
3380
3912
  console.log(
3381
- chalk13.gray('\nExample: inworld tts list-voices --filter "language=en"')
3913
+ chalk4.gray('\nExample: inworld tts list-voices --filter "language=en"')
3382
3914
  );
3383
3915
  console.log();
3384
3916
  } catch (error) {
3385
- console.error(chalk13.red("\u274C Error listing voices:"), error);
3917
+ console.error(chalk4.red("\u274C Error listing voices:"), error);
3386
3918
  process.exit(1);
3387
3919
  }
3388
3920
  process.exit(0);
3389
3921
  });
3390
- var synthesizeCommand = new Command17("synthesize").description("Synthesize text to speech").argument("<text>", "Text to synthesize (max 2000 characters)").requiredOption(
3922
+ var synthesizeCommand = new Command20("synthesize").description("Synthesize text to speech").argument("<text>", "Text to synthesize (max 2000 characters)").requiredOption(
3391
3923
  "-v, --voice <voiceId>",
3392
3924
  "Voice ID to use for synthesis",
3393
3925
  "Dennis"
@@ -3402,14 +3934,14 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3402
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) => {
3403
3935
  try {
3404
3936
  if (text.length > 2e3) {
3405
- console.error(chalk13.red("\u274C Error: Text exceeds 2000 character limit"));
3406
- console.log(chalk13.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`));
3407
3939
  process.exit(1);
3408
3940
  }
3409
3941
  const temperature = parseFloat(options.temperature);
3410
3942
  if (isNaN(temperature) || temperature < 0 || temperature > 2) {
3411
3943
  console.error(
3412
- chalk13.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")
3413
3945
  );
3414
3946
  process.exit(1);
3415
3947
  }
@@ -3418,10 +3950,10 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3418
3950
  "inworld-tts-1-max": "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */
3419
3951
  };
3420
3952
  const modelId = modelMap[options.model] || "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */;
3421
- console.log(chalk13.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
3422
- console.log(chalk13.gray(`Voice: ${options.voice}`));
3423
- console.log(chalk13.gray(`Model: ${options.model}`));
3424
- console.log(chalk13.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`));
3425
3957
  const request = {
3426
3958
  text,
3427
3959
  voiceId: options.voice,
@@ -3444,15 +3976,15 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3444
3976
  fileExtension = ".wav";
3445
3977
  if (options.format === "MP3") {
3446
3978
  console.log(
3447
- chalk13.yellow(
3979
+ chalk4.yellow(
3448
3980
  "\u26A0\uFE0F Warning: MP3 streaming requires special handling."
3449
3981
  )
3450
3982
  );
3451
3983
  console.log(
3452
- chalk13.yellow(" Audio chunks may not concatenate perfectly.")
3984
+ chalk4.yellow(" Audio chunks may not concatenate perfectly.")
3453
3985
  );
3454
3986
  console.log(
3455
- chalk13.yellow(
3987
+ chalk4.yellow(
3456
3988
  " Consider using LINEAR16 or OGG_OPUS for better streaming."
3457
3989
  )
3458
3990
  );
@@ -3465,8 +3997,8 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3465
3997
  streamFormat = "LINEAR16";
3466
3998
  fileExtension = ".wav";
3467
3999
  }
3468
- console.log(chalk13.cyan("\u{1F504} Using streaming synthesis..."));
3469
- console.log(chalk13.gray(`Format: ${streamFormat}${fileExtension}`));
4000
+ console.log(chalk4.cyan("\u{1F504} Using streaming synthesis..."));
4001
+ console.log(chalk4.gray(`Format: ${streamFormat}${fileExtension}`));
3470
4002
  const streamRequest = {
3471
4003
  ...request,
3472
4004
  audioConfig: {
@@ -3496,7 +4028,7 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3496
4028
  if (chunk.error) {
3497
4029
  streamError = chunk.error;
3498
4030
  console.error(
3499
- chalk13.red(`\u274C Stream error: ${chunk.error.message}`)
4031
+ chalk4.red(`\u274C Stream error: ${chunk.error.message}`)
3500
4032
  );
3501
4033
  } else {
3502
4034
  if (chunk.audioContent) {
@@ -3521,7 +4053,7 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3521
4053
  if (!options.json && !options.stats) {
3522
4054
  const chunkSizeKB = (chunkBuffer.length / 1024).toFixed(2);
3523
4055
  process.stdout.write(
3524
- chalk13.gray(
4056
+ chalk4.gray(
3525
4057
  `\rReceived chunk ${chunkCount} (${chunkSizeKB} KB)...`
3526
4058
  )
3527
4059
  );
@@ -3603,34 +4135,30 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3603
4135
  options.output || `output${fileExtension}`
3604
4136
  );
3605
4137
  await writeFile(outputPath, audioBuffer);
3606
- console.log(chalk13.green(`\u2705 Audio saved to: ${outputPath}`));
4138
+ console.log(chalk4.green(`\u2705 Audio saved to: ${outputPath}`));
3607
4139
  console.log(
3608
- chalk13.gray(
4140
+ chalk4.gray(
3609
4141
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
3610
4142
  )
3611
4143
  );
3612
- console.log(chalk13.gray(`Chunks received: ${chunkCount}`));
4144
+ console.log(chalk4.gray(`Chunks received: ${chunkCount}`));
3613
4145
  if (allWordAlignments.words.length > 0) {
3614
4146
  console.log(
3615
- chalk13.gray(
4147
+ chalk4.gray(
3616
4148
  `Word timestamps collected: ${allWordAlignments.words.length}`
3617
4149
  )
3618
4150
  );
3619
4151
  }
3620
4152
  if (allCharacterAlignments.characters.length > 0) {
3621
4153
  console.log(
3622
- chalk13.gray(
4154
+ chalk4.gray(
3623
4155
  `Character timestamps collected: ${allCharacterAlignments.characters.length}`
3624
4156
  )
3625
4157
  );
3626
4158
  }
3627
4159
  }
3628
4160
  } else {
3629
- console.log(chalk13.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
3630
- console.log(chalk13.gray(`Voice: ${options.voice}`));
3631
- console.log(chalk13.gray(`Model: ${options.model}`));
3632
- console.log(chalk13.gray(`Text length: ${text.length} characters`));
3633
- console.log(chalk13.gray(`Format: ${options.format || "MP3 (default)"}`));
4161
+ console.log(chalk4.gray(`Format: ${options.format || "MP3 (default)"}`));
3634
4162
  if (options.format === "LINEAR16") {
3635
4163
  fileExtension = ".wav";
3636
4164
  } else if (options.format === "OGG_OPUS") {
@@ -3649,9 +4177,9 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3649
4177
  options.output || `output${fileExtension}`
3650
4178
  );
3651
4179
  await writeFile(outputPath, audioBuffer);
3652
- console.log(chalk13.green(`\u2705 Audio saved to: ${outputPath}`));
4180
+ console.log(chalk4.green(`\u2705 Audio saved to: ${outputPath}`));
3653
4181
  console.log(
3654
- chalk13.gray(
4182
+ chalk4.gray(
3655
4183
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
3656
4184
  )
3657
4185
  );
@@ -3667,25 +4195,25 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3667
4195
  if (isStreaming) {
3668
4196
  const sm = m;
3669
4197
  console.log(
3670
- "\n" + chalk13.cyan("\u{1F4CA} Streaming Performance Statistics:")
4198
+ "\n" + chalk4.cyan("\u{1F4CA} Streaming Performance Statistics:")
3671
4199
  );
3672
- console.log(chalk13.gray("\u2550".repeat(50)));
3673
- console.log(chalk13.bold.white("\n Streaming Timeline:"));
3674
- console.log(chalk13.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)));
3675
4203
  console.log(
3676
- chalk13.white(" \u23F1\uFE0F Time to First Chunk: ") + chalk13.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
4204
+ chalk4.white(" \u23F1\uFE0F Time to First Chunk: ") + chalk4.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
3677
4205
  );
3678
4206
  console.log(
3679
- chalk13.white(" \u23F2\uFE0F Total Stream Time: ") + chalk13.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
4207
+ chalk4.white(" \u23F2\uFE0F Total Stream Time: ") + chalk4.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
3680
4208
  );
3681
- console.log(chalk13.bold.white("\n Chunk Statistics:"));
3682
- console.log(chalk13.gray(" \u2500".repeat(23)));
4209
+ console.log(chalk4.bold.white("\n Chunk Statistics:"));
4210
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3683
4211
  console.log(
3684
- chalk13.white(" \u{1F4E6} Chunks Received: ") + chalk13.yellow(`${sm.chunksReceived}`)
4212
+ chalk4.white(" \u{1F4E6} Chunks Received: ") + chalk4.yellow(`${sm.chunksReceived}`)
3685
4213
  );
3686
4214
  if (sm.errorChunks > 0) {
3687
4215
  console.log(
3688
- chalk13.white(" \u26A0\uFE0F Error Chunks: ") + chalk13.red(`${sm.errorChunks}`)
4216
+ chalk4.white(" \u26A0\uFE0F Error Chunks: ") + chalk4.red(`${sm.errorChunks}`)
3689
4217
  );
3690
4218
  }
3691
4219
  if (sm.chunkSizes.length > 0) {
@@ -3693,10 +4221,10 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3693
4221
  const minChunkSize = Math.min(...sm.chunkSizes);
3694
4222
  const maxChunkSize = Math.max(...sm.chunkSizes);
3695
4223
  console.log(
3696
- chalk13.white(" \u{1F4CF} Avg Chunk Size: ") + chalk13.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
4224
+ chalk4.white(" \u{1F4CF} Avg Chunk Size: ") + chalk4.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
3697
4225
  );
3698
4226
  console.log(
3699
- chalk13.gray(" Min/Max: ") + chalk13.gray(
4227
+ chalk4.gray(" Min/Max: ") + chalk4.gray(
3700
4228
  `${(minChunkSize / 1024).toFixed(2)} - ${(maxChunkSize / 1024).toFixed(2)} KB`
3701
4229
  )
3702
4230
  );
@@ -3706,126 +4234,126 @@ var synthesizeCommand = new Command17("synthesize").description("Synthesize text
3706
4234
  const minInterval = Math.min(...sm.chunkIntervals);
3707
4235
  const maxInterval = Math.max(...sm.chunkIntervals);
3708
4236
  console.log(
3709
- chalk13.white(" \u23F3 Avg Chunk Interval: ") + chalk13.yellow(`${avgInterval.toFixed(0)} ms`)
4237
+ chalk4.white(" \u23F3 Avg Chunk Interval: ") + chalk4.yellow(`${avgInterval.toFixed(0)} ms`)
3710
4238
  );
3711
4239
  console.log(
3712
- chalk13.gray(" Min/Max: ") + chalk13.gray(
4240
+ chalk4.gray(" Min/Max: ") + chalk4.gray(
3713
4241
  `${minInterval.toFixed(0)} - ${maxInterval.toFixed(0)} ms`
3714
4242
  )
3715
4243
  );
3716
4244
  }
3717
- console.log(chalk13.bold.white("\n Data Transfer:"));
3718
- console.log(chalk13.gray(" \u2500".repeat(23)));
4245
+ console.log(chalk4.bold.white("\n Data Transfer:"));
4246
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3719
4247
  console.log(
3720
- chalk13.white(" \u{1F4E5} Total Data: ") + chalk13.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
4248
+ chalk4.white(" \u{1F4E5} Total Data: ") + chalk4.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
3721
4249
  );
3722
4250
  console.log(
3723
- chalk13.white(" \u{1F3B5} Audio File: ") + chalk13.yellow(
4251
+ chalk4.white(" \u{1F3B5} Audio File: ") + chalk4.yellow(
3724
4252
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
3725
4253
  )
3726
4254
  );
3727
- console.log(chalk13.bold.white("\n Performance Metrics:"));
3728
- console.log(chalk13.gray(" \u2500".repeat(23)));
4255
+ console.log(chalk4.bold.white("\n Performance Metrics:"));
4256
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3729
4257
  const throughputKBps = sm.totalBytes / 1024 / (sm.totalTime / 1e3);
3730
4258
  console.log(
3731
- chalk13.white(" \u{1F4F6} Stream Throughput: ") + chalk13.yellow(`${throughputKBps.toFixed(2)} KB/s`)
4259
+ chalk4.white(" \u{1F4F6} Stream Throughput: ") + chalk4.yellow(`${throughputKBps.toFixed(2)} KB/s`)
3732
4260
  );
3733
4261
  const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
3734
4262
  const realTimeRatio = audioDuration / (sm.totalTime / 1e3);
3735
4263
  console.log(
3736
- chalk13.white(" \u{1F3B5} Audio Duration: ") + chalk13.yellow(`${audioDuration.toFixed(2)} seconds`)
4264
+ chalk4.white(" \u{1F3B5} Audio Duration: ") + chalk4.yellow(`${audioDuration.toFixed(2)} seconds`)
3737
4265
  );
3738
4266
  console.log(
3739
- chalk13.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk13.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk13.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`))
3740
4268
  );
3741
4269
  const streamingEfficiency = (sm.totalTime - sm.timeToFirstChunk) / sm.totalTime * 100;
3742
4270
  console.log(
3743
- chalk13.white(" \u{1F4C8} Stream Efficiency: ") + chalk13.yellow(`${streamingEfficiency.toFixed(1)}%`)
4271
+ chalk4.white(" \u{1F4C8} Stream Efficiency: ") + chalk4.yellow(`${streamingEfficiency.toFixed(1)}%`)
3744
4272
  );
3745
- console.log(chalk13.gray("\u2550".repeat(50)));
4273
+ console.log(chalk4.gray("\u2550".repeat(50)));
3746
4274
  } else {
3747
- console.log("\n" + chalk13.cyan("\u{1F4CA} Performance Statistics:"));
3748
- console.log(chalk13.gray("\u2550".repeat(50)));
3749
- console.log(chalk13.bold.white("\n Network Timing:"));
3750
- console.log(chalk13.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)));
3751
4279
  console.log(
3752
- chalk13.white(" \u23F1\uFE0F Time to First Byte: ") + chalk13.yellow(`${m.ttfb.toFixed(0)} ms`)
4280
+ chalk4.white(" \u23F1\uFE0F Time to First Byte: ") + chalk4.yellow(`${m.ttfb.toFixed(0)} ms`)
3753
4281
  );
3754
4282
  if (m.downloadTime !== void 0) {
3755
4283
  console.log(
3756
- chalk13.white(" \u2B07\uFE0F Content Download: ") + chalk13.yellow(`${m.downloadTime.toFixed(0)} ms`)
4284
+ chalk4.white(" \u2B07\uFE0F Content Download: ") + chalk4.yellow(`${m.downloadTime.toFixed(0)} ms`)
3757
4285
  );
3758
4286
  }
3759
4287
  console.log(
3760
- chalk13.white(" \u23F2\uFE0F Total Time: ") + chalk13.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
4288
+ chalk4.white(" \u23F2\uFE0F Total Time: ") + chalk4.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
3761
4289
  );
3762
- console.log(chalk13.bold.white("\n Data Transfer:"));
3763
- console.log(chalk13.gray(" \u2500".repeat(23)));
4290
+ console.log(chalk4.bold.white("\n Data Transfer:"));
4291
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3764
4292
  if (m.requestSize) {
3765
4293
  console.log(
3766
- chalk13.white(" \u2B06\uFE0F Request Size: ") + chalk13.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
4294
+ chalk4.white(" \u2B06\uFE0F Request Size: ") + chalk4.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
3767
4295
  );
3768
4296
  }
3769
4297
  console.log(
3770
- chalk13.white(" \u2B07\uFE0F Response Size: ") + chalk13.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
4298
+ chalk4.white(" \u2B07\uFE0F Response Size: ") + chalk4.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
3771
4299
  );
3772
4300
  console.log(
3773
- chalk13.white(" \u{1F3B5} Audio File: ") + chalk13.yellow(
4301
+ chalk4.white(" \u{1F3B5} Audio File: ") + chalk4.yellow(
3774
4302
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
3775
4303
  )
3776
4304
  );
3777
- console.log(chalk13.bold.white("\n Performance Metrics:"));
3778
- console.log(chalk13.gray(" \u2500".repeat(23)));
4305
+ console.log(chalk4.bold.white("\n Performance Metrics:"));
4306
+ console.log(chalk4.gray(" \u2500".repeat(23)));
3779
4307
  const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
3780
4308
  const realTimeRatio = audioDuration / (m.totalTime / 1e3);
3781
4309
  const serverTime = m.ttfb;
3782
4310
  console.log(
3783
- chalk13.white(" \u{1F5A5}\uFE0F Server Processing: ") + chalk13.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`)
3784
4312
  );
3785
4313
  console.log(
3786
- chalk13.white(" \u{1F3B5} Audio Duration: ") + chalk13.yellow(`${audioDuration.toFixed(2)} seconds`)
4314
+ chalk4.white(" \u{1F3B5} Audio Duration: ") + chalk4.yellow(`${audioDuration.toFixed(2)} seconds`)
3787
4315
  );
3788
4316
  console.log(
3789
- chalk13.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk13.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk13.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`))
3790
4318
  );
3791
4319
  const throughputMbps = (m.responseSize + (audioBuffer?.length || 0)) * 8 / (m.totalTime * 1e3);
3792
4320
  console.log(
3793
- chalk13.white(" \u{1F4F6} Throughput: ") + chalk13.yellow(`${throughputMbps.toFixed(2)} Mbps`)
4321
+ chalk4.white(" \u{1F4F6} Throughput: ") + chalk4.yellow(`${throughputMbps.toFixed(2)} Mbps`)
3794
4322
  );
3795
- console.log(chalk13.gray("\u2550".repeat(50)));
4323
+ console.log(chalk4.gray("\u2550".repeat(50)));
3796
4324
  }
3797
4325
  }
3798
4326
  if (response.timestampInfo?.wordAlignment) {
3799
4327
  const alignment = response.timestampInfo.wordAlignment;
3800
- console.log("\n" + chalk13.cyan("\u{1F4DD} Word Timestamps:"));
4328
+ console.log("\n" + chalk4.cyan("\u{1F4DD} Word Timestamps:"));
3801
4329
  alignment.words.forEach((word, i) => {
3802
4330
  const start = alignment.wordStartTimeSeconds[i].toFixed(3);
3803
4331
  const end = alignment.wordEndTimeSeconds[i].toFixed(3);
3804
- console.log(chalk13.gray(` ${start}s - ${end}s: ${word}`));
4332
+ console.log(chalk4.gray(` ${start}s - ${end}s: ${word}`));
3805
4333
  });
3806
4334
  }
3807
4335
  if (response.timestampInfo?.characterAlignment) {
3808
- console.log("\n" + chalk13.cyan("\u{1F4DD} Character Timestamps:"));
4336
+ console.log("\n" + chalk4.cyan("\u{1F4DD} Character Timestamps:"));
3809
4337
  console.log(
3810
- chalk13.gray(
4338
+ chalk4.gray(
3811
4339
  " (Too detailed to display - use --json to see full data)"
3812
4340
  )
3813
4341
  );
3814
4342
  }
3815
4343
  process.exit(0);
3816
4344
  } catch (error) {
3817
- console.error(chalk13.red("\u274C Error synthesizing speech:"));
3818
- console.error(chalk13.red(error.message || error));
4345
+ console.error(chalk4.red("\u274C Error synthesizing speech:"));
4346
+ console.error(chalk4.red(error.message || error));
3819
4347
  process.exit(1);
3820
4348
  }
3821
4349
  });
3822
- var ttsCommand = new Command17("tts").description("Text-to-speech functionality").addCommand(listVoicesCommand).addCommand(synthesizeCommand).action(() => {
4350
+ var ttsCommand = new Command20("tts").description("Text-to-speech functionality").addCommand(listVoicesCommand).addCommand(synthesizeCommand).action(() => {
3823
4351
  ttsCommand.help();
3824
4352
  });
3825
4353
 
3826
4354
  // src/commands/workspace_command.ts
3827
- import { Command as Command18 } from "commander";
3828
- var selectWorkspaceCommand = new Command18("select").description("Select a workspace for CLI operations").action(async () => {
4355
+ import { Command as Command21 } from "commander";
4356
+ var selectWorkspaceCommand = new Command21("select").description("Select a workspace for CLI operations").action(async () => {
3829
4357
  await requireAuth();
3830
4358
  try {
3831
4359
  await WorkspaceService.activateWorkspace();
@@ -3835,17 +4363,140 @@ var selectWorkspaceCommand = new Command18("select").description("Select a works
3835
4363
  process.exit(1);
3836
4364
  }
3837
4365
  });
3838
- var workspaceCommand = new Command18("workspace").description("Manage Inworld workspaces").alias("ws").addCommand(selectWorkspaceCommand).action(() => {
4366
+ var workspaceCommand = new Command21("workspace").description("Manage Inworld workspaces").alias("ws").addCommand(selectWorkspaceCommand).action(() => {
3839
4367
  workspaceCommand.help();
3840
4368
  });
3841
4369
 
3842
- // index.ts
4370
+ // src/services/update_checker.ts
4371
+ import Conf3 from "conf";
4372
+ import * as semver from "semver";
4373
+ var UpdateChecker = class _UpdateChecker {
4374
+ static PACKAGE_NAME = "@inworld/cli";
4375
+ static CHECK_INTERVAL = 24 * 60 * 60 * 1e3;
4376
+ // 24 hours
4377
+ static NPM_REGISTRY_URL = "https://registry.npmjs.org";
4378
+ static REQUEST_TIMEOUT = 3e3;
4379
+ // 3 seconds
4380
+ static CONF_ENTRY_NAME = "updateCheck";
4381
+ conf;
4382
+ constructor() {
4383
+ this.conf = new Conf3({
4384
+ projectName: "inworld-cli-config"
4385
+ });
4386
+ }
4387
+ /**
4388
+ * Checks if an update is available and displays a notification if needed.
4389
+ * This method is non-blocking and will not throw errors.
4390
+ */
4391
+ async checkAndNotify() {
4392
+ try {
4393
+ const shouldCheck = this.shouldCheckForUpdate();
4394
+ if (!shouldCheck) {
4395
+ const cached = this.conf.get(_UpdateChecker.CONF_ENTRY_NAME);
4396
+ if (cached) {
4397
+ const shouldUpdate2 = this.compareVersions(
4398
+ CLI_VERSION,
4399
+ cached.latestVersion
4400
+ );
4401
+ if (shouldUpdate2) {
4402
+ this.displayUpdateNotification(cached.latestVersion);
4403
+ }
4404
+ }
4405
+ return;
4406
+ }
4407
+ const latestVersion = await this.fetchLatestVersion();
4408
+ if (!latestVersion) {
4409
+ return;
4410
+ }
4411
+ const shouldUpdate = this.compareVersions(CLI_VERSION, latestVersion);
4412
+ this.conf.set("updateCheck", {
4413
+ lastChecked: Date.now(),
4414
+ latestVersion,
4415
+ shouldUpdate
4416
+ });
4417
+ if (shouldUpdate) {
4418
+ this.displayUpdateNotification(latestVersion);
4419
+ }
4420
+ } catch (_error) {
4421
+ }
4422
+ }
4423
+ /**
4424
+ * Determines if we should check for updates based on cache age
4425
+ */
4426
+ shouldCheckForUpdate() {
4427
+ const cached = this.conf.get("updateCheck");
4428
+ if (!cached) {
4429
+ return true;
4430
+ }
4431
+ const timeSinceLastCheck = Date.now() - cached.lastChecked;
4432
+ return timeSinceLastCheck > _UpdateChecker.CHECK_INTERVAL;
4433
+ }
4434
+ /**
4435
+ * Fetches the latest version from npm registry
4436
+ */
4437
+ async fetchLatestVersion() {
4438
+ try {
4439
+ const controller = new AbortController();
4440
+ const timeout = setTimeout(() => {
4441
+ controller.abort();
4442
+ }, _UpdateChecker.REQUEST_TIMEOUT);
4443
+ const response = await fetch(
4444
+ `${_UpdateChecker.NPM_REGISTRY_URL}/${_UpdateChecker.PACKAGE_NAME}/latest`,
4445
+ {
4446
+ signal: controller.signal,
4447
+ headers: {
4448
+ Accept: "application/json"
4449
+ }
4450
+ }
4451
+ );
4452
+ clearTimeout(timeout);
4453
+ if (!response.ok) {
4454
+ return null;
4455
+ }
4456
+ const data = await response.json();
4457
+ return data.version || null;
4458
+ } catch (_error) {
4459
+ return null;
4460
+ }
4461
+ }
4462
+ /**
4463
+ * Compares current version with latest version
4464
+ * Returns true if an update is available
4465
+ */
4466
+ compareVersions(current, latest) {
4467
+ try {
4468
+ const currentClean = semver.clean(current);
4469
+ const latestClean = semver.clean(latest);
4470
+ if (!currentClean || !latestClean) {
4471
+ return false;
4472
+ }
4473
+ return semver.gt(latestClean, currentClean);
4474
+ } catch (_error) {
4475
+ return false;
4476
+ }
4477
+ }
4478
+ /**
4479
+ * Displays a styled update notification to the user
4480
+ */
4481
+ displayUpdateNotification(latestVersion) {
4482
+ const lines = [
4483
+ bold("Update available! ") + `${CLI_VERSION} \u2192 ` + green(`${latestVersion}`),
4484
+ "",
4485
+ "Run " + cyan("npm install -g @inworld/cli") + " to update"
4486
+ ];
4487
+ printBox(lines, { color: "gray" });
4488
+ }
4489
+ };
4490
+ var updateChecker = new UpdateChecker();
4491
+
4492
+ // src/index.ts
3843
4493
  var version = CLI_VERSION;
3844
4494
  process.env.DISABLE_WELCOME_MESSAGE = "true";
3845
4495
  var InworldCLI = class {
3846
4496
  program;
4497
+ currentCommand = null;
3847
4498
  constructor() {
3848
- this.program = new Command19();
4499
+ this.program = new Command22();
3849
4500
  this.setupProgram();
3850
4501
  this.registerCommands();
3851
4502
  }
@@ -3855,8 +4506,44 @@ var InworldCLI = class {
3855
4506
  writeErr: (str) => process.stderr.write(str),
3856
4507
  getOutHelpWidth: () => process.stdout.columns || 80,
3857
4508
  getErrHelpWidth: () => process.stderr.columns || 80
4509
+ }).hook("preAction", (_thisCommand, actionCommand) => {
4510
+ const commandName = this.getCommandName(actionCommand);
4511
+ this.currentCommand = commandName;
4512
+ const options = actionCommand.opts();
4513
+ const sanitizedOptions = this.sanitizeOptions(options);
4514
+ analytics.trackCommandExecution(commandName, sanitizedOptions);
3858
4515
  });
3859
4516
  }
4517
+ /**
4518
+ * Gets the full command name from a Command instance
4519
+ */
4520
+ getCommandName(command) {
4521
+ let name = command.name();
4522
+ while (command.parent && command.parent.name() !== "inworld") {
4523
+ command = command.parent;
4524
+ name = `${command.name()} ${name}`;
4525
+ }
4526
+ return name;
4527
+ }
4528
+ /**
4529
+ * Sanitizes command options to remove sensitive data
4530
+ */
4531
+ sanitizeOptions(options) {
4532
+ const sanitized = {};
4533
+ const sensitiveKeys = ["token", "apikey", "password", "secret", "key"];
4534
+ for (const [key, value] of Object.entries(options)) {
4535
+ const lowerKey = key.toLowerCase();
4536
+ const isSensitive = sensitiveKeys.some((k) => lowerKey.includes(k));
4537
+ if (isSensitive) {
4538
+ sanitized[key] = "[REDACTED]";
4539
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
4540
+ sanitized[key] = value;
4541
+ } else {
4542
+ sanitized[key] = typeof value;
4543
+ }
4544
+ }
4545
+ return sanitized;
4546
+ }
3860
4547
  registerCommands() {
3861
4548
  this.program.addCommand(loginCommandAlias);
3862
4549
  this.program.addCommand(logoutCommandAlias);
@@ -3875,19 +4562,34 @@ var InworldCLI = class {
3875
4562
  }
3876
4563
  async run(args) {
3877
4564
  try {
4565
+ const initPromise = Promise.all([
4566
+ analytics.initialize().catch(() => {
4567
+ }),
4568
+ updateChecker.checkAndNotify().catch(() => {
4569
+ })
4570
+ ]);
4571
+ const timeoutPromise = new Promise(
4572
+ (resolve2) => setTimeout(resolve2, 1e3)
4573
+ );
4574
+ await Promise.race([initPromise, timeoutPromise]);
3878
4575
  await this.program.parseAsync(args);
4576
+ await analytics.flush();
3879
4577
  } catch (error) {
4578
+ if (this.currentCommand) {
4579
+ const errorMessage = error instanceof Error ? error.message : String(error);
4580
+ analytics.trackCommandResult(this.currentCommand, false, errorMessage);
4581
+ }
3880
4582
  console.error(
3881
- chalk14.red("Error:"),
4583
+ chalk5.red("Error:"),
3882
4584
  error instanceof Error ? error.message : String(error)
3883
4585
  );
4586
+ await analytics.flush();
3884
4587
  process.exit(1);
3885
4588
  }
3886
4589
  }
3887
4590
  };
3888
4591
  var cli = new InworldCLI();
3889
4592
  cli.run().catch((error) => {
3890
- console.error(chalk14.red("Fatal error:"), error);
4593
+ console.error(chalk5.red("Fatal error:"), error);
3891
4594
  process.exit(1);
3892
4595
  });
3893
- //# sourceMappingURL=index.js.map