@inworld/cli 0.3.1 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/index.js +820 -296
  2. package/dist/package.json +11 -7
  3. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.d.ts.map +1 -1
  4. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.js +0 -1
  5. package/dist/proto/generated/portal/ai/inworld/language_codes/language_codes.pb.js.map +1 -1
  6. package/dist/proto/generated/portal/ai/inworld/studio/v1/errors.pb.d.ts.map +1 -1
  7. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.d.ts.map +1 -1
  8. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.js +0 -1
  9. package/dist/proto/generated/portal/ai/inworld/studio/v1/operations.pb.js.map +1 -1
  10. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.d.ts.map +1 -1
  11. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.js +0 -1
  12. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graph_configuration.pb.js.map +1 -1
  13. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.d.ts.map +1 -1
  14. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.js +0 -1
  15. package/dist/proto/generated/portal/ai/inworld/studio/v1/remote/configuration/targeting.pb.js.map +1 -1
  16. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.d.ts +2 -0
  17. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.d.ts.map +1 -1
  18. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.js +0 -1
  19. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.js.map +1 -1
  20. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.d.ts.map +1 -1
  21. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.js +0 -1
  22. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/impression_event_data.pb.js.map +1 -1
  23. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.d.ts.map +1 -1
  24. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.js +0 -1
  25. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/language_code.pb.js.map +1 -1
  26. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.d.ts.map +1 -1
  27. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.js +0 -1
  28. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.js.map +1 -1
  29. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.d.ts.map +1 -1
  30. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.js +0 -1
  31. package/dist/proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.js.map +1 -1
  32. package/dist/proto/generated/portal/fetch.pb.d.ts.map +1 -1
  33. package/dist/proto/generated/portal/fetch.pb.js.map +1 -1
  34. package/dist/src/auth/manager.d.ts.map +1 -1
  35. package/dist/src/auth/manager.js +1 -3
  36. package/dist/src/auth/manager.js.map +1 -1
  37. package/dist/src/auth/utils.d.ts +1 -1
  38. package/dist/src/auth/utils.d.ts.map +1 -1
  39. package/dist/src/auth/utils.js +1 -1
  40. package/dist/src/auth/utils.js.map +1 -1
  41. package/dist/src/commands/auth/disable_telemetry_command.js +21 -0
  42. package/dist/src/commands/auth/disable_telemetry_command.js.map +1 -0
  43. package/dist/src/commands/auth/enable_telemetry_command.js +22 -0
  44. package/dist/src/commands/auth/enable_telemetry_command.js.map +1 -0
  45. package/dist/src/commands/auth/login_command.d.ts.map +1 -1
  46. package/dist/src/commands/auth/login_command.js +2 -2
  47. package/dist/src/commands/auth/login_command.js.map +1 -1
  48. package/dist/src/commands/auth/status_command.d.ts.map +1 -1
  49. package/dist/src/commands/auth/status_command.js.map +1 -1
  50. package/dist/src/commands/auth_command.js +4 -0
  51. package/dist/src/commands/auth_command.js.map +1 -1
  52. package/dist/src/commands/graph/graph_deploy_command.d.ts.map +1 -1
  53. package/dist/src/commands/graph/graph_deploy_command.js +14 -1
  54. package/dist/src/commands/graph/graph_deploy_command.js.map +1 -1
  55. package/dist/src/commands/graph/graph_init_command.d.ts.map +1 -1
  56. package/dist/src/commands/graph/graph_init_command.js +231 -272
  57. package/dist/src/commands/graph/graph_init_command.js.map +1 -1
  58. package/dist/src/commands/graph/graph_run_command.d.ts.map +1 -1
  59. package/dist/src/commands/graph/graph_run_command.js +1 -1
  60. package/dist/src/commands/graph/graph_run_command.js.map +1 -1
  61. package/dist/src/commands/graph/graph_visualize_command.d.ts.map +1 -1
  62. package/dist/src/commands/graph/graph_visualize_command.js +3 -3
  63. package/dist/src/commands/graph/graph_visualize_command.js.map +1 -1
  64. package/dist/src/commands/graph/variant/graph_variant_list_command.d.ts.map +1 -1
  65. package/dist/src/commands/graph/variant/graph_variant_list_command.js +1 -0
  66. package/dist/src/commands/graph/variant/graph_variant_list_command.js.map +1 -1
  67. package/dist/src/commands/graph/variant/graph_variant_print_command.d.ts.map +1 -1
  68. package/dist/src/commands/graph/variant/graph_variant_print_command.js +2 -1
  69. package/dist/src/commands/graph/variant/graph_variant_print_command.js.map +1 -1
  70. package/dist/src/commands/graph/variant/graph_variant_register_command.d.ts.map +1 -1
  71. package/dist/src/commands/graph/variant/graph_variant_register_command.js +1 -0
  72. package/dist/src/commands/graph/variant/graph_variant_register_command.js.map +1 -1
  73. package/dist/src/commands/tts/tts_clone_command.d.ts +6 -0
  74. package/dist/src/commands/tts/tts_clone_command.d.ts.map +1 -0
  75. package/dist/src/commands/tts/tts_clone_command.js +80 -0
  76. package/dist/src/commands/tts/tts_clone_command.js.map +1 -0
  77. package/dist/src/commands/tts/tts_design_command.d.ts +6 -0
  78. package/dist/src/commands/tts/tts_design_command.d.ts.map +1 -0
  79. package/dist/src/commands/tts/tts_design_command.js +216 -0
  80. package/dist/src/commands/tts/tts_design_command.js.map +1 -0
  81. package/dist/src/commands/tts/tts_list_voices_command.d.ts +6 -0
  82. package/dist/src/commands/tts/tts_list_voices_command.d.ts.map +1 -0
  83. package/dist/src/commands/tts/tts_list_voices_command.js +108 -0
  84. package/dist/src/commands/tts/tts_list_voices_command.js.map +1 -0
  85. package/dist/src/commands/tts/tts_synthesize_command.d.ts +6 -0
  86. package/dist/src/commands/tts/tts_synthesize_command.d.ts.map +1 -0
  87. package/dist/src/commands/tts/tts_synthesize_command.js +351 -0
  88. package/dist/src/commands/tts/tts_synthesize_command.js.map +1 -0
  89. package/dist/src/commands/tts/tts_utils.d.ts +14 -0
  90. package/dist/src/commands/tts/tts_utils.d.ts.map +1 -0
  91. package/dist/src/commands/tts/tts_utils.js +84 -0
  92. package/dist/src/commands/tts/tts_utils.js.map +1 -0
  93. package/dist/src/commands/tts_commands.d.ts +0 -11
  94. package/dist/src/commands/tts_commands.d.ts.map +1 -1
  95. package/dist/src/commands/tts_commands.js +6 -556
  96. package/dist/src/commands/tts_commands.js.map +1 -1
  97. package/dist/src/commands/workspace_command.d.ts +10 -0
  98. package/dist/src/commands/workspace_command.d.ts.map +1 -1
  99. package/dist/src/commands/workspace_command.js +39 -0
  100. package/dist/src/commands/workspace_command.js.map +1 -1
  101. package/dist/src/constants.d.ts +2 -1
  102. package/dist/src/constants.d.ts.map +1 -1
  103. package/dist/src/constants.js +19 -1
  104. package/dist/src/constants.js.map +1 -1
  105. package/dist/src/grpc/core/InworldError.d.ts.map +1 -1
  106. package/dist/src/grpc/core/InworldError.js.map +1 -1
  107. package/dist/src/index.js +139 -0
  108. package/dist/src/index.js.map +1 -0
  109. package/dist/src/services/analytics.d.ts +2 -2
  110. package/dist/src/services/analytics.d.ts.map +1 -1
  111. package/dist/src/services/analytics.js +139 -0
  112. package/dist/src/services/analytics.js.map +1 -0
  113. package/dist/src/services/deploy_service.js +1 -1
  114. package/dist/src/services/deploy_service.js.map +1 -1
  115. package/dist/src/services/graph_loader.d.ts.map +1 -1
  116. package/dist/src/services/graph_loader.js +1 -1
  117. package/dist/src/services/graph_loader.js.map +1 -1
  118. package/dist/src/services/graph_variant_service.d.ts.map +1 -1
  119. package/dist/src/services/graph_variant_service.js +1 -1
  120. package/dist/src/services/graph_variant_service.js.map +1 -1
  121. package/dist/src/services/template_service.d.ts +79 -0
  122. package/dist/src/services/template_service.d.ts.map +1 -0
  123. package/dist/src/services/template_service.js +299 -0
  124. package/dist/src/services/template_service.js.map +1 -0
  125. package/dist/src/services/tts_service.d.ts +138 -71
  126. package/dist/src/services/tts_service.d.ts.map +1 -1
  127. package/dist/src/services/tts_service.js +87 -66
  128. package/dist/src/services/tts_service.js.map +1 -1
  129. package/dist/src/services/update_checker.js +134 -0
  130. package/dist/src/services/update_checker.js.map +1 -0
  131. package/dist/src/services/workspace_service.d.ts +6 -0
  132. package/dist/src/services/workspace_service.d.ts.map +1 -1
  133. package/dist/src/services/workspace_service.js +115 -13
  134. package/dist/src/services/workspace_service.js.map +1 -1
  135. package/dist/src/utils/audio_player.d.ts +10 -0
  136. package/dist/src/utils/audio_player.d.ts.map +1 -0
  137. package/dist/src/utils/audio_player.js +34 -0
  138. package/dist/src/utils/audio_player.js.map +1 -0
  139. package/dist/src/utils/long_running_operations.d.ts.map +1 -1
  140. package/dist/src/utils/long_running_operations.js +1 -1
  141. package/dist/src/utils/long_running_operations.js.map +1 -1
  142. package/dist/src/utils/resource_name_helper.d.ts +5 -0
  143. package/dist/src/utils/resource_name_helper.d.ts.map +1 -1
  144. package/dist/src/utils/resource_name_helper.js +9 -0
  145. package/dist/src/utils/resource_name_helper.js.map +1 -1
  146. package/dist/src/utils/selector.d.ts.map +1 -1
  147. package/dist/src/utils/selector.js +1 -2
  148. package/dist/src/utils/selector.js.map +1 -1
  149. package/dist/src/utils/ui.d.ts.map +1 -1
  150. package/dist/src/utils/ui.js +8 -2
  151. package/dist/src/utils/ui.js.map +1 -1
  152. package/package.json +8 -2
  153. package/dist/index.js.map +0 -7
  154. package/dist/src/templates/llm_tts/README.md +0 -161
  155. package/dist/src/templates/llm_tts/graph.d.ts +0 -2
  156. package/dist/src/templates/llm_tts/graph.d.ts.map +0 -1
  157. package/dist/src/templates/llm_tts/graph.ts +0 -30
  158. package/dist/src/templates/llm_tts/metadata.json +0 -41
  159. package/dist/templates/llm_tts/README.md +0 -155
  160. package/dist/templates/llm_tts/graph.ts +0 -29
  161. package/dist/templates/llm_tts/metadata.json +0 -41
package/dist/index.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts", "../src/commands/auth/login_command.ts", "../src/auth/callback-server.ts", "../package.json", "../src/constants.ts", "../src/utils/ui.ts", "../src/auth/manager.ts", "../proto/generated/portal/fetch.pb.ts", "../proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts", "../src/utils/array.ts", "../src/grpc/core/statusCodes.ts", "../src/grpc/core/InworldError.ts", "../proto/generated/portal/ai/inworld/studio/v1/operations.pb.ts", "../src/utils/long_running_operations.ts", "../src/auth/utils.ts", "../src/services/workspace_service.ts", "../proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts", "../proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.ts", "../src/utils/confirm.ts", "../src/utils/resource_name_helper.ts", "../src/utils/selector.ts", "../src/commands/auth/logout_command.ts", "../src/commands/auth/status_command.ts", "../src/commands/auth_command.ts", "../src/commands/auth/login_ci_command.ts", "../src/commands/auth/print_access_token_command.ts", "../src/commands/auth/print_api_key_command.ts", "../src/commands/graph/graph_deploy_command.ts", "../proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.ts", "../src/utils/spinner.ts", "../src/services/deploy_service.ts", "../src/services/graph_loader.ts", "../src/commands/graph/graph_init_command.ts", "../src/commands/graph/graph_run_command.ts", "../src/commands/graph/graph_serve_command.ts", "../src/commands/graph_command.ts", "../src/commands/graph/graph_variant_command.ts", "../src/commands/graph/variant/graph_variant_list_command.ts", "../src/services/graph_variant_service.ts", "../src/commands/graph/variant/graph_variant_print_command.ts", "../src/commands/graph/variant/graph_variant_register_command.ts", "../src/commands/graph/graph_visualize_command.ts", "../src/commands/tts_commands.ts", "../src/services/tts_service.ts", "../src/commands/workspace_command.ts"],
4
- "sourcesContent": ["import chalk from 'chalk';\nimport { Command } from 'commander';\n\nimport { loginCommandAlias } from './commands/auth/login_command.js';\nimport { logoutCommandAlias } from './commands/auth/logout_command.js';\nimport { statusCommandAlias } from './commands/auth/status_command.js';\nimport { authCommand } from './commands/auth_command.js';\nimport { deployCommandAlias } from './commands/graph/graph_deploy_command.js';\nimport { initCommandAlias } from './commands/graph/graph_init_command.js';\nimport { runCommandAlias } from './commands/graph/graph_run_command.js';\nimport { serveCommandAlias } from './commands/graph/graph_serve_command.js';\nimport { graphCommand } from './commands/graph_command.js';\nimport { ttsCommand } from './commands/tts_commands.js';\nimport { workspaceCommand } from './commands/workspace_command.js';\nimport { CLI_VERSION } from './constants.js';\nimport { updateChecker } from 'services/update_checker.js';\n\nconst version = CLI_VERSION;\n\nprocess.env.DISABLE_WELCOME_MESSAGE = 'true';\n\nclass InworldCLI {\n private program: Command;\n\n constructor() {\n this.program = new Command();\n this.setupProgram();\n this.registerCommands();\n }\n\n private setupProgram(): void {\n this.program\n .name('inworld')\n .description('Inworld Runtime CLI')\n .version(version, '--version')\n .configureOutput({\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () => process.stdout.columns || 80,\n getErrHelpWidth: () => process.stderr.columns || 80,\n });\n }\n\n private registerCommands(): void {\n this.program.addCommand(loginCommandAlias);\n this.program.addCommand(logoutCommandAlias);\n this.program.addCommand(statusCommandAlias);\n this.program.addCommand(serveCommandAlias);\n this.program.addCommand(runCommandAlias);\n this.program.addCommand(deployCommandAlias);\n this.program.addCommand(initCommandAlias);\n this.program.addCommand(authCommand);\n this.program.addCommand(graphCommand);\n this.program.addCommand(ttsCommand);\n this.program.addCommand(workspaceCommand);\n\n // Add a default help command\n this.program\n .command('help')\n .description('Display help information')\n .action(() => {\n this.program.help();\n });\n }\n\n async run(args?: string[]): Promise<void> {\n try {\n const updateCheckPromise = updateChecker.checkAndNotify().catch(() => {\n // Silently ignore update check errors\n });\n\n // Give update check a reasonable time to complete, but don't block\n const timeoutPromise = new Promise((resolve) =>\n setTimeout(resolve, 1000),\n );\n await Promise.race([updateCheckPromise, timeoutPromise]);\n\n await this.program.parseAsync(args);\n } catch (error) {\n console.error(\n chalk.red('Error:'),\n error instanceof Error ? error.message : String(error),\n );\n process.exit(1);\n }\n }\n}\n\n// Create and run the CLI\nconst cli = new InworldCLI();\ncli.run().catch((error) => {\n console.error(chalk.red('Fatal error:'), error);\n process.exit(1);\n});\n", "import chalk from 'chalk';\nimport { exec } from 'child_process';\nimport { Command } from 'commander';\nimport * as readline from 'readline';\nimport { promisify } from 'util';\n\nimport {\n authManager,\n createCallbackServer,\n stopCallbackServer,\n} from '../../auth';\nimport {\n INWORLD_CLI_AUTH_CALLBACK_PORT,\n INWORLD_CLI_AUTH_URL,\n INWORLD_ENV,\n} from '../../constants';\nimport { WorkspaceService } from '../../services/workspace_service.js';\nimport * as ui from '../../utils/ui';\n\nconst execAsync = promisify(exec);\n\nconst loginAction = async (options: { force: boolean }) => {\n let authServerResult: Awaited<\n ReturnType<typeof createCallbackServer>\n > | null = null;\n\n try {\n if (!options.force && (await authManager.isAuthenticated())) {\n const credentials = await authManager.getCredentials();\n const email = credentials?.email || 'Unknown';\n\n console.log();\n ui.print('\u26A0 You are already authenticated');\n ui.print(`Current account: ${email}`);\n console.log();\n ui.print('Use --force flag to re-authenticate:');\n ui.print(' inworld login --force');\n\n // Check if token is still valid\n const isValid = await authManager.isTokenValid();\n if (!isValid) {\n console.log();\n ui.print(\n 'Note: Your token has expired but will be automatically refreshed when needed.',\n );\n }\n\n process.exit(0);\n }\n\n console.log();\n ui.printHeader('\uD83C\uDFAD Welcome to Inworld CLI!');\n\n // If forcing re-authentication, show current account\n if (options.force && (await authManager.isAuthenticated())) {\n const credentials = await authManager.getCredentials();\n const email = credentials?.email || 'Unknown';\n ui.print(`Currently logged in as: ${email}`);\n ui.print('Proceeding with re-authentication...');\n console.log();\n } else {\n ui.print(\"Let's get you authenticated.\");\n console.log();\n }\n\n const serverPromise = createCallbackServer({\n port: INWORLD_CLI_AUTH_CALLBACK_PORT,\n });\n\n ui.print('Please visit the following URL to authenticate:');\n ui.printLink(`${INWORLD_CLI_AUTH_URL}\\n`);\n\n const readlineInterface = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const enterPromise = new Promise<void>((resolve) => {\n readlineInterface.question('Press Enter to open your browser...', () => {\n resolve();\n });\n });\n\n const result = await Promise.race([\n enterPromise.then(() => ({ type: 'enter' as const })),\n serverPromise.then((result) => ({ type: 'auth' as const, result })),\n ]);\n\n readlineInterface.close();\n\n if (result.type === 'auth') {\n // Authentication completed before Enter was pressed\n authServerResult = result.result;\n } else {\n // User pressed Enter, open browser\n const openCommand =\n process.platform === 'darwin'\n ? 'open'\n : process.platform === 'win32'\n ? 'start'\n : 'xdg-open';\n\n try {\n await execAsync(`${openCommand} ${INWORLD_CLI_AUTH_URL}`);\n ui.success('\u2713 Browser opened');\n } catch (_error) {\n ui.print(\n '\u26A0 Could not open browser automatically. Please open the URL manually.',\n );\n }\n\n console.log();\n ui.print('Waiting for authentication...');\n authServerResult = await serverPromise;\n }\n\n console.log();\n ui.success('\u2713 Authentication successful!');\n\n console.log();\n ui.print('User information:');\n ui.printBright(`Email: ${authServerResult.email}\\n`);\n\n const success = await authManager.authenticateAndSaveCredentials(\n authServerResult.token,\n authServerResult.refreshToken,\n authServerResult.email,\n /* workspace */ undefined,\n INWORLD_ENV,\n );\n\n if (!success) {\n ui.printError('\\nFailed to complete authentication setup');\n ui.print('You may need to login again.');\n }\n\n // Close the server\n stopCallbackServer(authServerResult.server);\n\n console.log();\n ui.print('You are now authenticated with Inworld services.');\n ui.print('Your credentials have been securely stored.');\n await WorkspaceService.activateWorkspace({ forceFirst: true });\n\n ui.print('\\nIf you want to change the workspace, you can run command:');\n ui.printBright('inworld workspace select');\n ui.print(\n '\\nIf you want to see authentication status, you can run command:',\n );\n ui.printBright('inworld auth status');\n\n ui.print('\\nAuthentication completed.');\n\n process.exit(0);\n } catch (error) {\n // Clean up server if it exists\n if (authServerResult?.server) {\n try {\n await stopCallbackServer(authServerResult.server);\n } catch (_closeError) {\n // Ignore close errors\n }\n }\n\n console.log();\n ui.printError('Authentication failed:');\n console.error(error);\n process.exit(1);\n }\n};\n\nconst makeLoginCommand = (description: string) => {\n return new Command('login')\n .description(description)\n .option('-f, --force', 'Force re-authentication even if already logged in')\n .action(loginAction);\n};\n\nexport const loginCommand = makeLoginCommand(\n 'Authenticate with Inworld Platform',\n);\n\nexport const loginCommandAlias = makeLoginCommand(\n `Alias for \"${chalk.bold('inworld auth login')}\"`,\n);\n", "import * as http from 'http';\n\nimport { FIREBASE_API_KEY } from '../constants';\nimport * as ui from '../utils/ui';\n\n/**\n * Authentication callback data received from the OAuth flow\n */\nexport interface AuthCallbackData {\n idToken: string;\n refreshToken: string;\n email: string;\n uid: string;\n}\n\n/**\n * Result from the authentication callback server\n */\nexport interface AuthServerResult {\n server: http.Server;\n token: string;\n refreshToken: string;\n email: string;\n}\n\n/**\n * Options for creating the authentication callback server\n */\nexport interface CallbackServerOptions {\n port?: number;\n allowedOrigins?: string[];\n firebaseApiKey?: string;\n}\n\n/**\n * Creates and starts an authentication callback server\n *\n * @param options Configuration options for the server\n * @returns Promise that resolves with authentication data when callback is received\n */\nexport async function createCallbackServer(\n options: CallbackServerOptions = {},\n): Promise<AuthServerResult> {\n const {\n port = 8085,\n allowedOrigins = ['http://localhost:3001', 'https://cli.inworld.ai'],\n firebaseApiKey = FIREBASE_API_KEY,\n } = options;\n\n return new Promise<AuthServerResult>((resolve, reject) => {\n const httpServer = http.createServer(\n {\n keepAlive: false,\n },\n (req, res) => {\n // Set CORS headers for allowed origins\n const origin = req.headers.origin;\n if (origin && allowedOrigins.includes(origin)) {\n res.setHeader('Access-Control-Allow-Origin', origin);\n res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n res.setHeader('Access-Control-Max-Age', '86400');\n }\n\n // Handle preflight OPTIONS request\n if (req.url?.startsWith('/callback') && req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (req.url?.startsWith('/callback') && req.method === 'POST') {\n // Handle POST request with body\n let body = '';\n\n req.on('data', (chunk) => {\n body += chunk.toString();\n });\n\n req.on('end', async () => {\n try {\n const data: AuthCallbackData = JSON.parse(body);\n\n console.log();\n ui.print('Received authentication data...');\n\n // Store the refresh token and email temporarily\n const refreshToken = data.refreshToken;\n const email = data.email;\n\n ui.print('Exchanging tokens...');\n\n // Exchange refresh token for new ID token\n if (!firebaseApiKey) {\n throw new Error('FIREBASE_API_KEY is not set');\n }\n\n const tokenFetchResponse = await fetch(\n `https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,\n {\n method: 'POST',\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: data.refreshToken,\n }),\n },\n );\n\n const tokenResponse = (await tokenFetchResponse.json()) as {\n access_token: string;\n expires_in: string;\n id_token: string;\n refresh_token: string;\n token_type: string;\n error?: { message: string };\n };\n\n if (tokenResponse.error) {\n throw new Error(\n `Token exchange failed: ${tokenResponse.error.message}`,\n );\n }\n\n if (tokenResponse?.id_token) {\n // Send success response\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ success: true }));\n\n // Resolve with token and credentials\n resolve({\n server: httpServer,\n token: tokenResponse.id_token,\n refreshToken: refreshToken,\n email: email,\n });\n } else {\n // No token provided\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'No idToken provided' }));\n }\n } catch (error) {\n // Handle errors\n ui.printError('Callback processing error:');\n console.error(error);\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({\n error:\n error instanceof Error ? error.message : 'Invalid request',\n }),\n );\n\n if (error instanceof Error && error.message.includes('JSON')) {\n // Don't reject on JSON parse errors, just log them\n ui.print(\n 'Invalid JSON received, waiting for valid callback...',\n );\n } else {\n // Reject for other errors\n reject(error);\n }\n }\n });\n\n req.on('error', (error) => {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Server error' }));\n reject(error);\n });\n } else if (req.url?.startsWith('/callback')) {\n // Not a POST request\n res.writeHead(405, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Method not allowed. Use POST.' }));\n } else {\n // Unknown endpoint\n res.writeHead(404, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Not found' }));\n }\n },\n );\n\n httpServer.on('error', (error) => {\n reject(error);\n });\n\n httpServer.listen(port, 'localhost');\n });\n}\n\n/**\n * Stops the authentication callback server\n *\n * @param server The server instance to stop\n */\nexport function stopCallbackServer(server: http.Server): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n });\n}\n", "{\n \"name\": \"@inworld/cli\",\n \"version\": \"0.2.16\",\n \"type\": \"module\",\n \"main\": \"dist/index.js\",\n \"baseUrl\": \"./src\",\n \"bin\": {\n \"inworld\": \"dist/index.js\"\n },\n \"scripts\": {\n \"build\": \"node esbuild.config.js\",\n \"build:tsc\": \"tsc --project tsconfig.json\",\n \"build:types\": \"tsc --emitDeclarationOnly\",\n \"build:all\": \"npm run build && npm run build:types\",\n \"start\": \"node dist/index.js\",\n \"dev\": \"tsx src/index.ts\"\n },\n \"files\": [\n \"dist/**/*\",\n \"src/templates/**/*\"\n ],\n \"author\": \"Inworld AI\",\n \"license\": \"MIT\",\n \"description\": \"Inworld CLI\",\n \"devDependencies\": {\n \"@tsconfig/node-lts\": \"^22.0.2\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/express\": \"^5.0.3\",\n \"@types/keytar\": \"^4.4.0\",\n \"@types/node\": \"^24.1.0\",\n \"@types/ora\": \"^3.1.0\",\n \"@types/semver\": \"^7.5.8\"\n },\n \"dependencies\": {\n \"@zowe/secrets-for-zowe-sdk\": \"^8.27.0\",\n \"archiver\": \"^7.0.1\",\n \"chalk\": \"^5.3.0\",\n \"commander\": \"^12.0.0\",\n \"conf\": \"^14.0.0\",\n \"esbuild\": \"^0.25.10\",\n \"jwt-decode\": \"^4.0.0\",\n \"ora\": \"^8.2.0\",\n \"semver\": \"^7.6.3\",\n \"tsx\": \"^4.20.5\",\n \"typescript\": \"^5.8.3\"\n }\n}\n", "// @ts-ignore: used by bundler\nimport packageJson from '../package.json' assert { type: 'json' };\n\nconst DEFAULT_PLATFORM_ENDPOINT = 'https://platform.inworld.ai';\n\nconst resolvePlatformUrl = () => {\n if (process.env.INWORLD_PLATFORM_URL) {\n return process.env.INWORLD_PLATFORM_URL;\n }\n const env = (process.env.INWORLD_ENV || '').toUpperCase();\n switch (env) {\n case 'DEV':\n return 'https://platform.dev.inworld.ai';\n case 'STAGE':\n return 'https://platform.stage.inworld.ai';\n case 'PROD':\n return 'https://platform.inworld.ai';\n default:\n return DEFAULT_PLATFORM_ENDPOINT;\n }\n};\n\nexport const INWORLD_ENV: 'DEV' | 'STAGE' | 'PROD' = (process.env.INWORLD_ENV ||\n 'PROD') as 'DEV' | 'STAGE' | 'PROD';\nexport const WORKSPACES_LIST_SIZE = 100;\nexport const PLATFORM_URL = resolvePlatformUrl();\nexport const FIREBASE_API_KEY =\n process.env.INWORLD_FIREBASE_API_KEY ||\n 'AIzaSyAPVBLVid0xPwjuU4Gmn_6_GyqxBq-SwQs';\nexport const INWORLD_CLI_AUTH_URL =\n process.env.INWORLD_CLI_AUTH_URL || 'https://cli.inworld.ai/login';\nexport const INWORLD_CLI_AUTH_CALLBACK_PORT = parseInt(\n process.env.INWORLD_CLI_AUTH_CALLBACK_PORT || '8085',\n 10,\n);\n\nexport const RUNTIME_VERSION = '0.6.3';\nexport const CLI_VERSION = packageJson.version;\n", "import chalk from 'chalk';\nimport { PLATFORM_URL } from '../constants';\n\nexport function printHeader(message: string) {\n console.log(chalk.bold(message));\n}\n\nexport function p(message: string) {\n console.log(message);\n}\n\nexport function print(message: string) {\n console.log(chalk.dim.white(message));\n}\n\nexport function printBright(message: string) {\n console.log(chalk.white(message));\n}\n\nexport function printLink(message: string) {\n console.log(chalk.dim.underline.cyan(message));\n}\n\nexport function printError(message: string) {\n console.error(chalk.dim.red(message));\n}\n\nexport function success(message: string) {\n console.log(chalk.dim.green(message));\n}\n\nexport function printListHeader(message: string) {\n console.log(chalk.gray(message));\n}\n\nexport function printListItem(message: string) {\n console.log('\u2514 ' + chalk.gray(message));\n}\n\nexport function cyan(message: string) {\n return chalk.cyan(message);\n}\n\nexport function yellow(message: string) {\n return chalk.yellow(message);\n}\n\nexport function green(message: string) {\n return chalk.green(message);\n}\n\nexport function bold(message: string) {\n return chalk.bold(message);\n}\n\nexport function link(message: string) {\n return chalk.dim.underline.cyan(message);\n}\n\n/**\n * Prints content in a styled box\n */\nexport function printBox(lines: string[], options?: { color?: string; padding?: number }) {\n const color = options?.color || 'yellow';\n const padding = options?.padding ?? 2;\n\n // Strip ANSI codes to calculate actual text width\n const stripAnsi = (str: string) => str.replace(/\\x1b\\[[0-9;]*m/g, '');\n\n // Calculate box width based on longest line\n const maxContentWidth = Math.max(...lines.map(line => stripAnsi(line).length));\n const boxWidth = maxContentWidth + padding * 2;\n\n const horizontalLine = '\u2500'.repeat(boxWidth);\n const emptyLine = ' '.repeat(boxWidth);\n\n // Get chalk color function\n const colorFn = (chalk as any)[color] || chalk.yellow;\n\n // Print box\n p('');\n p(colorFn('\u250C' + horizontalLine + '\u2510'));\n p(colorFn('\u2502' + emptyLine + '\u2502'));\n\n lines.forEach(line => {\n const actualLength = stripAnsi(line).length;\n const leftPad = ' '.repeat(padding);\n const rightPad = ' '.repeat(boxWidth - actualLength - padding);\n p(colorFn('\u2502') + leftPad + line + rightPad + colorFn('\u2502'));\n });\n\n p(colorFn('\u2502' + emptyLine + '\u2502'));\n p(colorFn('\u2514' + horizontalLine + '\u2518'));\n p('');\n}\n\nexport function trimBase64Key(key: string): string {\n return key.substring(0, 3) + '...' + key.substring(key.length - 5);\n}\n\nexport function trimToken(token: string): string {\n return token.substring(0, 5) + '...';\n}\n\nexport function workspaceLink(workspaceId: string) {\n return link(`${PLATFORM_URL}/v2/workspaces/${workspaceId}`)\n}", "// Keyring will be dynamically imported to avoid crashes when libsecret is not available\nimport Conf from 'conf';\nimport { createHash } from 'crypto';\n\nimport {\n AuthType,\n Users,\n} from '../../proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.js';\nimport { FIREBASE_API_KEY, INWORLD_ENV, PLATFORM_URL } from '../constants.js';\nimport * as ui from '../utils/ui';\n\n/**\n * Credentials interface for storing authentication data\n */\ninterface Credentials {\n refreshToken: string;\n email: string;\n inworldToken?: string;\n workspace?: string;\n apiKey?: string;\n expiresAt?: number;\n env?: 'DEV' | 'STAGE' | 'PROD';\n}\n\n/**\n * Type for the keyring module when dynamically imported\n */\ntype KeyringModule = {\n keyring: {\n setPassword: (\n service: string,\n account: string,\n password: string,\n ) => Promise<void>;\n getPassword: (service: string, account: string) => Promise<string | null>;\n deletePassword: (service: string, account: string) => Promise<boolean>;\n };\n};\n\n/**\n * AuthManager handles secure storage and retrieval of authentication credentials.\n * It uses the OS keychain as the primary storage method with an encrypted\n * configuration file as a fallback.\n */\nexport class AuthManager {\n private static readonly SERVICE_NAME = 'InworldCLI';\n private static readonly ACCOUNT_NAME = 'default';\n private static readonly CONFIG_KEY = 'credentials';\n\n private conf: Conf<{ credentials?: Credentials }> | null = null;\n private keyringModule: KeyringModule['keyring'] | null = null;\n private keyringLoadAttempted: boolean = false;\n private keyringAvailable: boolean = false;\n\n constructor() {\n // Conf and keyring will be initialized lazily when first needed\n }\n\n /**\n * Lazily loads the keyring module with fallback if unavailable\n */\n private async getKeyring(): Promise<KeyringModule['keyring'] | null> {\n if (this.keyringLoadAttempted) {\n return this.keyringModule;\n }\n\n this.keyringLoadAttempted = true;\n\n try {\n const module = (await import(\n '@zowe/secrets-for-zowe-sdk'\n )) as KeyringModule;\n this.keyringModule = module.keyring;\n return this.keyringModule;\n } catch (error: any) {\n ui.print(`\u26A0\uFE0F Failed to load keychain: ${error.message}`);\n this.keyringModule = null;\n this.keyringAvailable = false;\n return null;\n }\n }\n\n /**\n * Lazily initializes the Conf instance with encrypted storage\n */\n private async getConf(): Promise<Conf<{ credentials?: Credentials }>> {\n if (!this.conf) {\n const encryptionKey = await this.generateEncryptionKey();\n\n this.conf = new Conf<{ credentials?: Credentials }>({\n projectName: 'inworld-cli',\n encryptionKey,\n schema: {\n credentials: {\n type: 'object',\n properties: {\n refreshToken: { type: 'string' },\n email: { type: 'string' },\n inworldToken: { type: 'string' },\n expiresAt: { type: 'number' },\n workspace: { type: 'string' },\n },\n },\n },\n });\n }\n\n return this.conf;\n }\n\n /**\n * Generates a machine-specific encryption key for the configuration file\n */\n private async generateEncryptionKey(): Promise<string> {\n const platform = process.platform;\n const arch = process.arch;\n const hostname = (await import('os')).hostname();\n const username = (await import('os')).userInfo().username;\n\n // Create a unique key based on machine characteristics\n const data = `${platform}-${arch}-${hostname}-${username}-inworld-cli`;\n return createHash('sha256').update(data).digest('hex').substring(0, 32);\n }\n\n /**\n * Saves credentials securely\n */\n async saveCredentials(credentials: Credentials): Promise<void> {\n try {\n // Try to save to OS keychain first\n const keyring = await this.getKeyring();\n if (keyring) {\n try {\n const credentialsJsonString = JSON.stringify(credentials);\n await keyring.setPassword(\n AuthManager.SERVICE_NAME,\n AuthManager.ACCOUNT_NAME,\n credentialsJsonString,\n );\n return;\n } catch (_keychainError: any) {\n ui.print(\n '\u26A0 Could not save to system keychain, using encrypted file storage',\n );\n // Fall through to use conf\n }\n }\n\n // Fallback to encrypted configuration file\n const conf = await this.getConf();\n conf.set(AuthManager.CONFIG_KEY, credentials);\n ui.success('\u2713 Credentials saved to encrypted configuration');\n } catch (error) {\n throw new Error(`Failed to save credentials: ${error}`);\n }\n }\n\n /**\n * Retrieves stored credentials\n */\n async getCredentials(): Promise<Credentials | null> {\n try {\n const keyring = await this.getKeyring();\n\n if (keyring) {\n try {\n const credentialsJson = await keyring.getPassword(\n AuthManager.SERVICE_NAME,\n AuthManager.ACCOUNT_NAME,\n );\n\n if (credentialsJson) {\n return JSON.parse(credentialsJson) as Credentials;\n }\n } catch (_keychainError: any) {\n // Keychain read failed, try config file\n // Don't log here as this is a common path\n }\n }\n\n const conf = await this.getConf();\n const credentials = conf.get(AuthManager.CONFIG_KEY) as\n | Credentials\n | undefined;\n return credentials || null;\n } catch (error) {\n throw new Error(`Failed to retrieve credentials: ${error}`);\n }\n }\n\n async getApiKey(): Promise<string | null> {\n const credentials = await this.getCredentials();\n return credentials?.apiKey || null;\n }\n\n async getWorkspace(): Promise<string | null> {\n const credentials = await this.getCredentials();\n return credentials?.workspace || null;\n }\n\n /**\n * Updates the Inworld token and its expiration\n */\n async updateInworldToken(\n token: string,\n expirationTime: string,\n ): Promise<void> {\n const credentials = await this.getCredentials();\n if (!credentials) {\n throw new Error('No credentials found to update');\n }\n\n credentials.inworldToken = token;\n credentials.expiresAt = new Date(expirationTime).getTime();\n\n await this.saveCredentials(credentials);\n }\n\n async updateWorkspaceAndApiKey(\n workspace: string,\n apiKey: string,\n ): Promise<void> {\n const credentials = await this.getCredentials();\n if (!credentials) {\n throw new Error('No credentials found to update');\n }\n\n credentials.workspace = workspace;\n credentials.apiKey = apiKey;\n await this.saveCredentials(credentials);\n }\n\n /**\n * Checks if the stored Inworld token is still valid\n */\n async isTokenValid(): Promise<boolean> {\n const credentials = await this.getCredentials();\n if (!credentials || !credentials.inworldToken) {\n return false;\n }\n\n // If we have an expiration time, check it\n if (credentials.expiresAt) {\n return Date.now() < credentials.expiresAt;\n }\n\n // Otherwise assume it's valid (will fail on API call if not)\n return true;\n }\n\n /**\n * Generates an Inworld token from a Firebase ID token\n *\n * @param firebaseToken The Firebase ID token\n * @returns The generated Inworld token or null if generation fails\n */\n async generateInworldToken(\n firebaseToken: string,\n ): Promise<{ token: string; expiresAt: string } | null> {\n try {\n ui.print('Generating Inworld token...');\n\n const tokenResponse = await Users.GenerateTokenUser(\n {\n type: AuthType.AUTH_TYPE_FIREBASE,\n token: firebaseToken,\n },\n {\n headers: {\n Authorization: `Bearer ${firebaseToken}`,\n 'Grpc-Metadata-X-Authorization-Bearer-Type': 'firebase',\n },\n pathPrefix: PLATFORM_URL,\n },\n );\n\n if (tokenResponse?.token) {\n return {\n token: tokenResponse.token,\n expiresAt: tokenResponse.expirationTime,\n };\n }\n\n return null;\n } catch (error) {\n ui.printError('Failed to generate Inworld token:');\n console.error(error);\n return null;\n }\n }\n\n /**\n * Refreshes the Inworld token using the stored refresh token\n */\n async refreshToken(): Promise<string | null> {\n const credentials = await this.getCredentials();\n if (!credentials || !credentials.refreshToken) {\n return null;\n }\n\n try {\n // Use the refresh token to get a new Firebase ID token\n const firebaseApiKey = FIREBASE_API_KEY;\n if (!firebaseApiKey) {\n throw new Error('FIREBASE_API_KEY environment variable not set');\n }\n\n const tokenFetchResponse = await fetch(\n `https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,\n {\n method: 'POST',\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: credentials.refreshToken,\n }),\n },\n );\n\n const tokenResponse = (await tokenFetchResponse.json()) as {\n access_token: string;\n expires_in: string;\n id_token: string;\n refresh_token: string;\n token_type: string;\n };\n\n if (tokenResponse?.id_token) {\n // Generate new Inworld token\n const inworldTokenResult = await this.generateInworldToken(\n tokenResponse.id_token,\n );\n\n if (inworldTokenResult) {\n // Update stored token\n await this.updateInworldToken(\n inworldTokenResult.token,\n inworldTokenResult.expiresAt,\n );\n return inworldTokenResult.token;\n }\n\n return null;\n }\n\n return null;\n } catch (error) {\n ui.printError('Failed to refresh token:');\n console.error(error);\n return null;\n }\n }\n\n /**\n * Gets a valid Inworld token, refreshing if necessary\n */\n async getValidToken(): Promise<string | null> {\n // Check if current token is valid\n if (await this.isTokenValid()) {\n const credentials = await this.getCredentials();\n return credentials?.inworldToken || null;\n }\n\n // Try to refresh the token\n ui.print('Token expired, refreshing...');\n return await this.refreshToken();\n }\n\n /**\n * Authenticates and saves credentials from Firebase auth data\n * This is typically called after successful Firebase authentication\n *\n * @param firebaseToken The Firebase ID token\n * @param refreshToken The Firebase refresh token\n * @param email The user's email address\n * @returns true if successful, false otherwise\n */\n async authenticateAndSaveCredentials(\n firebaseToken: string,\n refreshToken: string,\n email: string,\n workspace?: string,\n env?: 'DEV' | 'STAGE' | 'PROD',\n ): Promise<boolean> {\n try {\n // Generate Inworld token\n const inworldTokenResult = await this.generateInworldToken(firebaseToken);\n\n if (!inworldTokenResult) {\n ui.printError('Failed to generate Inworld token');\n return false;\n }\n\n // Calculate expiration time\n const expiresAt = new Date(inworldTokenResult.expiresAt).getTime();\n // Save all credentials\n const credentials: Credentials = {\n refreshToken,\n email,\n inworldToken: inworldTokenResult.token,\n workspace,\n expiresAt,\n env,\n };\n\n await this.saveCredentials(credentials);\n\n return true;\n } catch (error) {\n ui.printError('Failed to authenticate and save credentials:');\n console.error(error);\n return false;\n }\n }\n\n /**\n * Clears all stored credentials\n */\n async clearCredentials(): Promise<void> {\n try {\n // Try to clear from OS keychain\n const keyring = await this.getKeyring();\n if (keyring) {\n try {\n await keyring.deletePassword(\n AuthManager.SERVICE_NAME,\n AuthManager.ACCOUNT_NAME,\n );\n } catch (_keychainError) {\n // Ignore keychain errors\n }\n }\n\n // Clear from configuration file\n const conf = await this.getConf();\n conf.delete(AuthManager.CONFIG_KEY);\n ui.success('\u2713 Credentials cleared');\n } catch (error) {\n throw new Error(`Failed to clear credentials: ${error}`);\n }\n }\n\n /**\n * Checks if user is authenticated\n */\n async isAuthenticated(): Promise<boolean> {\n const credentials = await this.getCredentials();\n if (credentials?.env && credentials?.env !== INWORLD_ENV) {\n ui.print(\n `Warning: Currently saved credentials might not match current Inworld CLI environment.\\n\\n` +\n `Current Inworld CLI environment is ${INWORLD_ENV}\\n` +\n `Environment of current credentials is ${credentials?.env}\\n\\n` +\n `You can run \"inworld login --force\" to login with the correct environment.`,\n );\n }\n return credentials !== null && !!credentials.refreshToken;\n }\n}\n\n// Export singleton instance\nexport const authManager = new AuthManager();\n", "/* eslint-disable */\n// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\n/**\n * base64 encoder and decoder\n * Copied and adapted from https://github.com/protobufjs/protobuf.js/blob/master/lib/base64/index.js\n */\n// Base64 encoding table\nconst b64 = new Array(64);\n\n// Base64 decoding table\nconst s64 = new Array(123);\n\n// 65..90, 97..122, 48..57, 43, 47\nfor (let i = 0; i < 64; )\n s64[\n (b64[i] =\n i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : (i - 59) | 43)\n ] = i++;\n\nexport function b64Encode(\n buffer: Uint8Array,\n start: number,\n end: number,\n): string {\n let parts: string[] = null;\n const chunk = [];\n let i = 0, // output index\n j = 0, // goto index\n t; // temporary\n while (start < end) {\n const b = buffer[start++];\n switch (j) {\n case 0:\n chunk[i++] = b64[b >> 2];\n t = (b & 3) << 4;\n j = 1;\n break;\n case 1:\n chunk[i++] = b64[t | (b >> 4)];\n t = (b & 15) << 2;\n j = 2;\n break;\n case 2:\n chunk[i++] = b64[t | (b >> 6)];\n chunk[i++] = b64[b & 63];\n j = 0;\n break;\n }\n if (i > 8191) {\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (j) {\n chunk[i++] = b64[t];\n chunk[i++] = 61;\n if (j === 1) chunk[i++] = 61;\n }\n if (parts) {\n if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n\nconst invalidEncoding = 'invalid encoding';\n\nexport function b64Decode(s: string): Uint8Array {\n const buffer = [];\n let offset = 0;\n let j = 0, // goto index\n t; // temporary\n for (let i = 0; i < s.length; ) {\n let c = s.charCodeAt(i++);\n if (c === 61 && j > 1) break;\n if ((c = s64[c]) === undefined) throw Error(invalidEncoding);\n switch (j) {\n case 0:\n t = c;\n j = 1;\n break;\n case 1:\n buffer[offset++] = (t << 2) | ((c & 48) >> 4);\n t = c;\n j = 2;\n break;\n case 2:\n buffer[offset++] = ((t & 15) << 4) | ((c & 60) >> 2);\n t = c;\n j = 3;\n break;\n case 3:\n buffer[offset++] = ((t & 3) << 6) | c;\n j = 0;\n break;\n }\n }\n if (j === 1) throw Error(invalidEncoding);\n return new Uint8Array(buffer);\n}\n\nfunction b64Test(s: string): boolean {\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n s,\n );\n}\n\nexport interface InitReq extends RequestInit {\n pathPrefix?: string;\n}\n\nexport function replacer(key: any, value: any): any {\n if (value && value.constructor === Uint8Array) {\n return b64Encode(value, 0, value.length);\n }\n\n return value;\n}\n\nexport function fetchReq<I, O>(path: string, init?: InitReq): Promise<O> {\n const { pathPrefix, ...req } = init || {};\n\n const url = pathPrefix ? `${pathPrefix}${path}` : path;\n\n return fetch(url, req).then((r) =>\n r.json().then((body: O) => {\n if (!r.ok) {\n throw body;\n }\n return body;\n }),\n ) as Promise<O>;\n}\n\n// NotifyStreamEntityArrival is a callback that will be called on streaming entity arrival\nexport type NotifyStreamEntityArrival<T> = (resp: T) => void;\n\n/**\n * fetchStreamingRequest is able to handle grpc-gateway server side streaming call\n * it takes NotifyStreamEntityArrival that lets users respond to entity arrival during the call\n * all entities will be returned as an array after the call finishes.\n **/\nexport async function fetchStreamingRequest<S, R>(\n path: string,\n callback?: NotifyStreamEntityArrival<R>,\n init?: InitReq,\n) {\n const { pathPrefix, ...req } = init || {};\n const url = pathPrefix ? `${pathPrefix}${path}` : path;\n const result = await fetch(url, req);\n // needs to use the .ok to check the status of HTTP status code\n // http other than 200 will not throw an error, instead the .ok will become false.\n // see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#\n if (!result.ok) {\n const resp = await result.json();\n const errMsg = resp.error && resp.error.message ? resp.error.message : '';\n throw new Error(errMsg);\n }\n\n if (!result.body) {\n throw new Error('response doesnt have a body');\n }\n\n await result.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough<R>(getNewLineDelimitedJSONDecodingStream<R>())\n .pipeTo(\n getNotifyEntityArrivalSink((e: R) => {\n if (callback) {\n callback(e);\n }\n }),\n );\n\n // wait for the streaming to finish and return the success respond\n return;\n}\n\n/**\n * JSONStringStreamController represents the transform controller that's able to transform the incoming\n * new line delimited json content stream into entities and able to push the entity to the down stream\n */\ninterface JSONStringStreamController<T>\n extends TransformStreamDefaultController {\n buf?: string;\n pos?: number;\n enqueue: (s: T) => void;\n}\n\n/**\n * getNewLineDelimitedJSONDecodingStream returns a TransformStream that's able to handle new line delimited json stream content into parsed entities\n */\nfunction getNewLineDelimitedJSONDecodingStream<T>(): TransformStream<\n string,\n T\n> {\n return new TransformStream({\n start(controller: JSONStringStreamController<T>) {\n controller.buf = '';\n controller.pos = 0;\n },\n\n transform(chunk: string, controller: JSONStringStreamController<T>) {\n if (controller.buf === undefined) {\n controller.buf = '';\n }\n if (controller.pos === undefined) {\n controller.pos = 0;\n }\n controller.buf += chunk;\n while (controller.pos < controller.buf.length) {\n if (controller.buf[controller.pos] === '\\n') {\n const line = controller.buf.substring(0, controller.pos);\n const response = JSON.parse(line);\n controller.enqueue(response.result);\n controller.buf = controller.buf.substring(controller.pos + 1);\n controller.pos = 0;\n } else {\n ++controller.pos;\n }\n }\n },\n });\n}\n\n/**\n * getNotifyEntityArrivalSink takes the NotifyStreamEntityArrival callback and return\n * a sink that will call the callback on entity arrival\n * @param notifyCallback\n */\nfunction getNotifyEntityArrivalSink<T>(\n notifyCallback: NotifyStreamEntityArrival<T>,\n) {\n return new WritableStream<T>({\n write(entity: T) {\n notifyCallback(entity);\n },\n });\n}\n\ntype Primitive = string | boolean | number;\ntype RequestPayload = Record<string, unknown>;\ntype FlattenedRequestPayload = Record<string, Primitive | Array<Primitive>>;\n\n/**\n * Checks if given value is a plain object\n * Logic copied and adapted from below source:\n * https://github.com/char0n/ramda-adjunct/blob/master/src/isPlainObj.js\n * @param {unknown} value\n * @return {boolean}\n */\nfunction isPlainObject(value: unknown): boolean {\n const isObject =\n Object.prototype.toString.call(value).slice(8, -1) === 'Object';\n const isObjLike = value !== null && isObject;\n\n if (!isObjLike || !isObject) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value);\n\n const hasObjectConstructor =\n typeof proto === 'object' &&\n proto.constructor === Object.prototype.constructor;\n\n return hasObjectConstructor;\n}\n\n/**\n * Checks if given value is of a primitive type\n * @param {unknown} value\n * @return {boolean}\n */\nfunction isPrimitive(value: unknown): boolean {\n return ['string', 'number', 'boolean'].some((t) => typeof value === t);\n}\n\n/**\n * Checks if given primitive is zero-value\n * @param {Primitive} value\n * @return {boolean}\n */\nfunction isZeroValuePrimitive(value: Primitive): boolean {\n return value === false || value === 0 || value === '';\n}\n\n/**\n * Flattens a deeply nested request payload and returns an object\n * with only primitive values and non-empty array of primitive values\n * as per https://github.com/googleapis/googleapis/blob/master/google/api/http.proto\n * @param {RequestPayload} requestPayload\n * @param {String} path\n * @return {FlattenedRequestPayload>}\n */\nfunction flattenRequestPayload<T extends RequestPayload>(\n requestPayload: T,\n path: string = '',\n): FlattenedRequestPayload {\n return Object.keys(requestPayload).reduce((acc: T, key: string): T => {\n const value = requestPayload[key];\n const newPath = path ? [path, key].join('.') : key;\n\n const isNonEmptyPrimitiveArray =\n Array.isArray(value) &&\n value.every((v) => isPrimitive(v)) &&\n value.length > 0;\n\n const isNonZeroValuePrimitive =\n isPrimitive(value) && !isZeroValuePrimitive(value as Primitive);\n\n let objectToMerge = {};\n\n if (isPlainObject(value)) {\n objectToMerge = flattenRequestPayload(value as RequestPayload, newPath);\n } else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {\n objectToMerge = { [newPath]: value };\n }\n\n return { ...acc, ...objectToMerge };\n }, {} as T) as FlattenedRequestPayload;\n}\n\n/**\n * Renders a deeply nested request payload into a string of URL search\n * parameters by first flattening the request payload and then removing keys\n * which are already present in the URL path.\n * @param {RequestPayload} requestPayload\n * @param {string[]} urlPathParams\n * @return {string}\n */\nexport function renderURLSearchParams<T extends RequestPayload>(\n requestPayload: T,\n urlPathParams: string[] = [],\n): string {\n const flattenedRequestPayload = flattenRequestPayload(requestPayload);\n\n const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(\n (acc: string[][], key: string): string[][] => {\n // key should not be present in the url path as a parameter\n const value = flattenedRequestPayload[key];\n if (urlPathParams.find((f) => f === key)) {\n return acc;\n }\n return Array.isArray(value)\n ? [...acc, ...value.map((m) => [key, m.toString()])]\n : (acc = [...acc, [key, value.toString()]]);\n },\n [] as string[][],\n );\n\n return new URLSearchParams(urlSearchParams).toString();\n}\n", "/* eslint-disable */\n// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\nimport * as fm from '../../../../fetch.pb';\nimport * as GoogleProtobufEmpty from '../../../../google/protobuf/empty.pb';\nimport * as GoogleProtobufField_mask from '../../../../google/protobuf/field_mask.pb';\nimport * as GoogleProtobufTimestamp from '../../../../google/protobuf/timestamp.pb';\n\nexport enum MarketingConsent {\n MARKETING_CONSENT_UNSPECIFIED = 'MARKETING_CONSENT_UNSPECIFIED',\n MARKETING_CONSENT_DECLINED = 'MARKETING_CONSENT_DECLINED',\n MARKETING_CONSENT_GRANTED = 'MARKETING_CONSENT_GRANTED',\n}\n\nexport enum MarketingPlatformPurpose {\n MARKETING_PLATFORM_PURPOSE_UNSPECIFIED = 'MARKETING_PLATFORM_PURPOSE_UNSPECIFIED',\n MARKETING_PLATFORM_PURPOSE_GAME_AND_METAVERSE = 'MARKETING_PLATFORM_PURPOSE_GAME_AND_METAVERSE',\n MARKETING_PLATFORM_PURPOSE_ENTERTAINMENT = 'MARKETING_PLATFORM_PURPOSE_ENTERTAINMENT',\n MARKETING_PLATFORM_PURPOSE_SALES_AND_MARKETING = 'MARKETING_PLATFORM_PURPOSE_SALES_AND_MARKETING',\n MARKETING_PLATFORM_PURPOSE_TRAINING_AND_EDUCATION = 'MARKETING_PLATFORM_PURPOSE_TRAINING_AND_EDUCATION',\n MARKETING_PLATFORM_PURPOSE_OTHER = 'MARKETING_PLATFORM_PURPOSE_OTHER',\n}\n\nexport enum OnboardingInterest {\n ONBOARDING_INTEREST_UNSPECIFIED = 'ONBOARDING_INTEREST_UNSPECIFIED',\n ONBOARDING_INTEREST_NEW_APP_RUNTIME = 'ONBOARDING_INTEREST_NEW_APP_RUNTIME',\n ONBOARDING_INTEREST_MIGRATE_TO_RUNTIME = 'ONBOARDING_INTEREST_MIGRATE_TO_RUNTIME',\n ONBOARDING_INTEREST_TRYING_TTS = 'ONBOARDING_INTEREST_TRYING_TTS',\n ONBOARDING_INTEREST_NOT_SURE = 'ONBOARDING_INTEREST_NOT_SURE',\n}\n\nexport enum ProjectType {\n PROJECT_TYPE_UNSPECIFIED = 'PROJECT_TYPE_UNSPECIFIED',\n PROJECT_TYPE_PERSONAL = 'PROJECT_TYPE_PERSONAL',\n PROJECT_TYPE_WORK = 'PROJECT_TYPE_WORK',\n}\n\nexport enum WorkRole {\n WORK_ROLE_UNSPECIFIED = 'WORK_ROLE_UNSPECIFIED',\n WORK_ROLE_FOUNDER = 'WORK_ROLE_FOUNDER',\n WORK_ROLE_TEAM_LEAD = 'WORK_ROLE_TEAM_LEAD',\n WORK_ROLE_SOFTWARE_ENGINEER = 'WORK_ROLE_SOFTWARE_ENGINEER',\n WORK_ROLE_ML_ENGINEER = 'WORK_ROLE_ML_ENGINEER',\n WORK_ROLE_PRODUCT_MANAGER = 'WORK_ROLE_PRODUCT_MANAGER',\n WORK_ROLE_OTHER = 'WORK_ROLE_OTHER',\n}\n\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n AUTH_TYPE_OCULUS_NONCE = 'AUTH_TYPE_OCULUS_NONCE',\n AUTH_TYPE_FIREBASE = 'AUTH_TYPE_FIREBASE',\n}\n\nexport type GenerateTokenUserRequest = {\n type?: AuthType;\n token?: string;\n};\n\nexport type GenerateTokenUserResponse = {\n token?: string;\n type?: string;\n expirationTime?: GoogleProtobufTimestamp.Timestamp;\n isCreated?: boolean;\n};\n\nexport type LinkAccountRequest = {\n name?: string;\n oculusOauthToken?: string;\n};\n\nexport type GetUserRequest = {\n name?: string;\n};\n\nexport type AcceptTosRequest = {\n user?: string;\n};\n\nexport type UpdateUserRequest = {\n user?: User;\n updateMask?: GoogleProtobufField_mask.FieldMask;\n};\n\nexport type User = {\n name?: string;\n oculusId?: string;\n firebaseId?: string;\n tosAcceptanceVersion?: number;\n marketingConsent?: MarketingConsent;\n marketingPlatformPurpose?: MarketingPlatformPurpose;\n displayName?: string;\n role?: string;\n application?: string;\n games?: string[];\n characters?: string[];\n internal?: boolean[];\n onboardingSurvey?: OnboardingSurvey;\n};\n\nexport type OnboardingSurvey = {\n interests?: OnboardingInterest[];\n projectType?: ProjectType;\n workRole?: WorkRole;\n};\n\nexport type DeleteUserRequest = {\n name?: string;\n};\n\nexport type ResolveAzureMarketplaceOfferTokenRequest = {\n token?: string;\n};\n\nexport type ResolveAzureMarketplaceOfferTokenResponse = {\n subscriptionId?: string;\n subscriptionDisplayName?: string;\n planId?: string;\n subscriberEmail?: string;\n};\n\nexport type ActivateAzureMarketplaceSubscriptionRequest = {\n subscriptionId?: string;\n planId?: string;\n billingAccountId?: string;\n};\n\nexport class Users {\n static GenerateTokenUser(\n req: GenerateTokenUserRequest,\n initReq?: fm.InitReq,\n ): Promise<GenerateTokenUserResponse> {\n return fm.fetchReq<GenerateTokenUserRequest, GenerateTokenUserResponse>(\n `/v1alpha/users:generateTokenUser`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static LinkAccountUser(\n req: LinkAccountRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<LinkAccountRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}:link`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static GetUser(req: GetUserRequest, initReq?: fm.InitReq): Promise<User> {\n return fm.fetchReq<GetUserRequest, User>(\n `/v1alpha/${req['name']}?${fm.renderURLSearchParams(req, ['nameusers'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static UpdateUser(\n req: UpdateUserRequest,\n initReq?: fm.InitReq,\n ): Promise<User> {\n return fm.fetchReq<UpdateUserRequest, User>(\n `/v1alpha/${req['user']['name']}`,\n {\n ...initReq,\n method: 'PATCH',\n body: JSON.stringify(req['user'], fm.replacer),\n },\n );\n }\n static AcceptTos(req: AcceptTosRequest, initReq?: fm.InitReq): Promise<User> {\n return fm.fetchReq<AcceptTosRequest, User>(\n `/v1alpha/${req['user']}:acceptTos`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static DeleteUser(\n req: DeleteUserRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<DeleteUserRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}`,\n { ...initReq, method: 'DELETE' },\n );\n }\n static ResolveAzureMarketplaceOfferToken(\n req: ResolveAzureMarketplaceOfferTokenRequest,\n initReq?: fm.InitReq,\n ): Promise<ResolveAzureMarketplaceOfferTokenResponse> {\n return fm.fetchReq<\n ResolveAzureMarketplaceOfferTokenRequest,\n ResolveAzureMarketplaceOfferTokenResponse\n >(\n `/v1alpha/users:resolveAzureMarketplaceOfferToken?${fm.renderURLSearchParams(req, [])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static ActivateAzureMarketplaceSubscription(\n req: ActivateAzureMarketplaceSubscriptionRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<\n ActivateAzureMarketplaceSubscriptionRequest,\n GoogleProtobufEmpty.Empty\n >(`/v1alpha/users:activateAzureMarketplaceSubscription`, {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req, fm.replacer),\n });\n }\n}\n", "export function isArrayOfType<T>(\n arr: T[] | undefined,\n typeGuard: (obj: unknown) => obj is T,\n): arr is T[] {\n return (\n typeof arr !== 'undefined' && Array.isArray(arr) && arr.every(typeGuard)\n );\n}\n", "/**\n * @fileoverview gRPC status codes\n * Reference https://grpc.github.io/grpc/core/md_doc_statuscodes.html\n */\n\nexport enum GrpcStatusCode {\n /**\n * Not an error; returned on success.\n */\n OK = 0,\n\n /**\n * The operation was cancelled, typically by the caller.\n */\n CANCELLED = 1,\n\n /**\n * Unknown error. For example, this error may be returned when a Status\n * value received from another address space belongs to an error space\n * that is not known in this address space. Also, errors raised by APIs\n * that do not return enough error information may be converted to this error.\n */\n UNKNOWN = 2,\n\n /**\n * The client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file name).\n */\n INVALID_ARGUMENT = 3,\n\n /**\n * The deadline expired before the operation could complete. For operations\n * that change the state of the system, this error may be returned even if\n * the operation has completed successfully. For example, a successful\n * response from a server could have been delayed long.\n */\n DEADLINE_EXCEEDED = 4,\n\n /**\n * Some requested entity (e.g., file or directory) was not found. Note to\n * server developers: if a request is denied for an entire class of users,\n * such as gradual feature rollout or undocumented allowlist, NOT_FOUND may be used.\n * If a request is denied for some users within a class of users, such as user-based\n * access control, PERMISSION_DENIED must be used. This error code does not imply the\n * request is valid or the requested entity exists or satisfies other pre-conditions.\n */\n NOT_FOUND = 5,\n\n /**\n * The entity that a client attempted to create (e.g., file or directory) already exists.\n */\n ALREADY_EXISTS = 6,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller cannot be identified\n * (use UNAUTHENTICATED instead for those errors). This error code does not\n * imply the request is valid or the requested entity exists or satisfies other pre-conditions.\n */\n PERMISSION_DENIED = 7,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps\n * the entire file system is out of space.\n */\n RESOURCE_EXHAUSTED = 8,\n\n /**\n * The operation was rejected because the system is not in a state required\n * for the operation's execution. For example, the directory to be deleted is\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n * Service implementors can use the following guidelines to decide between\n * FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher level (e.g.,\n * when a client-specified test-and-set fails, indicating the client should\n * restart a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until the\n * system state has been explicitly fixed. E.g., if an \"rmdir\" fails because\n * the directory is non-empty, FAILED_PRECONDITION should be returned since\n * the client should not retry unless the files are deleted from the directory.\n */\n FAILED_PRECONDITION = 9,\n\n /**\n * The operation was aborted, typically due to a concurrency issue such as\n * a sequencer check failure or transaction abort. See the guidelines above\n * for deciding between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE.\n */\n ABORTED = 10,\n\n /**\n * The operation was attempted past the valid range. E.g., seeking or\n * reading past end-of-file. Unlike INVALID_ARGUMENT, this error indicates\n * a problem that may be fixed if the system state changes. For example,\n * a 32-bit file system will generate INVALID_ARGUMENT if asked to read at\n * an offset that is not in the range [0,2^32-1], but it will generate\n * OUT_OF_RANGE if asked to read from an offset past the current file size.\n * There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE.\n * We recommend using OUT_OF_RANGE (the more specific error) when it applies\n * so that callers who are iterating through a space can easily look for an\n * OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE = 11,\n\n /**\n * The operation is not implemented or is not supported/enabled in this service.\n */\n UNIMPLEMENTED = 12,\n\n /**\n * Internal errors. This means that some invariants expected by the underlying\n * system have been broken. This error code is reserved for serious errors.\n */\n INTERNAL = 13,\n\n /**\n * The service is currently unavailable. This is most likely a transient\n * condition, which can be corrected by retrying with a backoff.\n * Note that it is not always safe to retry non-idempotent operations.\n */\n UNAVAILABLE = 14,\n\n /**\n * Unrecoverable data loss or corruption.\n */\n DATA_LOSS = 15,\n\n /**\n * The request does not have valid authentication credentials for the operation.\n */\n UNAUTHENTICATED = 16,\n}\n\nexport function isGrpcStatusCode(value: number): value is GrpcStatusCode {\n return Object.values(GrpcStatusCode).includes(value);\n}\n\nexport const CommonRetryableGrpcStatusCodes = [\n GrpcStatusCode.UNKNOWN,\n GrpcStatusCode.ABORTED,\n GrpcStatusCode.CANCELLED,\n GrpcStatusCode.DEADLINE_EXCEEDED,\n GrpcStatusCode.INTERNAL,\n GrpcStatusCode.RESOURCE_EXHAUSTED,\n GrpcStatusCode.UNAVAILABLE,\n];\n", "import { BadRequest } from '../../../proto/generated/portal/ai/inworld/studio/v1/errors.pb';\nimport { isArrayOfType } from '../../utils/array';\nimport { GrpcStatusCode, isGrpcStatusCode } from './statusCodes';\n\nexport type ErrorStatus = {\n code: number;\n message: string;\n details?: any[];\n};\n\nexport interface InworldErrorContract {\n code: GrpcStatusCode;\n message: string;\n details: BadRequestDetails[];\n}\n\nexport interface BadRequestDetails extends Required<BadRequest> {\n '@type': string;\n}\n\nexport interface InworldErrorContract {\n code: GrpcStatusCode;\n message: string;\n details: BadRequestDetails[];\n}\n\nexport function isBadRequestDetails(obj: any): obj is BadRequestDetails {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n '@type' in obj &&\n typeof obj['@type'] === 'string' &&\n 'fieldViolations' in obj &&\n (obj.fieldViolations === undefined || Array.isArray(obj.fieldViolations)) &&\n (typeof obj.requestIndex === 'string' || obj.requestIndex === undefined) &&\n (typeof obj.message === 'string' || obj.message === undefined)\n );\n}\n\nexport function isInworldErrorContract(obj: any): obj is InworldErrorContract {\n return (\n (typeof obj === 'object' || obj instanceof InworldError) &&\n obj !== null &&\n 'code' in obj &&\n 'message' in obj &&\n 'details' in obj &&\n isArrayOfType(obj.details, isBadRequestDetails)\n );\n}\n\nexport function isGrpcError(obj: any): obj is Partial<InworldError> {\n return (\n (typeof obj === 'object' || obj instanceof InworldError) &&\n obj !== null &&\n 'code' in obj &&\n isGrpcStatusCode(obj.code)\n );\n}\n\nexport class InworldError extends Error {\n code: GrpcStatusCode;\n details: BadRequestDetails[];\n metadata?: unknown;\n\n constructor(error: InworldErrorContract | Error, metadata?: unknown) {\n super(error.message);\n\n if (isInworldErrorContract(error)) {\n this.message = error.message;\n this.code = error.code;\n this.details = error.details;\n } else {\n this.code = GrpcStatusCode.UNKNOWN;\n this.details = [];\n }\n\n this.metadata = metadata;\n\n Object.setPrototypeOf(this, InworldError.prototype);\n }\n}\n", "/* eslint-disable */\n// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\nimport * as fm from '../../../../fetch.pb';\nimport * as GoogleLongrunningOperations from '../../../../google/longrunning/operations.pb';\nexport class Operations {\n static ListOperations(\n req: GoogleLongrunningOperations.ListOperationsRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.ListOperationsResponse> {\n return fm.fetchReq<\n GoogleLongrunningOperations.ListOperationsRequest,\n GoogleLongrunningOperations.ListOperationsResponse\n >(\n `/studio/v1/${req['name']}/operations?${fm.renderURLSearchParams(req, ['nameworkspaces'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static GetOperation(\n req: GoogleLongrunningOperations.GetOperationRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n GoogleLongrunningOperations.GetOperationRequest,\n GoogleLongrunningOperations.Operation\n >(\n `/studio/v1/${req['nameworkspacescharactersoperations']}?${fm.renderURLSearchParams(req, ['nameworkspacescharactersoperations'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n}\n", "// Potred from portal ui code.\n\nimport { Operations } from '../../proto/generated/portal/ai/inworld/studio/v1/operations.pb';\nimport { retryableAuthenticatedInworldRequest } from '../auth/utils';\nimport { ErrorStatus } from '../grpc/core/InworldError';\n\n// reference https://github.com/googleapis/googleapis/blob/master/google/longrunning/operations.proto\nexport type LongRunningOperationResponse = {\n name: string;\n metadata?: any;\n done: boolean;\n error?: ErrorStatus;\n response?: any;\n};\n\nconst isOperationError = (obj: any): obj is ErrorStatus =>\n typeof obj === 'object' &&\n obj !== null &&\n typeof obj.code === 'number' &&\n typeof obj.message === 'string' &&\n ('details' in obj ? Array.isArray(obj.details) : true);\n\nexport const isLongRunningOperationResponse = (\n obj: any,\n): obj is LongRunningOperationResponse =>\n typeof obj === 'object' &&\n obj !== null &&\n typeof obj.name === 'string' &&\n typeof obj.done === 'boolean' &&\n ('error' in obj ? isOperationError(obj.error) : true);\n\nexport const CHECK_LIMIT = 60;\nexport const CHECK_TIMEOUT = 2000;\n\nexport type LROPollOptions<T> = {\n currentIteration?: number;\n skipCheck?: boolean;\n isRunning?: boolean;\n operationName?: string;\n startCallback?: (operationName: string) => void;\n iterationCallback?: (\n operationName: string,\n checkResponse:\n | {\n done?: boolean | undefined;\n response?: T | undefined;\n error?: string | undefined;\n }\n | undefined,\n checkData: {\n checkIteration: number;\n checkLimit: number;\n checkTimeout: number;\n },\n ) => void;\n doneCallback?: (operationName: string, response: T | undefined) => void;\n errorCallback?: (operationName: string, error: string) => void;\n};\n\n//Decoupled polling logic from calling the operation\nexport const checkLRO = async <T>({\n operationName,\n signal,\n checkLimit,\n checkTimeout,\n pollOptions,\n returnWithMetadata,\n}: {\n operationName: string;\n signal?: AbortSignal;\n checkLimit?: number;\n checkTimeout?: number;\n pollOptions?: LROPollOptions<T>;\n returnWithMetadata?: boolean;\n}) => {\n let checkResponse;\n\n checkLimit = checkLimit ?? CHECK_LIMIT;\n checkTimeout = checkTimeout ?? CHECK_TIMEOUT;\n\n if (pollOptions?.startCallback) {\n pollOptions.startCallback(operationName);\n }\n\n for (let i = pollOptions?.currentIteration ?? 0; i < checkLimit; i++) {\n signal?.throwIfAborted();\n try {\n checkResponse = await check<T>(operationName, signal, returnWithMetadata);\n if (checkResponse?.done) {\n if (checkResponse?.error || checkResponse?.metadata?.error) {\n pollOptions?.errorCallback?.(\n operationName,\n checkResponse.error || checkResponse?.metadata?.error,\n );\n throw checkResponse.error || checkResponse?.metadata?.error;\n }\n pollOptions?.doneCallback?.(operationName, checkResponse?.response);\n return (\n returnWithMetadata ? checkResponse : checkResponse?.response\n ) as T;\n } else {\n pollOptions?.iterationCallback?.(operationName, checkResponse, {\n checkIteration: i,\n checkLimit,\n checkTimeout,\n });\n }\n } catch (error: any) {\n pollOptions?.errorCallback?.(operationName, error);\n throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, checkTimeout));\n }\n\n throw new Error(\n `Operation timeout. Max number of checks reached ${checkLimit}`,\n );\n};\n\nconst check = async <T>(\n operationName: string,\n signal?: AbortSignal,\n returnWithMetadata?: boolean,\n) =>\n retryableAuthenticatedInworldRequest<\n any,\n {\n done?: boolean;\n response?: T;\n error?: string;\n // WHY? now BE can skip root error and return it in metadata, so we need to check it\n metadata?: { error?: any };\n }\n >(\n Operations.GetOperation,\n {\n nameworkspacescharactersoperations: operationName,\n },\n returnWithMetadata\n ? {\n withMetadata: true,\n maxRetries: 1,\n backoffFactor: 2,\n minTimeout: 300,\n }\n : undefined,\n signal,\n );\n", "import * as fm from '../../proto/generated/portal/fetch.pb.js';\nimport { PLATFORM_URL } from '../constants.js';\nimport {\n BadRequestDetails,\n InworldErrorContract,\n isGrpcError,\n isInworldErrorContract,\n} from '../grpc/core/InworldError';\nimport { GrpcStatusCode } from '../grpc/core/statusCodes';\nimport { CommonRetryableGrpcStatusCodes } from '../grpc/core/statusCodes';\nimport { isLongRunningOperationResponse } from '../utils/long_running_operations';\nimport * as ui from '../utils/ui';\nimport { authManager } from './manager.js';\n\n/**\n * Authentication utilities for CLI commands\n */\n\n/**\n * Ensures the user is authenticated before proceeding.\n * If not authenticated, prompts the user to login and exits.\n */\nexport async function requireAuth(): Promise<void> {\n const isAuthenticated = await authManager.isAuthenticated();\n\n if (!isAuthenticated) {\n console.log();\n ui.printError('\u274C Authentication required');\n ui.print('You must be logged in to use this command.');\n console.log();\n ui.print('Run: inworld login');\n process.exit(1);\n }\n}\n\nexport async function requireWorkspace(): Promise<string> {\n const workspaceResourceName = await authManager.getWorkspace();\n if (!workspaceResourceName) {\n console.log();\n ui.printError('\u274C Workspace required');\n ui.print('Please run \"inworld ws select\" to select a workspace.');\n process.exit(1);\n }\n return workspaceResourceName;\n}\n\nexport async function requireApiKey() {\n let apiKey;\n if (process.env.INWORLD_API_KEY) {\n apiKey = process.env.INWORLD_API_KEY;\n } else {\n apiKey = await authManager.getApiKey();\n }\n if (!apiKey) {\n console.log();\n ui.printError('\u274C API key required');\n ui.print(\n 'Please export \"INWORLD_API_KEY\" to environment variable or run \"inworld login\" to login.',\n );\n process.exit(1);\n }\n return apiKey;\n}\n\nexport type InworldRequestRetryOptions = {\n maxRetries: number; // The maximum number of retries.\n backoffFactor: number; // The factor by which the timeout increases exponentially on each retry.\n minTimeout: number; // The minimum timeout in milliseconds before the first retry.\n maxTimeout?: number; // The maximum timeout in milliseconds for any individual retry.\n withMetadata?: boolean; // Whether to include metadata in the error.\n};\n\nexport class InworldError extends Error {\n code: GrpcStatusCode;\n details: BadRequestDetails[];\n metadata?: unknown;\n\n constructor(error: InworldErrorContract | Error, metadata?: unknown) {\n super(error.message);\n\n if (isInworldErrorContract(error)) {\n this.message = error.message;\n this.code = error.code;\n this.details = error.details;\n } else {\n this.code = GrpcStatusCode.UNKNOWN;\n this.details = [];\n }\n\n this.metadata = metadata;\n\n Object.setPrototypeOf(this, InworldError.prototype);\n }\n}\n\nexport type PbFunc<P, R> = (req: P, initReq?: fm.InitReq) => Promise<R>;\n\nexport async function retryableAuthenticatedInworldRequest<\n RequestOptions,\n Response,\n>(\n pb: PbFunc<RequestOptions, Response>,\n req: RequestOptions,\n options: InworldRequestRetryOptions = {\n maxRetries: 5,\n backoffFactor: 2,\n minTimeout: 300,\n },\n signal?: AbortSignal,\n): Promise<Response | undefined> {\n const maxRetries = options.maxRetries;\n const backoffFactor = options.backoffFactor;\n const minTimeout = options.minTimeout;\n const maxTimeout =\n options.maxTimeout ?? minTimeout * backoffFactor ** maxRetries * 2;\n\n /**\n * Recursive function to retry the inworld request with exponential backoff.\n * @param {number} currentAttempt - The current attempt number.\n * @param {AbortSignal} [signal] - AbortSignal to be able to abort operations.\n * * @returns {Promise<Response | undefined>} A promise that resolves with the response or rejects if the maximum retries are reached.\n */\n const retryRequest = async (\n currentAttempt: number,\n signal?: AbortSignal,\n ): Promise<Response | undefined> => {\n signal?.throwIfAborted();\n try {\n const response = await authenticatedInworldRequest(pb, req);\n if (isLongRunningOperationResponse(response) && response?.done) {\n // BE started sending metadata not in the error, but on the same level as the response for some cases.\n if (\n (response?.error || response?.metadata?.error) &&\n options.withMetadata\n ) {\n throw response;\n }\n if (response?.error) {\n throw response.error;\n }\n return response as Response;\n }\n return response;\n } catch (cause) {\n const error = cause as InworldError;\n const isGrpcGatewayError = isGrpcError(cause);\n\n /**\n * Retry if the error is a gRPC error and the status code is in the list of retryable status codes\n * OR\n * the error is not a gRPC error. Since it can be a network error, we should retry.\n */\n const allowRetry =\n (isGrpcGatewayError &&\n CommonRetryableGrpcStatusCodes.includes(error.code)) ||\n !isGrpcGatewayError;\n\n if (allowRetry && currentAttempt < maxRetries) {\n const timeout = Math.min(\n minTimeout * Math.pow(backoffFactor, currentAttempt),\n maxTimeout,\n );\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(retryRequest(currentAttempt + 1));\n }, timeout);\n });\n } else {\n throw new InworldError(\n error.metadata\n ? (error as unknown as { error: InworldError; metadata?: unknown })\n .error\n : error,\n error.metadata,\n );\n }\n }\n };\n\n return retryRequest(1, signal);\n}\n\nexport type ArgsWithSignal<P = unknown> = P & { signal?: AbortSignal };\n\nexport const authenticatedInworldRequest = async <P, R>(\n pb: PbFunc<P, R>,\n req: P,\n inworldToken?: string,\n signal?: AbortSignal,\n) => {\n if (!inworldToken) {\n requireAuth();\n inworldToken = (await authManager.getValidToken()) || '';\n }\n if (inworldToken) {\n const request = {\n ...{\n headers: {\n Authorization: `Bearer ${inworldToken}`,\n 'Grpc-Metadata-X-Authorization-Bearer-Type': 'inworld',\n },\n },\n pathPrefix: PLATFORM_URL,\n signal,\n };\n\n return pb(req, request);\n }\n};\n\n/**\n * Checks if the user is authenticated without exiting.\n * Useful for commands that have optional authentication.\n *\n * @returns true if authenticated, false otherwise\n */\nexport async function isAuthenticated(): Promise<boolean> {\n return await authManager.isAuthenticated();\n}\n\n/**\n * Shows the current authentication status.\n * Useful for debugging or status commands.\n */\nexport async function showAuthStatus(): Promise<void> {\n const isAuth = await authManager.isAuthenticated();\n\n if (!isAuth) {\n ui.printError('\uD83D\uDD12 Not authenticated');\n return;\n }\n\n const credentials = await authManager.getCredentials();\n const email = credentials?.email || 'Unknown';\n const hasValidToken = await authManager.isTokenValid();\n\n ui.success('\u2713 Authenticated');\n ui.print(` Email: ${email}`);\n ui.print(\n ` Token status: ${hasValidToken ? 'Valid' : 'Expired (will refresh automatically)'}`,\n );\n\n if (credentials?.expiresAt) {\n const expiresIn = Math.round(\n (credentials.expiresAt - Date.now()) / 1000 / 60,\n );\n if (expiresIn > 0) {\n ui.print(` Token expires in: ${expiresIn} minutes`);\n }\n }\n}\n", "import chalk from 'chalk';\n\nimport {\n ApiKey,\n ApiKeys,\n} from '../../proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb';\nimport { Workspaces } from '../../proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb';\nimport { authManager } from '../auth/manager';\nimport { authenticatedInworldRequest } from '../auth/utils';\nimport { WORKSPACES_LIST_SIZE } from '../constants';\nimport { confirm } from '../utils/confirm';\nimport { parseWorkspaceResourceName } from '../utils/resource_name_helper';\nimport { selectItemOrExit } from '../utils/selector';\nimport * as ui from '../utils/ui';\nimport { trimBase64Key } from '../utils/ui';\n\n/**\n * Service for managing Inworld workspaces and API keys.\n * Provides functionality to list, select, and activate workspaces with their associated API keys.\n *\n * @remarks\n * This service handles the authentication flow for workspace activation,\n * including API key selection and generation when needed.\n */\nexport class WorkspaceService {\n /**\n * Prompts user to select a workspace from available workspaces\n * @param forceFirst If true, automatically selects the first workspace\n * @returns The resource name of the selected workspace\n */\n private static async pickWorkspace(\n forceFirst: boolean = false,\n ): Promise<string> {\n const listWorkspacesResponse = await authenticatedInworldRequest(\n Workspaces.ListWorkspaces,\n {\n pageSize: forceFirst ? 1 : WORKSPACES_LIST_SIZE,\n },\n );\n\n const workspaces = listWorkspacesResponse?.workspaces || [];\n\n const selectedWorkspace = await selectItemOrExit({\n items: workspaces,\n getDisplayName: (ws) =>\n ws.displayName || ws.name?.split('/').pop() || 'unknown',\n getIdentifier: (ws) => ws.name?.split('/').pop() || 'unknown',\n prompt: 'Enter the number or resource name of the workspace to activate:',\n title: 'Available workspaces:',\n forceFirst,\n noItemsMessage: 'No workspaces found.',\n invalidSelectionMessage:\n 'Invalid selection. Please enter a valid number or workspace resource name.',\n });\n\n return selectedWorkspace.name!;\n }\n\n /**\n * Prompts user to select an API key from available API keys\n * @param apiKeys List of API keys to select from\n * @param forceFirst If true, automatically selects the first API key\n * @returns The selected API key or null if no selection was made\n */\n private static async pickApiKey(\n apiKeys: ApiKey[],\n forceFirst: boolean = false,\n ): Promise<ApiKey | null> {\n return selectItemOrExit({\n items: apiKeys,\n getDisplayName: (apiKey) => {\n const name = apiKey.name?.split('/').pop() || 'unknown';\n // Show creation time if available\n const createdAt = apiKey.createTime\n ? new Date(apiKey.createTime).toLocaleDateString()\n : 'unknown date';\n return `${name} (created: ${createdAt})`;\n },\n getIdentifier: (apiKey) => apiKey.name?.split('/').pop() || 'unknown',\n prompt: 'Enter the number or resource name of the API key to use:',\n title: 'Available API keys:',\n forceFirst,\n noItemsMessage: 'No API keys found.',\n invalidSelectionMessage:\n 'Invalid selection. Please enter a valid number or API key resource name.',\n });\n }\n\n private static returnBase64 = (key: string, secret: string) => {\n const encodedKeySecret = new TextEncoder().encode(`${key}:${secret}`);\n return btoa(String.fromCharCode.apply(null, Array.from(encodedKeySecret)));\n };\n\n /**\n * Activates a workspace by selecting it and its associated API key.\n * If no API key exists, prompts the user to generate one.\n *\n * @param options Configuration options\n * @param options.forceFirst If true, automatically selects the first workspace and API key\n */\n static async activateWorkspace({\n forceFirst,\n }: { forceFirst?: boolean } = {}) {\n const workspaceResourceName = await this.pickWorkspace(forceFirst);\n\n const workspaceId = parseWorkspaceResourceName(\n workspaceResourceName,\n ).workspaceId;\n\n ui.print(`\\nSelecting workspace: ${chalk.whiteBright(workspaceId)}`);\n ui.print(`Selected workspace link: ${ui.workspaceLink(workspaceId)}`);\n\n let apiKey: ApiKey | null = null;\n const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {\n parent: workspaceResourceName,\n pageSize: forceFirst ? 1 : WORKSPACES_LIST_SIZE,\n });\n\n if (response?.apiKeys?.length) {\n // If there's only one API key or forceFirst is true, use it directly\n if (response.apiKeys.length === 1 || forceFirst) {\n apiKey = response.apiKeys[0];\n } else {\n // Multiple API keys found, let user select\n ui.print(`Found ${response.apiKeys.length} API keys in the workspace.`);\n apiKey = await this.pickApiKey(response.apiKeys, false);\n }\n } else {\n const shouldGenerate = await confirm({\n message:\n 'No API keys found for this workspace. Would you like to generate one? (y/N): ',\n defaultValue: false,\n });\n\n if (shouldGenerate) {\n ui.print('Generating API key...');\n const generateApiKeyResponse = await authenticatedInworldRequest(\n ApiKeys.GenerateApiKey,\n {\n parent: workspaceResourceName,\n },\n );\n if (!generateApiKeyResponse) {\n ui.printError('Failed to generate API key.');\n process.exit(1);\n }\n apiKey = generateApiKeyResponse;\n ui.success('API key generated successfully.');\n } else {\n ui.print('No API key will be generated.');\n }\n }\n\n const base64Key = this.returnBase64(apiKey?.key!, apiKey?.secret!);\n ui.print(`\\nSelecting API key: ${chalk.whiteBright(trimBase64Key(base64Key))}`);\n await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);\n\n ui.success('\\nWorkspace and API key selected.');\n }\n\n /**\n * Lists all API keys for the currently active workspace\n */\n static async listApiKeys() {\n const credentials = await authManager.getCredentials();\n\n if (!credentials?.workspace) {\n ui.printError(\n 'No workspace activated. Please run \"inworld workspace activate\" first.',\n );\n return;\n }\n\n const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {\n parent: credentials.workspace,\n pageSize: WORKSPACES_LIST_SIZE,\n });\n\n const apiKeys = response?.apiKeys || [];\n\n if (apiKeys.length === 0) {\n ui.printError('No API keys found in the active workspace.');\n return;\n }\n\n console.log();\n ui.printHeader(`API keys in workspace ${credentials.workspace}:`);\n apiKeys.forEach((apiKey, idx) => {\n const name = apiKey.name?.split('/').pop() || 'unknown';\n const createdAt = apiKey.createTime\n ? new Date(apiKey.createTime).toLocaleDateString()\n : 'unknown date';\n const state = apiKey.state || 'unknown';\n\n ui.printListItem(\n `${idx + 1}. ${name} (created: ${createdAt}, state: ${state})`,\n );\n });\n }\n\n /**\n * Allows user to select and activate a different API key from the current workspace\n */\n static async selectApiKey() {\n const credentials = await authManager.getCredentials();\n\n if (!credentials?.workspace) {\n ui.printError(\n 'No workspace activated. Please run \"inworld workspace activate\" first.',\n );\n return;\n }\n\n const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {\n parent: credentials.workspace,\n pageSize: WORKSPACES_LIST_SIZE,\n });\n\n const apiKeys = response?.apiKeys || [];\n\n if (apiKeys.length === 0) {\n ui.printError('No API keys found in the active workspace.');\n\n const shouldGenerate = await confirm({\n message: 'Would you like to generate a new API key? (y/N): ',\n defaultValue: false,\n });\n\n if (shouldGenerate) {\n await this.generateApiKey();\n }\n return;\n }\n\n if (apiKeys.length === 1) {\n ui.print('Only one API key found in the workspace.');\n const apiKey = apiKeys[0];\n const base64Key = this.returnBase64(apiKey?.key!, apiKey?.secret!);\n await authManager.updateWorkspaceAndApiKey(\n credentials.workspace,\n base64Key,\n );\n ui.success('API key activated successfully.');\n return;\n }\n\n const selectedApiKey = await this.pickApiKey(apiKeys, false);\n if (selectedApiKey) {\n const base64Key = this.returnBase64(\n selectedApiKey.key!,\n selectedApiKey.secret!,\n );\n await authManager.updateWorkspaceAndApiKey(\n credentials.workspace,\n base64Key,\n );\n ui.success('API key activated successfully.');\n }\n }\n\n /**\n * Generates a new API key for the currently active workspace\n */\n static async generateApiKey() {\n const credentials = await authManager.getCredentials();\n\n if (!credentials?.workspace) {\n ui.printError(\n 'No workspace activated. Please run \"inworld workspace activate\" first.',\n );\n return;\n }\n\n ui.print('Generating new API key...');\n\n const generateApiKeyResponse = await authenticatedInworldRequest(\n ApiKeys.GenerateApiKey,\n {\n parent: credentials.workspace,\n },\n );\n\n if (!generateApiKeyResponse) {\n ui.printError('Failed to generate API key.');\n return;\n }\n\n const base64Key = this.returnBase64(\n generateApiKeyResponse.key!,\n generateApiKeyResponse.secret!,\n );\n\n await authManager.updateWorkspaceAndApiKey(\n credentials.workspace,\n base64Key,\n );\n\n ui.success('API key activated successfully.');\n ui.success('API key generated and activated successfully.');\n console.log();\n ui.printHeader('API Key details:');\n ui.printListItem(\n `Name: ${generateApiKeyResponse.name?.split('/').pop() || 'unknown'}`,\n );\n ui.printListItem(`Key: ${generateApiKeyResponse.key}`);\n ui.printListItem(`Base64: ${base64Key}`);\n }\n}\n", "/* eslint-disable */\n// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\nimport * as fm from '../../../../fetch.pb';\nimport * as GoogleProtobufEmpty from '../../../../google/protobuf/empty.pb';\nimport * as GoogleProtobufTimestamp from '../../../../google/protobuf/timestamp.pb';\n\nexport enum ApiKeyAuthorizationType {\n API_KEY_AUTHORIZATION_TYPE_UNSPECIFIED = 'API_KEY_AUTHORIZATION_TYPE_UNSPECIFIED',\n API_KEY_AUTHORIZATION_TYPE_BASIC = 'API_KEY_AUTHORIZATION_TYPE_BASIC',\n API_KEY_AUTHORIZATION_TYPE_JWT = 'API_KEY_AUTHORIZATION_TYPE_JWT',\n}\n\nexport enum ApiKeyState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n ACTIVE = 'ACTIVE',\n SUSPENDED = 'SUSPENDED',\n DELETED = 'DELETED',\n}\n\nexport type AuthScope = {\n name?: string;\n displayName?: string;\n};\n\nexport type ListAuthScopesRequest = {\n parent?: string;\n pageSize?: number;\n pageToken?: string;\n};\n\nexport type ListAuthScopesResponse = {\n authScopes?: AuthScope[];\n nextPageToken?: string;\n};\n\nexport type ApiKeyUsageLimits = {\n maxConcurrentSessions?: number;\n dailyLimitSecondsAmount?: string;\n totalLimitSecondsAmount?: string;\n expirationTime?: GoogleProtobufTimestamp.Timestamp;\n};\n\nexport type ApiKey = {\n name?: string;\n key?: string;\n secret?: string;\n state?: ApiKeyState;\n usageLimits?: ApiKeyUsageLimits;\n createTime?: GoogleProtobufTimestamp.Timestamp;\n scopes?: string[];\n authTypes?: ApiKeyAuthorizationType[];\n};\n\nexport type GenerateApiKeyRequest = {\n parent?: string;\n scopes?: string[];\n authTypes?: ApiKeyAuthorizationType[];\n};\n\nexport type ListApiKeysRequest = {\n parent?: string;\n pageSize?: number;\n pageToken?: string;\n};\n\nexport type SuspendApiKeyRequest = {\n name?: string;\n};\n\nexport type ActivateApiKeyRequest = {\n name?: string;\n};\n\nexport type DeleteApiKeyRequest = {\n name?: string;\n};\n\nexport type ListApiKeysResponse = {\n apiKeys?: ApiKey[];\n nextPageToken?: string;\n collectionApiKeys?: ApiKey[];\n};\n\nexport class ApiKeys {\n static ListApiKeys(\n req: ListApiKeysRequest,\n initReq?: fm.InitReq,\n ): Promise<ListApiKeysResponse> {\n return fm.fetchReq<ListApiKeysRequest, ListApiKeysResponse>(\n `/v1alpha/${req['parent']}/apikeys?${fm.renderURLSearchParams(req, ['parent'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static SuspendApiKey(\n req: SuspendApiKeyRequest,\n initReq?: fm.InitReq,\n ): Promise<ApiKey> {\n return fm.fetchReq<SuspendApiKeyRequest, ApiKey>(\n `/v1alpha/${req['name']}:suspend`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static ActivateApiKey(\n req: ActivateApiKeyRequest,\n initReq?: fm.InitReq,\n ): Promise<ApiKey> {\n return fm.fetchReq<ActivateApiKeyRequest, ApiKey>(\n `/v1alpha/${req['name']}:activate`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static DeleteApiKey(\n req: DeleteApiKeyRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<DeleteApiKeyRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}`,\n { ...initReq, method: 'DELETE' },\n );\n }\n static GenerateApiKey(\n req: GenerateApiKeyRequest,\n initReq?: fm.InitReq,\n ): Promise<ApiKey> {\n return fm.fetchReq<GenerateApiKeyRequest, ApiKey>(\n `/v1alpha/${req['parent']}/apikey:generate`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static ListAuthScopes(\n req: ListAuthScopesRequest,\n initReq?: fm.InitReq,\n ): Promise<ListAuthScopesResponse> {\n return fm.fetchReq<ListAuthScopesRequest, ListAuthScopesResponse>(\n `/v1alpha/${req['parent']}/auth-scopes?${fm.renderURLSearchParams(req, ['parent'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n}\n", "/* eslint-disable */\n// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\nimport * as fm from '../../../../fetch.pb';\nimport * as GoogleProtobufEmpty from '../../../../google/protobuf/empty.pb';\nimport * as GoogleProtobufField_mask from '../../../../google/protobuf/field_mask.pb';\nimport * as AiInworldLanguage_codesLanguage_codes from '../../language_codes/language_codes.pb';\nimport * as AiInworldStudioV1alphaImpression_event_data from './impression_event_data.pb';\nimport * as AiInworldStudioV1alphaLanguage_code from './language_code.pb';\n\nexport enum WorkspaceItemView {\n WORKSPACE_ITEM_VIEW_UNSPECIFIED = 'WORKSPACE_ITEM_VIEW_UNSPECIFIED',\n WORKSPACE_ITEM_VIEW_DEFAULT = 'WORKSPACE_ITEM_VIEW_DEFAULT',\n WORKSPACE_ITEM_VIEW_WITH_META = 'WORKSPACE_ITEM_VIEW_WITH_META',\n}\n\nexport enum WorkspaceRuntimeAccess {\n RUNTIME_ACCESS_UNSPECIFIED = 'RUNTIME_ACCESS_UNSPECIFIED',\n RUNTIME_ACCESS_PRIVATE = 'RUNTIME_ACCESS_PRIVATE',\n RUNTIME_ACCESS_PUBLIC = 'RUNTIME_ACCESS_PUBLIC',\n}\n\nexport enum ShareUserRole {\n ROLE_UNSPECIFIED = 'ROLE_UNSPECIFIED',\n ROLE_OWNER = 'ROLE_OWNER',\n ROLE_ADMIN = 'ROLE_ADMIN',\n ROLE_DEVELOPER = 'ROLE_DEVELOPER',\n ROLE_VIEWER = 'ROLE_VIEWER',\n}\n\nexport enum GenerateResourceNameRequestResourceType {\n RESOURCE_TYPE_UNSPECIFIED = 'RESOURCE_TYPE_UNSPECIFIED',\n RESOURCE_TYPE_WORKSPACE = 'RESOURCE_TYPE_WORKSPACE',\n RESOURCE_TYPE_CHARACTER = 'RESOURCE_TYPE_CHARACTER',\n RESOURCE_TYPE_SCENE = 'RESOURCE_TYPE_SCENE',\n RESOURCE_TYPE_ENTITY = 'RESOURCE_TYPE_ENTITY',\n RESOURCE_TYPE_KNOWLEDGE = 'RESOURCE_TYPE_KNOWLEDGE',\n RESOURCE_TYPE_WORKSPACE_COLLECTION = 'RESOURCE_TYPE_WORKSPACE_COLLECTION',\n RESOURCE_TYPE_CUSTOM_VOICE = 'RESOURCE_TYPE_CUSTOM_VOICE',\n}\n\nexport type GetWorkspaceRequest = {\n name?: string;\n view?: WorkspaceItemView;\n};\n\nexport type ListWorkspacesRequest = {\n pageSize?: number;\n pageToken?: string;\n};\n\nexport type CreateWorkspaceRequest = {\n workspace?: Workspace;\n};\n\nexport type UpdateWorkspaceRequest = {\n workspace?: Workspace;\n updateMask?: GoogleProtobufField_mask.FieldMask;\n};\n\nexport type DeleteWorkspaceRequest = {\n name?: string;\n force?: boolean;\n};\n\nexport type CloneWorkspaceRequest = {\n name?: string;\n targetWorkspace?: string;\n};\n\nexport type ImpressionEventRequest = {\n name?: string;\n data?: AiInworldStudioV1alphaImpression_event_data.ImpressionEventData[];\n};\n\nexport type WorkspaceMeta = {\n totalCharacters?: number;\n totalScenes?: number;\n totalTriggers?: number;\n totalCommonKnowledge?: number;\n};\n\nexport type Workspace = {\n name?: string;\n displayName?: string;\n experimentalFeatures?: string[];\n billingAccount?: string;\n meta?: WorkspaceMeta;\n runtimeAccess?: WorkspaceRuntimeAccess;\n primaryLanguageCode?: AiInworldStudioV1alphaLanguage_code.LanguageCode;\n primaryLanguage?: AiInworldLanguage_codesLanguage_codes.LanguageCode;\n dogfoodEnabled?: boolean;\n uiEdits?: boolean;\n userRole?: ShareUserRole;\n billingAccountEmail?: string;\n};\n\nexport type ListWorkspacesResponse = {\n workspaces?: Workspace[];\n nextPageToken?: string;\n};\n\nexport type ShareUser = {\n email?: string;\n role?: ShareUserRole;\n};\n\nexport type ShareWorkspaceRequest = {\n name?: string;\n emails?: string[];\n shareUsers?: ShareUser[];\n};\n\nexport type GenerateResourceNameRequest = {\n workspace?: string;\n displayName?: string;\n resourceType?: GenerateResourceNameRequestResourceType;\n};\n\nexport type GenerateResourceNameResponse = {\n resource?: string;\n};\n\nexport type GetWorkspaceShareInfoRequest = {\n name?: string;\n};\n\nexport type WorkspaceShareInfoRolePermission = {\n role?: ShareUserRole;\n permissions?: string[];\n};\n\nexport type WorkspaceShareInfo = {\n emails?: string[];\n shareUsers?: ShareUser[];\n rolePermissions?: WorkspaceShareInfoRolePermission[];\n};\n\nexport type GetWorkspaceLimitInfoRequest = {\n name?: string;\n};\n\nexport type GetRemainWorkspaceLimitInfoRequest = {\n name?: string;\n};\n\nexport type WorkspaceLimitInfoTextListLimit = {\n itemMaxLength?: number;\n totalItems?: number;\n};\n\nexport type WorkspaceLimitInfoRangeLimit = {\n minValue?: number;\n maxValue?: number;\n};\n\nexport type WorkspaceLimitInfoCharacterLimitCharacterDescriptionLimit = {\n coreMaxLength?: number;\n exampleDialogMaxLength?: number;\n motivationMaxLength?: number;\n characterRoleMaxLength?: number;\n hobbyOrInterests?: WorkspaceLimitInfoTextListLimit;\n nicknames?: WorkspaceLimitInfoTextListLimit;\n personalityAdjectives?: WorkspaceLimitInfoTextListLimit;\n flawsMaxLength?: number;\n};\n\nexport type WorkspaceLimitInfoCharacterLimit = {\n nameMaxLength?: number;\n totalTriggers?: number;\n totalCommonKnowledge?: number;\n characterDescription?: WorkspaceLimitInfoCharacterLimitCharacterDescriptionLimit;\n userTags?: WorkspaceLimitInfoTextListLimit;\n};\n\nexport type WorkspaceLimitInfoSceneLimit = {\n descriptionMaxLength?: number;\n totalCharacters?: number;\n totalTriggers?: number;\n displayNameMaxLength?: number;\n totalCommonKnowledge?: number;\n sceneTriggerDescriptionMaxLength?: number;\n userTags?: WorkspaceLimitInfoTextListLimit;\n};\n\nexport type WorkspaceLimitInfoWorkspaceLimit = {\n displayNameMaxLength?: number;\n totalCharacters?: number;\n totalScenes?: number;\n totalTriggers?: number;\n totalVoices?: number;\n totalCommonKnowledge?: number;\n totalNarrativeGraphs?: number;\n totalCollaborators?: number;\n totalEntities?: number;\n totalCustomTasks?: number;\n totalPlayerProfileFields?: number;\n};\n\nexport type WorkspaceLimitInfoBillingAccountLimit = {\n totalWorkspaces?: number;\n};\n\nexport type WorkspaceLimitInfoCommonKnowledgeLimit = {\n displayNameMaxLength?: number;\n descriptionMaxLength?: number;\n memoryRecords?: WorkspaceLimitInfoTextListLimit;\n userTags?: WorkspaceLimitInfoTextListLimit;\n};\n\nexport type WorkspaceLimitInfoAutoGeneratorLimit = {\n notesMaxLength?: number;\n outlineMaxLength?: number;\n totalForks?: number;\n totalFiles?: number;\n};\n\nexport type WorkspaceLimitInfoNarrativeGraphLimitAutoGeneratorNodeLimit = {\n sceneCount?: WorkspaceLimitInfoRangeLimit;\n forkCount?: WorkspaceLimitInfoRangeLimit;\n instructionSize?: WorkspaceLimitInfoRangeLimit;\n};\n\nexport type WorkspaceLimitInfoNarrativeGraphLimit = {\n totalNodes?: number;\n totalConnections?: number;\n displayNameMaxLength?: number;\n nodeLimit?: WorkspaceLimitInfoNarrativeGraphLimitAutoGeneratorNodeLimit;\n};\n\nexport type WorkspaceLimitInfoBatchLimit = {\n totalCommon?: number;\n totalImageUploads?: number;\n totalDeploys?: number;\n};\n\nexport type WorkspaceLimitInfoFineTuneModelLimit = {\n minFeedbackMessages?: number;\n minPairedFeedbackMessages?: number;\n maxFeedbackHistoryDays?: number;\n};\n\nexport type WorkspaceLimitInfoEntityLimitRegexRuleLimit = {\n nameMaxLength?: number;\n regexPatternMaxLength?: number;\n};\n\nexport type WorkspaceLimitInfoEntityLimitDictionaryRuleLimit = {\n nameMaxLength?: number;\n displayNameMaxLength?: number;\n totalSynonyms?: number;\n synonymMaxLength?: number;\n};\n\nexport type WorkspaceLimitInfoEntityLimit = {\n displayNameMaxLength?: number;\n descriptionMaxLength?: number;\n totalRegexRules?: number;\n totalDictionaryRules?: number;\n regexRuleLimit?: WorkspaceLimitInfoEntityLimitRegexRuleLimit;\n dictionaryRuleLimit?: WorkspaceLimitInfoEntityLimitDictionaryRuleLimit;\n};\n\nexport type WorkspaceLimitInfoCustomTaskLimitParameterLimit = {\n descriptionMaxLength?: number;\n};\n\nexport type WorkspaceLimitInfoCustomTaskLimit = {\n totalParameters?: number;\n parameter?: WorkspaceLimitInfoCustomTaskLimitParameterLimit;\n};\n\nexport type WorkspaceLimitInfo = {\n character?: WorkspaceLimitInfoCharacterLimit;\n scene?: WorkspaceLimitInfoSceneLimit;\n workspace?: WorkspaceLimitInfoWorkspaceLimit;\n billingAccount?: WorkspaceLimitInfoBillingAccountLimit;\n commonKnowledge?: WorkspaceLimitInfoCommonKnowledgeLimit;\n autoGenerator?: WorkspaceLimitInfoAutoGeneratorLimit;\n narrativeGraph?: WorkspaceLimitInfoNarrativeGraphLimit;\n batch?: WorkspaceLimitInfoBatchLimit;\n fineTuneModel?: WorkspaceLimitInfoFineTuneModelLimit;\n entity?: WorkspaceLimitInfoEntityLimit;\n customTask?: WorkspaceLimitInfoCustomTaskLimit;\n};\n\nexport class Workspaces {\n static GetWorkspace(\n req: GetWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<Workspace> {\n return fm.fetchReq<GetWorkspaceRequest, Workspace>(\n `/v1alpha/${req['name']}?${fm.renderURLSearchParams(req, ['nameworkspaces'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static ListWorkspaces(\n req: ListWorkspacesRequest,\n initReq?: fm.InitReq,\n ): Promise<ListWorkspacesResponse> {\n return fm.fetchReq<ListWorkspacesRequest, ListWorkspacesResponse>(\n `/v1alpha/workspaces?${fm.renderURLSearchParams(req, [])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static UpdateWorkspace(\n req: UpdateWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<Workspace> {\n return fm.fetchReq<UpdateWorkspaceRequest, Workspace>(\n `/v1alpha/${req['workspace']['name']}`,\n {\n ...initReq,\n method: 'PATCH',\n body: JSON.stringify(req['workspace'], fm.replacer),\n },\n );\n }\n static CreateWorkspace(\n req: CreateWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<Workspace> {\n return fm.fetchReq<CreateWorkspaceRequest, Workspace>(\n `/v1alpha/workspaces`,\n {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req['workspace'], fm.replacer),\n },\n );\n }\n static DeleteWorkspace(\n req: DeleteWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<DeleteWorkspaceRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}`,\n { ...initReq, method: 'DELETE' },\n );\n }\n static CloneWorkspace(\n req: CloneWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<Workspace> {\n return fm.fetchReq<CloneWorkspaceRequest, Workspace>(\n `/v1alpha/${req['name']}:clone`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static ShareWorkspace(\n req: ShareWorkspaceRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<ShareWorkspaceRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}:share`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n static generateResourceName(\n req: GenerateResourceNameRequest,\n initReq?: fm.InitReq,\n ): Promise<GenerateResourceNameResponse> {\n return fm.fetchReq<\n GenerateResourceNameRequest,\n GenerateResourceNameResponse\n >(`/v1alpha/${req['workspace']}:generateResourceName`, {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req, fm.replacer),\n });\n }\n static GetWorkspaceShareInfo(\n req: GetWorkspaceShareInfoRequest,\n initReq?: fm.InitReq,\n ): Promise<WorkspaceShareInfo> {\n return fm.fetchReq<GetWorkspaceShareInfoRequest, WorkspaceShareInfo>(\n `/v1alpha/${req['name']}?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static GetWorkspaceLimitInfo(\n req: GetWorkspaceLimitInfoRequest,\n initReq?: fm.InitReq,\n ): Promise<WorkspaceLimitInfo> {\n return fm.fetchReq<GetWorkspaceLimitInfoRequest, WorkspaceLimitInfo>(\n `/v1alpha/${req['name']}?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static RemainWorkspaceLimitInfo(\n req: GetRemainWorkspaceLimitInfoRequest,\n initReq?: fm.InitReq,\n ): Promise<WorkspaceLimitInfo> {\n return fm.fetchReq<GetRemainWorkspaceLimitInfoRequest, WorkspaceLimitInfo>(\n `/v1alpha/${req['name']}:remain?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static SendImpressionEvent(\n req: ImpressionEventRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<ImpressionEventRequest, GoogleProtobufEmpty.Empty>(\n `/v1alpha/${req['name']}:impression`,\n { ...initReq, method: 'POST', body: JSON.stringify(req, fm.replacer) },\n );\n }\n}\n", "import * as readline from 'readline';\n\n/**\n * Global context for confirmation prompts\n */\nlet globalForceYes = false;\n\n/**\n * Sets the global auto-confirm flag\n * @param value If true, all confirmations will be auto-accepted\n */\nexport function setGlobalForceYes(value: boolean): void {\n globalForceYes = value;\n}\n\n/**\n * Gets the current global auto-confirm flag value\n */\nexport function getGlobalForceYes(): boolean {\n return globalForceYes;\n}\n\n/**\n * Options for confirmation prompts\n */\nexport interface ConfirmOptions {\n /**\n * The prompt message to show the user\n */\n message: string;\n\n /**\n * If true, automatically confirm without prompting\n * Overrides global forceYes setting\n */\n forceYes?: boolean;\n\n /**\n * The default value if user just presses enter (defaults to false)\n */\n defaultValue?: boolean;\n}\n\n/**\n * Prompts the user for a yes/no confirmation\n * Supports auto-confirm via forceYes parameter or global setting\n *\n * @param options Confirmation options\n * @returns Promise that resolves to true if user confirmed, false otherwise\n *\n * @example\n * ```typescript\n * const shouldProceed = await confirm({\n * message: 'Do you want to continue?',\n * defaultValue: false\n * });\n * if (shouldProceed) {\n * // proceed with action\n * }\n * ```\n */\nexport async function confirm(options: ConfirmOptions): Promise<boolean> {\n const { message, forceYes, defaultValue = false } = options;\n\n // Check if we should auto-confirm (local override or global setting)\n if (forceYes !== undefined ? forceYes : globalForceYes) {\n return true;\n }\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(message, (answer: string) => {\n rl.close();\n\n const trimmedAnswer = answer.trim().toLowerCase();\n\n // Handle explicit yes/no\n if (trimmedAnswer === 'y' || trimmedAnswer === 'yes') {\n resolve(true);\n return;\n }\n\n if (trimmedAnswer === 'n' || trimmedAnswer === 'no') {\n resolve(false);\n return;\n }\n\n // Empty answer uses default\n if (trimmedAnswer === '') {\n resolve(defaultValue);\n return;\n }\n\n // Invalid input defaults to false for safety\n resolve(false);\n });\n });\n}\n\n/**\n * Prompts the user for confirmation and exits the process if declined\n *\n * @param options Confirmation options\n * @param exitCode Exit code to use if user declines (defaults to 1)\n *\n * @example\n * ```typescript\n * await confirmOrExit({\n * message: 'This will delete all data. Continue? (y/N): '\n * });\n * // Code only reaches here if user confirmed\n * ```\n */\nexport async function confirmOrExit(\n options: ConfirmOptions,\n exitCode: number = 1,\n): Promise<void> {\n const confirmed = await confirm(options);\n if (!confirmed) {\n process.exit(exitCode);\n }\n}", "export const parseWorkspaceResourceName = (resourceName: string) => {\n const [collection, workspaceId] = resourceName.split('/');\n if (collection !== 'workspaces') {\n throw new Error(`Invalid workspace resource name: ${resourceName}`);\n }\n return { workspaceId };\n};\n\nexport const parseGraphResourceName = (resourceName: string) => {\n const [workspaceCollection, workspaceId, graphCollection, graphId] =\n resourceName.split('/');\n if (\n workspaceCollection !== 'workspaces' ||\n graphCollection !== 'graphs' ||\n graphId === undefined\n ) {\n throw new Error(`Invalid graph resource name: ${resourceName}`);\n }\n return { workspaceId, graphId };\n};\n\nexport const getGraphResourceName = (workspaceId: string, graphId: string) => {\n return `workspaces/${workspaceId}/graphs/${graphId}`;\n};\n\nexport const getGraphVariantResourceName = (\n workspaceId: string,\n graphId: string,\n variantId: string,\n) => {\n return `${getGraphResourceName(workspaceId, graphId)}/variants/${variantId}`;\n};\n\nexport const getWorkspaceResourceName = (workspaceId: string) => {\n return `workspaces/${workspaceId}`;\n};\n\nexport const getGraphDeploymentResourceName = (\n workspaceId: string,\n graphId: string,\n) => {\n return `${getGraphResourceName(workspaceId, graphId)}/deploy`;\n};\n", "import * as readline from 'readline';\n\nimport * as ui from './ui';\n\n/**\n * Options for configuring the selector behavior\n */\nexport interface SelectorOptions<T> {\n /**\n * The items to select from\n */\n items: T[];\n\n /**\n * Function to get the display name for an item\n */\n getDisplayName: (item: T) => string;\n\n /**\n * Function to get the ID/resource name for an item\n */\n getIdentifier: (item: T) => string;\n\n /**\n * The prompt message to show to the user\n */\n prompt: string;\n\n /**\n * The title to show before listing items\n */\n title: string;\n\n /**\n * If true, automatically select the first item without prompting\n */\n forceFirst?: boolean;\n\n /**\n * Message to show when no items are found\n */\n noItemsMessage?: string;\n\n /**\n * Message to show for invalid selection\n */\n invalidSelectionMessage?: string;\n}\n\n/**\n * Generic selector utility that provides a consistent interface for selecting items\n * from a list. Supports selection by index number or identifier.\n *\n * @param options Configuration options for the selector\n * @returns The selected item or null if no selection was made\n */\nexport async function selectItem<T>(\n options: SelectorOptions<T>,\n): Promise<T | null> {\n const {\n items,\n getDisplayName,\n getIdentifier,\n prompt,\n title,\n forceFirst = false,\n noItemsMessage = 'No items found.',\n invalidSelectionMessage = 'Invalid selection. Please enter a valid number or identifier.',\n } = options;\n\n if (items.length === 0) {\n ui.printError(noItemsMessage);\n return null;\n }\n\n // If forceFirst is true, return the first item without prompting\n if (forceFirst) {\n return items[0];\n }\n\n // Display available items\n console.log();\n ui.printHeader(title);\n items.forEach((item, idx) => {\n const displayName = getDisplayName(item);\n const identifier = getIdentifier(item);\n ui.printListItem(`${idx + 1}. ${displayName} (ID: ${identifier})`);\n });\n\n // Create readline interface for user input\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const question = (query: string): Promise<string> =>\n new Promise((resolve) => rl.question(query, resolve));\n\n let selectedItem: T | null = null;\n\n try {\n while (!selectedItem) {\n const answer = (await question(`\\n${prompt} `)).trim();\n\n // Try to match by number\n const idx = parseInt(answer, 10);\n if (!isNaN(idx) && idx >= 1 && idx <= items.length) {\n selectedItem = items[idx - 1];\n } else {\n // Try to match by identifier (full or partial)\n selectedItem =\n items.find((item) => {\n const identifier = getIdentifier(item);\n return (\n identifier === answer || identifier.split('/').pop() === answer\n );\n }) || null;\n }\n\n if (!selectedItem) {\n ui.printError(invalidSelectionMessage);\n // Exit the loop and return null for invalid selection\n break;\n }\n }\n } finally {\n rl.close();\n }\n\n return selectedItem;\n}\n\n/**\n * Selector options with exit capability\n */\nexport interface SelectorWithExitOptions<T> extends SelectorOptions<T> {\n /**\n * If true, the process will exit with code 1 when selection fails\n */\n exitOnFailure?: boolean;\n}\n\n/**\n * Wrapper around selectItem that exits the process on failure\n *\n * @param options Configuration options for the selector\n * @returns The selected item (never null due to process exit on failure)\n */\nexport async function selectItemOrExit<T>(\n options: SelectorWithExitOptions<T>,\n): Promise<T> {\n const { exitOnFailure = true, ...selectorOptions } = options;\n\n const selected = await selectItem(selectorOptions);\n\n if (!selected && exitOnFailure) {\n process.exit(1);\n }\n\n return selected!;\n}\n\n", "import chalk from 'chalk';\nimport { Command } from 'commander';\nimport * as readline from 'readline';\n\nimport { authManager } from '../../auth/manager.js';\nimport { confirm } from '../../utils/confirm.js';\nimport * as ui from '../../utils/ui';\n\nconst logoutAction = async (options: { force: boolean }) => {\n try {\n // Check if user is authenticated\n const isAuthenticated = await authManager.isAuthenticated();\n\n if (!isAuthenticated) {\n ui.print('You are not currently authenticated.');\n process.exit(0);\n }\n\n // Get stored credentials to show which account is being logged out\n const credentials = await authManager.getCredentials();\n const email = credentials?.email || 'Unknown user';\n\n console.log();\n ui.printHeader('\uD83C\uDFAD Inworld CLI - Logout');\n ui.print(`Current account: ${email}`);\n\n // Ask for confirmation unless --force flag is used\n if (!options.force) {\n const confirmed = await confirm({\n message: '\\nAre you sure you want to logout? (y/N): ',\n defaultValue: false,\n });\n\n if (!confirmed) {\n console.log();\n ui.print('Logout cancelled.');\n process.exit(0);\n }\n }\n\n // Clear credentials\n console.log();\n ui.print('Clearing stored credentials...');\n await authManager.clearCredentials();\n\n ui.success('\u2713 Successfully logged out.');\n ui.print('You will need to authenticate again to use Inworld services.');\n\n process.exit(0);\n } catch (error) {\n console.log();\n ui.printError('Failed to logout:');\n console.error(error);\n process.exit(1);\n }\n};\n\nconst makeLogoutCommand = (description: string) => {\n return new Command('logout')\n .description(description)\n .option('-f, --force', 'Skip confirmation prompt')\n .action(logoutAction);\n};\n\nexport const logoutCommandAlias = makeLogoutCommand(\n `Alias for \"${chalk.bold('inworld auth logout')}\"`,\n);\n\nexport const logoutCommand = makeLogoutCommand(\n 'Clear stored authentication credentials',\n);\n", "import chalk from 'chalk';\nimport { Command } from 'commander';\n\nimport { authManager } from '../../auth/manager';\nimport { PLATFORM_URL } from '../../constants';\nimport * as ui from '../../utils/ui';\n\nconst statusAction = async () => {\n try {\n const credentials = await authManager.getCredentials();\n\n ui.printHeader('\\nInworld CLI Status\\n');\n\n if (!credentials) {\n // credentials are ensured by requireAuth call.\n ui.print('Not authenticated.');\n ui.print(`Run \\`${chalk.white('inworld auth login')}\\` to authenticate.`);\n if (process.env.INWORLD_API_KEY) {\n ui.print(\n `\\nINWORLD_API_KEY environment variable: ${ui.trimBase64Key(process.env.INWORLD_API_KEY)} (active)`,\n );\n }\n\n process.exit(0);\n }\n\n // Authentication Status\n ui.printBright('Authentication:');\n ui.print(` Email: ${credentials.email}`);\n if (credentials.env !== 'PROD') {\n ui.print(` Environment: ${credentials.env}`);\n }\n\n // Token Status\n if (credentials.inworldToken) {\n const isExpired =\n credentials.expiresAt && Date.now() > credentials.expiresAt;\n const expirationDate = credentials.expiresAt\n ? new Date(credentials.expiresAt).toLocaleString()\n : 'Unknown';\n\n console.log();\n ui.printBright('Token Status:');\n ui.print(\n ` Inworld Token: ${ui.trimToken(credentials.inworldToken)}`,\n );\n ui.print(` Expires At: ${expirationDate}`);\n ui.print(` Status: ${isExpired ? 'Expired' : 'Valid'}`);\n } else {\n ui.printHeader('\\nToken Status:');\n ui.print(` Inworld Token: Not available`);\n }\n\n ui.print(\n ` Refresh Token: ${ui.trimToken(credentials.refreshToken)}`,\n );\n ui.print(` Session Status: Active`);\n\n // Workspace Status\n ui.printBright('\\nActive Workspace:');\n if (credentials.workspace) {\n ui.print(` Workspace id: ${credentials.workspace}`);\n ui.print(\n ` Workspace link: ${ui.workspaceLink(credentials.workspace)}`,\n );\n } else {\n ui.print(` No workspace activated`);\n ui.print(` Run \"inworld workspace activate\" to select a workspace`);\n }\n\n // API Key Status\n ui.printBright('\\nAPI Key:');\n\n if (process.env.INWORLD_API_KEY) {\n ui.print(\n ` INWORLD_API_KEY environment variable: ${ui.trimBase64Key(process.env.INWORLD_API_KEY)} (active)`,\n );\n }\n\n if (credentials.apiKey) {\n // Only show first and last few characters for security\n const maskedKey =\n credentials.apiKey.length > 20\n ? `${ui.trimBase64Key(credentials.apiKey)}`\n : '***';\n ui.print(` Stored API Key: ${maskedKey}`);\n } else {\n ui.print(` No API key configured`);\n if (credentials.workspace) {\n ui.print(` Run \"inworld apikey select\" to choose an API key`);\n }\n }\n\n console.log();\n\n process.exit(0);\n } catch (error) {\n console.log();\n ui.printError('Failed to get status:');\n console.error(error);\n process.exit(1);\n }\n};\n\nconst makeStatusCommand = (description: string) => {\n return new Command('status').description(description).action(statusAction);\n};\n\nexport const statusCommand = makeStatusCommand(\n 'Display current authentication status and configuration',\n);\n\nexport const statusCommandAlias = makeStatusCommand(\n `Alias for \"${ui.bold('inworld auth status')}\"`,\n);\n", "import { Command } from 'commander';\n\nimport { loginCiCommand } from './auth/login_ci_command';\nimport { loginCommand } from './auth/login_command';\nimport { logoutCommand } from './auth/logout_command';\nimport { printAccessTokenCommand } from './auth/print_access_token_command';\nimport { printApiKeyCommand } from './auth/print_api_key_command';\nimport { statusCommand } from './auth/status_command';\n\n// Create the graph parent command\nexport const authCommand = new Command('auth')\n .description('Manage Inworld authentication')\n .addCommand(loginCommand)\n .addCommand(loginCiCommand)\n .addCommand(logoutCommand)\n .addCommand(printAccessTokenCommand)\n .addCommand(printApiKeyCommand)\n .addCommand(statusCommand)\n .action(() => {\n authCommand.help();\n });\n", "import { Command } from 'commander';\n\nimport { authManager } from '../../auth';\nimport { INWORLD_ENV } from '../../constants';\nimport { WorkspaceService } from '../../services/workspace_service.js';\nimport { setGlobalForceYes } from '../../utils/confirm.js';\nimport * as ui from '../../utils/ui';\n\nconst loginCiAction = async (options: {\n token: string;\n refreshToken?: string;\n email: string;\n}) => {\n try {\n // Enable auto-confirm for all prompts in CI mode\n setGlobalForceYes(true);\n\n console.log();\n ui.printHeader('\uD83C\uDFAD Authenticating with external Firebase token');\n console.log();\n\n const success = await authManager.authenticateAndSaveCredentials(\n options.token,\n options.refreshToken || options.token, // Use token as fallback if no refresh token\n options.email,\n /* workspace */ undefined,\n INWORLD_ENV,\n );\n\n if (!success) {\n ui.printError('Failed to authenticate with provided token');\n process.exit(1);\n }\n\n console.log();\n ui.success('\u2713 Authentication successful!');\n ui.print(`Email: ${options.email}`);\n\n await WorkspaceService.activateWorkspace({ forceFirst: true });\n\n ui.print('\\nAuthentication completed.');\n process.exit(0);\n } catch (error) {\n console.log();\n ui.printError('Token-based authentication failed:');\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const loginCiCommand = new Command('login-ci')\n .description('Authenticate using Firebase token (for CI/testing)')\n .requiredOption('-t, --token <token>', 'Firebase ID token')\n .requiredOption('-e, --email <email>', 'Email address')\n .option(\n '-r, --refresh-token <refreshToken>',\n 'Firebase refresh token (optional, enables token refresh)',\n )\n .action(loginCiAction);", "import { Command } from 'commander';\n\nimport { authManager } from '../../auth/manager';\n\nconst printAccessTokenAction = async () => {\n try {\n // Get valid token (this will refresh if needed)\n const token = await authManager.getValidToken();\n\n if (token) {\n console.log(token);\n return;\n }\n\n // No token found or failed to refresh\n process.exit(1);\n } catch (_error) {\n process.exit(1);\n }\n};\n\nexport const printAccessTokenCommand = new Command('print-access-token')\n .description('Print the current Inworld access token')\n .action(printAccessTokenAction);\n", "import { Command } from 'commander';\n\nimport { authManager } from '../../auth/manager.js';\n\nconst printApiKeyAction = async () => {\n try {\n // Check environment variable first (takes precedence)\n if (process.env.INWORLD_API_KEY) {\n console.log(process.env.INWORLD_API_KEY);\n return;\n }\n\n // Check stored credentials\n const credentials = await authManager.getCredentials();\n if (credentials?.apiKey) {\n console.log(credentials.apiKey);\n return;\n }\n\n // No API key found\n process.exit(1);\n } catch (_error) {\n process.exit(1);\n }\n};\n\nexport const printApiKeyCommand = new Command('print-api-key')\n .description('Print the current API key')\n .action(printApiKeyAction);\n", "import archiver from 'archiver';\nimport chalk from 'chalk';\nimport { Command } from 'commander';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { requireWorkspace } from '../../auth/utils';\nimport { PLATFORM_URL, RUNTIME_VERSION } from '../../constants';\nimport { deployGraph, getGraphDeployment } from '../../services/deploy_service';\nimport { loadGraph } from '../../services/graph_loader';\nimport { getGraphResourceName } from '../../utils/resource_name_helper';\nimport * as ui from '../../utils/ui';\n\n/**\n * User context attributes as key-value pairs.\n */\nexport interface UserContextAttributes {\n [key: string]: string;\n}\n\n/**\n * User context configuration.\n */\nexport interface UserContextInterface {\n /** User attributes as key-value pairs. */\n attributes: UserContextAttributes;\n /** Targeting key for user identification. */\n targetingKey: string;\n}\n\nexport interface ExecutionContext {\n executionId?: string;\n userContext?: UserContextInterface;\n dataStoreContent?: Record<string, any>;\n}\n\n/**\n * Process and enhance the package.json for deployment\n */\nfunction processPackageJson(\n originalPackageJson: any,\n graphFileName: string,\n): any {\n // Clone the original package.json\n const packageJson = JSON.parse(JSON.stringify(originalPackageJson));\n\n // Update/add deployment-specific fields\n packageJson.name = packageJson.name || 'inworld-graph-deployment';\n packageJson.version = packageJson.version || '1.0.0';\n packageJson.description =\n packageJson.description || 'Inworld Runtime Graph Deployment Package';\n packageJson.main = graphFileName;\n\n // Ensure scripts section exists and add deployment scripts\n packageJson.scripts = packageJson.scripts || {};\n packageJson.scripts.start = `npx inworld serve --host 0.0.0.0 ${graphFileName}`;\n packageJson.scripts['run'] = `npx inworld run ${graphFileName}`;\n\n // Ensure @inworld/runtime is included if not already present\n packageJson.dependencies = packageJson.dependencies || {};\n if (!packageJson.dependencies['@inworld/runtime']) {\n packageJson.dependencies['@inworld/runtime'] = RUNTIME_VERSION;\n }\n\n // Ensure @inworld/cli is in dependencies\n if (!packageJson.dependencies['@inworld/cli']) {\n packageJson.dependencies['@inworld/cli'] =\n 'https://storage.googleapis.com/assets-inworld-ai/node-packages/inworld-cli-0.2.15.tgz';\n }\n\n // Ensure dotenv is in dependencies\n if (!packageJson.dependencies['dotenv']) {\n packageJson.dependencies['dotenv'] = '^17.2.1';\n }\n\n // Remove unnecessary fields for deployment\n delete packageJson.devDependencies; // Remove dev deps to reduce package size\n delete packageJson.scripts.test;\n delete packageJson.scripts.lint;\n delete packageJson.scripts.build;\n delete packageJson.scripts.prepare;\n\n return packageJson;\n}\n\nconst deployAction = async (\n file: string,\n options: { info?: boolean; packageOnly?: string | boolean },\n) => {\n try {\n const workspaceId = await requireWorkspace();\n const { graph, bundledCode, originalPackageJson, packageJsonPath } =\n await loadGraph(file);\n const graphResourceName = getGraphResourceName(workspaceId, graph.graphId);\n\n if (options.info) {\n const deployment = await getGraphDeployment(graphResourceName);\n console.log(deployment);\n ui.success('Inworld Cloud URI:');\n ui.print(\n `${PLATFORM_URL.replace('platform', 'api')}/cloud/${graphResourceName}/v1/graph:start`,\n );\n process.exit(0);\n }\n\n const randomId = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;\n const tempBaseDir = path.join(os.tmpdir(), 'inworld', randomId);\n\n if (!fs.existsSync(tempBaseDir)) {\n fs.mkdirSync(tempBaseDir, { recursive: true });\n }\n\n const outputPath = path.join(tempBaseDir, 'graph-deployment.zip');\n\n const output = fs.createWriteStream(outputPath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', () => {\n if (options.packageOnly) {\n let packageName;\n if (options.packageOnly === true) {\n packageName = 'graph-deployment.zip';\n } else {\n packageName = options.packageOnly;\n }\n // Determine the destination path (handle both absolute and relative paths)\n const destinationPath = path.isAbsolute(packageName)\n ? packageName\n : path.join(process.cwd(), packageName);\n\n // Copy from temp location to destination\n fs.copyFileSync(outputPath, destinationPath);\n ui.success(`\u2705 Graph packaged successfully: ${destinationPath}`);\n process.exit(0);\n }\n\n ui.success(`\u2705 Graph packaged successfully: ${outputPath}`);\n ui.print(` Size: ${(archive.pointer() / 1024).toFixed(2)} KB`);\n console.log();\n ui.print('Deployment should take around 5 minutes, please be patient.');\n ui.print('Deploying...');\n console.log();\n resolve();\n });\n\n archive.on('error', (err) => {\n reject(err);\n });\n\n output.on('error', (err) => {\n reject(err);\n });\n });\n\n archive.pipe(output);\n\n // Add the bundled graph file\n const graphFileName = path.basename(file).replace('.ts', '.js');\n archive.append(bundledCode!, { name: graphFileName });\n\n // Process and add package.json\n const packageJson = processPackageJson(originalPackageJson, graphFileName);\n\n archive.append(JSON.stringify(packageJson, null, 2), {\n name: 'package.json',\n });\n\n // Add a README with instructions\n const readme = `# Inworld Graph Deployment\n\nThis package contains an Inworld Runtime graph ready for deployment.\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Running the Graph\n\n### As a server (recommended):\n\\`\\`\\`bash\ninworld serve ${graphFileName}\n\\`\\`\\`\n\n### Direct execution:\n\\`\\`\\`bash\ninworld run ${graphFileName}\n\\`\\`\\`\n\n## Graph File\n- **Bundled File**: ${graphFileName}\n- **Original Source**: ${path.basename(file)}\n- **Package source**: ${path.relative(process.cwd(), packageJsonPath)}\n\n## Notes\n- This graph module has been bundled with all local files (custom nodes, local imports, etc.)\n- NPM packages remain external and will be installed via package.json dependencies\n- The bundle includes all your custom code in a single file for easy deployment\n\n## Requirements\n- Node.js >= 18.0.0\n- @inworld/cli package installed globally or locally\n`;\n\n archive.append(readme, { name: 'README.md' });\n await archive.finalize();\n await archiveComplete;\n const deployment = await deployGraph(\n graph.graphId,\n new Uint8Array(fs.readFileSync(outputPath)),\n );\n\n if (!deployment) {\n ui.printError('Deployment failed');\n try {\n fs.rmSync(tempBaseDir, { recursive: true, force: true });\n } catch {}\n process.exit(1);\n }\n\n ui.success('Deployment successful!');\n ui.success('Inworld Cloud URI:');\n ui.print(\n `${PLATFORM_URL.replace('platform', 'api')}/cloud/${graphResourceName}/v1/graph:start`,\n );\n\n try {\n fs.rmSync(tempBaseDir, { recursive: true, force: true });\n } catch (_error) {\n // Silently ignore cleanup errors\n }\n\n process.exit(0);\n } catch (error) {\n ui.printError('Error packaging graph:');\n console.error(error);\n process.exit(1);\n }\n};\n\nconst makeDeployCommand = (description: string) => {\n return new Command('deploy')\n .description(description)\n .argument('<file>', 'Path to the graph file (e.g., test.ts)')\n .option('-i, --info', 'Shows deployment info if any')\n .option(\n '-p, --package-only [file]',\n 'Output file path (if not specified, outputs to graph-deployment.zip in current directory)',\n )\n .action(deployAction);\n};\n\nexport const deployCommand = makeDeployCommand(\n '[preview] Packages a graph for deployment to the Inworld Cloud.',\n);\n\nexport const deployCommandAlias = makeDeployCommand(\n `[preview] Alias for \"${chalk.bold('inworld graph deploy')}\"`,\n);\n", "// @ts-nocheck\n/*\n * This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY\n */\n\nimport * as fm from '../../../../../../fetch.pb';\nimport * as GoogleLongrunningOperations from '../../../../../../google/longrunning/operations.pb';\nimport * as GoogleProtobufEmpty from '../../../../../../google/protobuf/empty.pb';\nimport * as GoogleProtobufField_mask from '../../../../../../google/protobuf/field_mask.pb';\nimport * as GoogleProtobufTimestamp from '../../../../../../google/protobuf/timestamp.pb';\nimport * as AiInworldStudioV1RemoteConfigurationGraph_configuration from './graph_configuration.pb';\nimport * as AiInworldStudioV1RemoteConfigurationTargeting from './targeting.pb';\n\nexport enum DeployState {\n DEPLOY_STATE_UNSPECIFIED = 'DEPLOY_STATE_UNSPECIFIED',\n DEPLOY_STATE_IN_PROGRESS = 'DEPLOY_STATE_IN_PROGRESS',\n DEPLOY_STATE_SUCCESSFUL = 'DEPLOY_STATE_SUCCESSFUL',\n DEPLOY_STATE_FAILED = 'DEPLOY_STATE_FAILED',\n}\n\nexport type Graph = {\n name?: string;\n displayName?: string;\n targeting?: AiInworldStudioV1RemoteConfigurationTargeting.Targeting;\n createTime?: GoogleProtobufTimestamp.Timestamp;\n updateTime?: GoogleProtobufTimestamp.Timestamp;\n};\n\nexport type GetGraphRequest = {\n name?: string;\n};\n\nexport type ListGraphsRequest = {\n parent?: string;\n pageSize?: number;\n pageToken?: string;\n};\n\nexport type ListGraphsResponse = {\n graphs?: Graph[];\n nextPageToken?: string;\n};\n\nexport type CreateGraphRequest = {\n parent?: string;\n graph?: Graph;\n};\n\nexport type UpdateGraphRequest = {\n graph?: Graph;\n updateMask?: GoogleProtobufField_mask.FieldMask;\n};\n\nexport type DeleteGraphRequest = {\n name?: string;\n};\n\nexport type CreateGraphMetadata = {};\n\nexport type UpdateGraphMetadata = {};\n\nexport type GetGraphVariantRequest = {\n name?: string;\n};\n\nexport type ListGraphVariantsRequest = {\n parent?: string;\n pageSize?: number;\n pageToken?: string;\n};\n\nexport type ListGraphVariantsResponse = {\n graphVariants?: GraphVariant[];\n nextPageToken?: string;\n};\n\nexport type CreateGraphVariantRequest = {\n parent?: string;\n graphVariant?: GraphVariant;\n};\n\nexport type UpdateGraphVariantRequest = {\n graphVariant?: GraphVariant;\n updateMask?: GoogleProtobufField_mask.FieldMask;\n};\n\nexport type DeleteGraphVariantRequest = {\n name?: string;\n};\n\nexport type CreateGraphVariantMetadata = {};\n\nexport type UpdateGraphVariantMetadata = {};\n\nexport type GraphVariant = {\n name?: string;\n displayName?: string;\n graph?: string;\n config?: AiInworldStudioV1RemoteConfigurationGraph_configuration.GraphConfig;\n createTime?: GoogleProtobufTimestamp.Timestamp;\n updateTime?: GoogleProtobufTimestamp.Timestamp;\n};\n\nexport type DeployGraphRequest = {\n parent?: string;\n graph?: DeployGraphInfo;\n};\n\nexport type DeployGraphInfo = {\n archive?: Uint8Array;\n archiveType?: string;\n};\n\nexport type DeployGraphResponse = {\n graphVariant?: string;\n};\n\nexport type GetGraphDeploymentRequest = {\n name?: string;\n};\n\nexport type GraphDeployment = {\n name?: string;\n createTime?: GoogleProtobufTimestamp.Timestamp;\n updateTime?: GoogleProtobufTimestamp.Timestamp;\n cloudRunFunction?: string;\n invokeUri?: string;\n deployStatus?: DeployState;\n};\n\nexport type DeployGraphMetadata = {};\n\nexport class GraphsService {\n static CreateGraph(\n req: CreateGraphRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n CreateGraphRequest,\n GoogleLongrunningOperations.Operation\n >(`/studio/v1/${req['parent']}/graphs`, {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req['graph'], fm.replacer),\n });\n }\n static DeployGraph(\n req: DeployGraphRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n DeployGraphRequest,\n GoogleLongrunningOperations.Operation\n >(`/studio/v1/${req['parent']}:deploy`, {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req, fm.replacer),\n });\n }\n static GetGraphDeployment(\n req: GetGraphDeploymentRequest,\n initReq?: fm.InitReq,\n ): Promise<GraphDeployment> {\n return fm.fetchReq<GetGraphDeploymentRequest, GraphDeployment>(\n `/studio/v1/${req['name']}?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static GetGraph(req: GetGraphRequest, initReq?: fm.InitReq): Promise<Graph> {\n return fm.fetchReq<GetGraphRequest, Graph>(\n `/studio/v1/${req['name']}?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static ListGraphs(\n req: ListGraphsRequest,\n initReq?: fm.InitReq,\n ): Promise<ListGraphsResponse> {\n return fm.fetchReq<ListGraphsRequest, ListGraphsResponse>(\n `/studio/v1/${req['parent']}/graphs?${fm.renderURLSearchParams(req, ['parent'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static UpdateGraph(\n req: UpdateGraphRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n UpdateGraphRequest,\n GoogleLongrunningOperations.Operation\n >(`/studio/v1/${req['graph']['name']}`, {\n ...initReq,\n method: 'PATCH',\n body: JSON.stringify(req['graph'], fm.replacer),\n });\n }\n static DeleteGraph(\n req: DeleteGraphRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<DeleteGraphRequest, GoogleProtobufEmpty.Empty>(\n `/studio/v1/${req['name']}`,\n { ...initReq, method: 'DELETE' },\n );\n }\n static CreateGraphVariant(\n req: CreateGraphVariantRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n CreateGraphVariantRequest,\n GoogleLongrunningOperations.Operation\n >(`/studio/v1/${req['parent']}/variants`, {\n ...initReq,\n method: 'POST',\n body: JSON.stringify(req['graphVariant'], fm.replacer),\n });\n }\n static GetGraphVariant(\n req: GetGraphVariantRequest,\n initReq?: fm.InitReq,\n ): Promise<GraphVariant> {\n return fm.fetchReq<GetGraphVariantRequest, GraphVariant>(\n `/studio/v1/${req['name']}?${fm.renderURLSearchParams(req, ['name'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static ListGraphVariants(\n req: ListGraphVariantsRequest,\n initReq?: fm.InitReq,\n ): Promise<ListGraphVariantsResponse> {\n return fm.fetchReq<ListGraphVariantsRequest, ListGraphVariantsResponse>(\n `/studio/v1/${req['parent']}/variants?${fm.renderURLSearchParams(req, ['parent'])}`,\n { ...initReq, method: 'GET' },\n );\n }\n static UpdateGraphVariant(\n req: UpdateGraphVariantRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleLongrunningOperations.Operation> {\n return fm.fetchReq<\n UpdateGraphVariantRequest,\n GoogleLongrunningOperations.Operation\n >(`/studio/v1/${req['graphVariant']['name']}`, {\n ...initReq,\n method: 'PATCH',\n body: JSON.stringify(req['graphVariant'], fm.replacer),\n });\n }\n static DeleteGraphVariant(\n req: DeleteGraphVariantRequest,\n initReq?: fm.InitReq,\n ): Promise<GoogleProtobufEmpty.Empty> {\n return fm.fetchReq<DeleteGraphVariantRequest, GoogleProtobufEmpty.Empty>(\n `/studio/v1/${req['name']}`,\n { ...initReq, method: 'DELETE' },\n );\n }\n}\n", "import chalk from 'chalk';\nimport ora, { Ora } from 'ora';\n\nconst PHRASES = [\n 'Condensing time-space matter',\n 'Starting particle collider',\n 'Calibrating quantum flux capacitor',\n 'Reversing polarity of neutron flow',\n 'Aligning cosmic frequencies',\n 'Compiling infinite loops',\n 'Downloading more RAM',\n 'Reticulating splines',\n 'Generating witty loading messages',\n 'Convincing electrons to cooperate',\n 'Negotiating with the cloud overlords',\n 'Bribing the API hamsters',\n 'Warming up the server potatoes',\n 'Untangling quantum entanglements',\n 'Feeding the deployment gremlins',\n 'Optimizing coffee-to-code ratio',\n 'Summoning the deployment spirits',\n 'Consulting the ancient scrolls',\n 'Charging the flux compensators',\n 'Stabilizing temporal anomalies',\n 'Synchronizing parallel universes',\n 'Decoding the matrix',\n 'Activating turbo encabulator',\n 'Adjusting the dilithium crystals',\n];\n\n/**\n * Configuration for the LRO spinner\n */\nexport interface LROSpinnerConfig {\n initialText?: string;\n phraseInterval?: number;\n showIterations?: boolean;\n spinnerStyle?: string;\n}\n\n/**\n * Creates and manages a spinner for long-running operations\n */\nexport class LROSpinner {\n private spinner: Ora;\n private phraseInterval?: NodeJS.Timeout;\n private currentPhraseIndex: number = 0;\n private config: Required<LROSpinnerConfig>;\n private iterationCount: number = 0;\n private startTime: number;\n\n constructor(config: LROSpinnerConfig = {}) {\n this.config = {\n initialText: 'Initializing deployment',\n phraseInterval: 10000,\n showIterations: true,\n spinnerStyle: 'dots8Bit',\n ...config,\n };\n\n this.spinner = ora({\n text: this.config.initialText,\n spinner: this.config.spinnerStyle as any,\n color: 'cyan',\n });\n\n this.startTime = Date.now();\n }\n\n /**\n * Starts the spinner with rotating phrases\n */\n start(): void {\n this.spinner.start();\n this.updateText();\n\n // Start rotating phrases\n this.phraseInterval = setInterval(() => {\n // this.currentPhraseIndex = (this.currentPhraseIndex + 1) % PHRASES.length;\n this.updateText();\n }, this.config.phraseInterval);\n }\n\n /**\n * Updates the spinner text with current phrase and optional iteration count\n */\n private updateText(): void {\n const phrase = LROSpinner.getRandomPhrase();\n const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1000);\n\n let text = chalk.cyan(phrase);\n\n if (this.config.showIterations && this.iterationCount > 0) {\n text += chalk.gray(\n ` (iteration ${this.iterationCount}, ${elapsedSeconds}s)`,\n );\n } else if (elapsedSeconds > 0) {\n text += chalk.gray(` (${elapsedSeconds}s)`);\n }\n\n this.spinner.text = text;\n }\n\n /**\n * Updates the iteration count\n */\n updateIteration(iteration: number): void {\n this.iterationCount = iteration + 1; // Convert 0-based to 1-based for display\n this.updateText();\n }\n\n /**\n * Updates spinner with custom text temporarily\n */\n updateCustomText(text: string): void {\n this.spinner.text = chalk.yellow(text);\n }\n\n /**\n * Succeeds the spinner with a success message\n */\n succeed(text?: string): void {\n this.cleanup();\n const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1000);\n const successText =\n text || `Deployment completed successfully in ${elapsedSeconds}s`;\n this.spinner.succeed(chalk.green(successText));\n }\n\n /**\n * Fails the spinner with an error message\n */\n fail(text?: string): void {\n this.cleanup();\n const errorText = text || 'Deployment failed';\n this.spinner.fail(chalk.red(errorText));\n }\n\n /**\n * Warns the spinner with a warning message\n */\n warn(text?: string): void {\n this.cleanup();\n const warnText = text || 'Deployment completed with warnings';\n this.spinner.warn(chalk.yellow(warnText));\n }\n\n /**\n * Stops the spinner without any status\n */\n stop(): void {\n this.cleanup();\n this.spinner.stop();\n }\n\n /**\n * Cleans up intervals\n */\n private cleanup(): void {\n if (this.phraseInterval) {\n clearInterval(this.phraseInterval);\n this.phraseInterval = undefined;\n }\n }\n\n /**\n * Gets a random phrase for one-off usage\n */\n static getRandomPhrase(): string {\n return PHRASES[Math.floor(Math.random() * PHRASES.length)];\n }\n}\n\n/**\n * Helper function to create spinner callbacks for LRO operations\n */\nexport function createLROSpinnerCallbacks(config?: LROSpinnerConfig) {\n let spinner: LROSpinner | null = null;\n\n return {\n startCallback: (operationName: string) => {\n spinner = new LROSpinner({\n ...config,\n initialText: `Starting operation: ${operationName}`,\n });\n spinner.start();\n },\n\n iterationCallback: (\n operationName: string,\n _checkResponse: any,\n checkData: {\n checkIteration: number;\n checkLimit: number;\n checkTimeout: number;\n },\n ) => {\n if (spinner) {\n spinner.updateIteration(checkData.checkIteration);\n\n // Add progress warning if getting close to limit\n if (checkData.checkIteration > checkData.checkLimit * 0.8) {\n spinner.updateCustomText(\n chalk.yellow(\n `\u26A0\uFE0F Taking longer than expected... (${checkData.checkIteration}/${checkData.checkLimit})`,\n ),\n );\n }\n }\n },\n\n doneCallback: (_operationName: string, _response: any) => {\n if (spinner) {\n spinner.succeed(`Operation completed.`);\n spinner = null;\n }\n },\n\n errorCallback: (operationName: string, error: string) => {\n if (spinner) {\n spinner.fail(`Operation ${operationName} failed: ${error}`);\n spinner = null;\n }\n },\n };\n}\n", "import { GraphsService } from '../../proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb';\nimport {\n authenticatedInworldRequest,\n requireAuth,\n requireWorkspace,\n} from '../auth/utils';\nimport { isGrpcError } from '../grpc/core/InworldError';\nimport { GrpcStatusCode } from '../grpc/core/statusCodes';\nimport { checkLRO } from '../utils/long_running_operations';\nimport {\n getGraphResourceName,\n getWorkspaceResourceName,\n} from '../utils/resource_name_helper';\nimport { createLROSpinnerCallbacks } from '../utils/spinner';\nimport * as ui from '../utils/ui';\n\nexport const deployGraph = async (graphId: string, _archive: Uint8Array) => {\n const workspaceId = await requireWorkspace();\n const graphResourceName = getGraphResourceName(workspaceId, graphId);\n\n try {\n await ensureGraphRegistered(workspaceId, graphId);\n } catch (error) {\n ui.printError(\n `Error ensuring graph registration on workspace ${workspaceId}:`,\n );\n console.error(error);\n process.exit(1);\n }\n\n try {\n const operation = await authenticatedInworldRequest(\n GraphsService.DeployGraph,\n {\n parent: graphResourceName,\n graph: {\n archive: _archive,\n archiveType: 'zip',\n },\n },\n );\n\n const gracefulShutdown = () => {\n process.exit(0);\n };\n for (const signal of [\n 'SIGINT',\n 'SIGTERM',\n 'SIGQUIT',\n 'SIGSEGV',\n 'SIGBUS',\n 'exit',\n ]) {\n process.on(signal, gracefulShutdown);\n }\n\n const spinnerCallbacks = createLROSpinnerCallbacks({\n initialText: `Deploying graph \"${graphId}\" to Inworld platform`,\n showIterations: false,\n phraseInterval: 10000, // Change phrase every 10 seconds\n });\n\n await checkLRO({\n operationName: operation.name,\n checkLimit: 100,\n checkTimeout: 8000,\n returnWithMetadata: true,\n pollOptions: spinnerCallbacks,\n });\n } catch (error) {\n ui.printError('Error deploying graph:');\n console.error(error);\n process.exit(1);\n }\n\n const deployment = await getGraphDeployment(graphResourceName);\n return deployment;\n};\n\nexport const getGraphDeployment = async (graphResourceName: string) => {\n requireAuth();\n return await authenticatedInworldRequest(GraphsService.GetGraphDeployment, {\n name: graphResourceName + '/deploy',\n });\n};\n\nexport const ensureGraphRegistered = async (\n workspaceId: string,\n graphId: string,\n) => {\n requireAuth();\n const graphResourceName = getGraphResourceName(workspaceId, graphId);\n try {\n return await getGraph(graphResourceName);\n } catch (error) {\n if (isGrpcError(error) && error.code === GrpcStatusCode.NOT_FOUND) {\n ui.print(\n `Graph \"${graphId}\" is not registered on the Inworld platform for workspace \"${workspaceId}\", registering now...`,\n );\n await registerGraph(workspaceId, graphId);\n } else {\n throw error;\n }\n }\n};\n\n/**\n *\n * @param graphResourceName\n * @returns\n *\n * @throws {GrpcError}\n */\nconst getGraph = async (graphResourceName: string) => {\n requireAuth();\n return await authenticatedInworldRequest(GraphsService.GetGraph, {\n name: graphResourceName,\n });\n};\n\n/**\n *\n * @param workspace\n * @param graphResourceName\n * @param displayName\n * @returns\n *\n * @throws {GrpcError}\n */\nconst registerGraph = async (workspaceId: string, graphId: string) => {\n requireAuth();\n const graphResourceName = getGraphResourceName(workspaceId, graphId);\n const workspaceResourceName = getWorkspaceResourceName(workspaceId);\n const operation = await authenticatedInworldRequest(\n GraphsService.CreateGraph,\n {\n parent: `${workspaceResourceName}`,\n graph: {\n name: graphResourceName,\n displayName: graphId,\n targeting: { rawContent: JSON.stringify({}) },\n },\n },\n );\n\n const spinnerCallbacks = createLROSpinnerCallbacks({\n initialText: `Registering graph ${graphId} on Inworld platform`,\n showIterations: false,\n });\n\n await checkLRO({\n operationName: operation.name,\n pollOptions: spinnerCallbacks,\n });\n return getGraph(graphResourceName);\n};\n", "import chalk from 'chalk';\nimport * as esbuild from 'esbuild';\nimport fs from 'fs';\nimport { Module } from 'module';\nimport path from 'path';\n\nimport { requireApiKey } from '../auth/utils';\n\nexport const loadGraph = async (file: string) => {\n process.env.INWORLD_API_KEY = await requireApiKey();\n\n // Resolve the file path\n const filePath = path.resolve(process.cwd(), file);\n\n if (!fs.existsSync(filePath)) {\n console.error(`Error: File not found: ${filePath}`);\n process.exit(1);\n }\n\n console.log(`Packaging graph from: ${filePath}`);\n\n // Find the nearest package.json\n const packageJsonPath = findNearestPackageJson(path.dirname(filePath));\n if (!packageJsonPath) {\n console.error('Error: No package.json found in the project hierarchy');\n console.error(\n 'Please ensure your graph file is in a proper Node.js project',\n );\n process.exit(1);\n }\n\n console.log(`Using package.json from: ${packageJsonPath}`);\n const originalPackageJson = JSON.parse(\n fs.readFileSync(packageJsonPath, 'utf-8'),\n );\n\n // Bundle the module with local files\n console.log('Bundling graph module with local dependencies...');\n let bundledCode: string;\n let module;\n\n if (!filePath.endsWith('.ts') && !filePath.endsWith('.js')) {\n console.error('Error: File must be a .ts or .js file');\n process.exit(1);\n }\n\n // Use esbuild to bundle local files together\n const result = await esbuild.build({\n entryPoints: [filePath],\n bundle: true,\n platform: 'node',\n loader: { '.ts': 'ts', '.js': 'js' },\n target: 'node18',\n format: 'cjs',\n // Keep all npm packages external - they'll be installed via package.json\n packages: 'external',\n sourcemap: 'inline',\n write: false,\n logLevel: 'error',\n resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],\n keepNames: true,\n minify: false,\n });\n\n bundledCode = result.outputFiles[0].text;\n\n // Validate that the bundled module exports a graph\n const moduleInstance = new Module(filePath, module);\n moduleInstance.filename = filePath;\n moduleInstance.paths = (Module as any)._nodeModulePaths(\n path.dirname(filePath),\n );\n\n // Compile and evaluate with proper module resolution\n (moduleInstance as any)._compile(bundledCode, filePath);\n module = moduleInstance.exports;\n\n // Validate that the module exports a graph\n if (!module.graph) {\n console.error('Error: The file must export a \"graph\" object');\n process.exit(1);\n }\n\n const graphId = module.graph.graphId;\n\n // Validate that the graphId is alphanumeric, dashes, or underscores\n if (typeof graphId !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(graphId)) {\n console.error(\n chalk.red(\n 'Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores.',\n ),\n );\n process.exit(1);\n }\n\n // FIXME: validate graph module.\n // if (!(module.graph instanceof Graph)) {\n // console.error(\n // 'Error: The exported \"graph\" must be an instance of Inworld Runtime Graph class',\n // );\n // process.exit(1);\n // }\n\n return {\n graph: module.graph,\n bundledCode,\n originalPackageJson,\n packageJsonPath,\n };\n};\n\n/**\n * Find the nearest package.json file by traversing up the directory tree\n */\nfunction findNearestPackageJson(startDir: string): string | null {\n let currentDir = startDir;\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const packageJsonPath = path.join(currentDir, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n return packageJsonPath;\n }\n currentDir = path.dirname(currentDir);\n }\n\n // Check root directory as well\n const rootPackageJson = path.join(root, 'package.json');\n if (fs.existsSync(rootPackageJson)) {\n return rootPackageJson;\n }\n\n return null;\n}\n", "import chalk from 'chalk';\nimport { Command } from 'commander';\nimport fs from 'fs';\nimport path from 'path';\nimport * as readline from 'readline';\nimport { fileURLToPath } from 'url';\n\nimport { RUNTIME_VERSION } from '../../constants.js';\nimport { confirm } from '../../utils/confirm.js';\nimport { selectItem } from '../../utils/selector.js';\nimport * as ui from '../../utils/ui';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Resolve template path - check multiple possible locations\nfunction getTemplatePath(): string {\n const possiblePaths = [\n // Production: templates are copied to dist/templates (when code is bundled in dist/index.js)\n path.join(__dirname, 'templates'),\n // Development: templates are in src/templates (when running from src/)\n path.join(__dirname, '..', '..', 'templates'),\n // Alternative: if running from nested directory structure\n path.join(__dirname, '..', '..', '..', 'templates'),\n ];\n\n for (const templatePath of possiblePaths) {\n if (fs.existsSync(templatePath)) {\n return templatePath;\n }\n }\n\n throw new Error(\n 'Template directory not found. Please ensure templates are properly installed.',\n );\n}\n\nconst TEMPLATE_PATH = getTemplatePath();\n\n/**\n * Template metadata interface\n */\ninterface TemplateMetadata {\n name: string;\n displayName: string;\n description: string;\n tags: string[];\n defaultProjectName: string;\n examples?: {\n curlCommand?: string;\n inputExample?: any;\n outputExample?: any;\n };\n features?: string[];\n requirements?: {\n node?: string;\n dependencies?: string[];\n apiKeys?: string[];\n optionalApiKeys?: string[];\n };\n}\n\n/**\n * Template info including directory name and metadata\n */\ninterface TemplateInfo {\n directory: string;\n metadata: TemplateMetadata;\n}\n\n/**\n * Load metadata for a template\n */\nfunction loadTemplateMetadata(\n templateDir: string,\n basePath: string,\n): TemplateMetadata | null {\n const metadataPath = path.join(basePath, templateDir, 'metadata.json');\n if (fs.existsSync(metadataPath)) {\n try {\n return JSON.parse(fs.readFileSync(metadataPath, 'utf-8'));\n } catch (err) {\n ui.print(`Failed to parse metadata for ${templateDir}: ${err}`);\n }\n }\n // Return default metadata if file doesn't exist\n return {\n name: templateDir,\n displayName: templateDir\n .replace(/_/g, ' ')\n .replace(/\\b\\w/g, (c) => c.toUpperCase()),\n description: `${templateDir} template`,\n tags: [],\n defaultProjectName: templateDir,\n };\n}\n\n/**\n * Get available templates with their metadata\n */\nfunction getAvailableTemplatesWithMetadata(): TemplateInfo[] {\n const templates: TemplateInfo[] = [];\n\n try {\n const entries = fs.readdirSync(TEMPLATE_PATH, { withFileTypes: true });\n const templateDirs = entries\n .filter((entry) => entry.isDirectory())\n .filter((dir) => {\n // Check if the directory contains a graph.ts file\n const graphPath = path.join(TEMPLATE_PATH, dir.name, 'graph.ts');\n return fs.existsSync(graphPath);\n });\n\n for (const dir of templateDirs) {\n const metadata = loadTemplateMetadata(dir.name, TEMPLATE_PATH);\n if (metadata) {\n templates.push({\n directory: dir.name,\n metadata,\n });\n }\n }\n } catch (_err) {\n // Continue to next path if there's an error\n }\n return templates;\n}\n\n/**\n * Ask user to confirm npm install\n */\nasync function promptNpmInstall(): Promise<boolean> {\n return confirm({\n message: '\\n\uD83D\uDCE6 Would you like to install dependencies now? (y/n) ',\n defaultValue: false,\n });\n}\n\n/**\n * Run npm install in a directory\n */\nasync function runNpmInstall(directory: string): Promise<void> {\n const { spawn } = await import('child_process');\n\n return new Promise((resolve, reject) => {\n console.log();\n ui.print('\uD83D\uDCE6 Installing dependencies...');\n console.log();\n\n const install = spawn('npm', ['install'], {\n cwd: directory,\n stdio: 'inherit',\n shell: true,\n });\n\n install.on('close', (code) => {\n if (code === 0) {\n console.log();\n ui.success('\u2705 Dependencies installed successfully!');\n resolve();\n } else {\n console.log();\n ui.printError(`\u274C npm install failed with code ${code}`);\n reject(new Error(`npm install failed with code ${code}`));\n }\n });\n\n install.on('error', (err) => {\n console.log();\n ui.printError(`\u274C Failed to run npm install: ${err.message}`);\n reject(err);\n });\n });\n}\n\n/**\n * Process and enhance the package.json for initialization\n */\nfunction createPackageJson(graphFileName: string): any {\n const packageJson = {\n name: 'inworld-graph-project',\n version: '1.0.0',\n description: 'Inworld Runtime Graph Project',\n main: graphFileName,\n scripts: {\n start: `npx inworld serve ${graphFileName}`,\n run: `npx inworld run ${graphFileName}`,\n },\n dependencies: {\n '@inworld/runtime': RUNTIME_VERSION,\n },\n keywords: ['inworld', 'ai', 'graph', 'runtime'],\n author: '',\n license: 'MIT',\n };\n\n return packageJson;\n}\n\n/**\n * Get the graph template content from the templates folder\n */\nfunction createGraphTemplate(templateName: string): string {\n const availableTemplates = getAvailableTemplatesWithMetadata();\n\n if (\n !availableTemplates.find((template) => template.directory === templateName)\n ) {\n throw new Error(\n `Unknown template: ${templateName}. Available templates: ${availableTemplates\n .map((template) => template.directory)\n .join(', ')}`,\n );\n }\n\n const templateFilePath = path.join(TEMPLATE_PATH, templateName, 'graph.ts');\n\n if (!fs.existsSync(templateFilePath)) {\n throw new Error(\n `Template file not found: ${templateName}/graph.ts. Please ensure the template files are in the templates folder.`,\n );\n }\n\n return fs.readFileSync(templateFilePath, 'utf-8');\n}\n\n/**\n * Get README content for the selected template\n */\nfunction createReadme(templateName: string, graphFileName: string): string {\n const readmePath = path.join(TEMPLATE_PATH, templateName, 'README.md');\n\n if (!fs.existsSync(readmePath)) {\n ui.printError(`README file not found: ${readmePath}`);\n process.exit(1);\n }\n\n const readmeContent = fs.readFileSync(readmePath, 'utf-8');\n\n // Replace placeholders in the README\n return readmeContent.replace(/\\{\\{graphFileName\\}\\}/g, graphFileName);\n}\n\n// The actual init action handler\nconst initAction = async (options: {\n name?: string;\n template?: string;\n skipPackageJson?: boolean;\n skipReadme?: boolean;\n listTemplates?: boolean;\n skipInstall?: boolean;\n}) => {\n try {\n // Handle list templates flag\n if (options.listTemplates) {\n const templates = getAvailableTemplatesWithMetadata();\n console.log();\n ui.printHeader('\uD83D\uDCDA Available templates:');\n console.log();\n\n for (const template of templates) {\n ui.printListItem(`${chalk.cyan.bold(template.metadata.name)}`);\n ui.printListItem(` ${template.metadata.description}`);\n if (template.metadata.tags && template.metadata.tags.length > 0) {\n ui.printListItem(` Tags: ${template.metadata.tags.join(', ')}`);\n }\n if (template.metadata.requirements?.apiKeys) {\n ui.printListItem(\n ` Required API Keys: ${template.metadata.requirements.apiKeys.join(', ')}`,\n );\n }\n console.log();\n }\n\n ui.print(\n `Use ${chalk.bold('inworld graph init')} to interactively select a template.`,\n );\n console.log();\n return;\n }\n\n // Get available templates with metadata\n const templates = getAvailableTemplatesWithMetadata();\n\n if (templates.length === 0) {\n ui.printError(\n '\u274C No templates found. Please ensure templates are properly installed.',\n );\n process.exit(1);\n }\n\n let selectedTemplate: TemplateInfo | null = null;\n let projectName: string;\n\n // Interactive mode if no template specified\n if (!options.template) {\n console.log();\n ui.printHeader('\uD83D\uDE80 Welcome to Inworld Graph Project Initializer!');\n console.log();\n\n // Select template using the selector\n selectedTemplate = await selectItem({\n items: templates,\n getDisplayName: (item) =>\n `${item.metadata.name} - ${item.metadata.description}`,\n getIdentifier: (item) => item.directory,\n prompt: 'Select a template (enter number or id):',\n title: '\uD83D\uDCCB Available Templates:',\n noItemsMessage: 'No templates found.',\n invalidSelectionMessage: 'Invalid selection. Please try again.',\n });\n\n if (!selectedTemplate) {\n console.log();\n ui.print('\u26A0\uFE0F No template selected. Exiting.');\n return;\n }\n } else {\n // Find template by directory name if specified\n selectedTemplate =\n templates.find((t) => t.directory === options.template) || null;\n\n if (!selectedTemplate) {\n ui.printError(`\u274C Template not found: ${options.template}`);\n ui.print(\n `Available templates: ${templates.map((t) => t.directory).join(', ')}`,\n );\n process.exit(1);\n }\n }\n\n // Determine project name\n projectName =\n options.name ||\n selectedTemplate.metadata.defaultProjectName ||\n selectedTemplate.directory;\n\n // If in interactive mode and no name specified, ask for project name\n if (!options.template && !options.name) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const askProjectName = (): Promise<string> =>\n new Promise((resolve) => {\n rl.question(\n `\\nProject name (${selectedTemplate!.metadata.defaultProjectName}): `,\n (answer) => {\n rl.close();\n resolve(\n answer.trim() || selectedTemplate!.metadata.defaultProjectName,\n );\n },\n );\n });\n\n projectName = await askProjectName();\n }\n\n const currentDir = process.cwd();\n const projectDir = path.join(currentDir, projectName);\n\n // Check if project directory already exists\n if (fs.existsSync(projectDir)) {\n console.log();\n ui.print(`\u26A0\uFE0F Directory '${projectName}' already exists.`);\n\n // In interactive mode, ask for confirmation\n if (!options.template) {\n const confirmOverwrite = await confirm({\n message: 'Do you want to overwrite it? (y/n) ',\n defaultValue: false,\n });\n\n if (!confirmOverwrite) {\n ui.print('\u26A0\uFE0F Initialization cancelled.');\n return;\n }\n\n // Remove existing directory\n fs.rmSync(projectDir, { recursive: true, force: true });\n } else {\n ui.print('Overwriting existing directory...');\n fs.rmSync(projectDir, { recursive: true, force: true });\n }\n }\n\n // Create project directory\n fs.mkdirSync(projectDir, { recursive: true });\n\n const graphFileName = 'graph.ts';\n const graphFilePath = path.join(projectDir, graphFileName);\n const packageJsonPath = path.join(projectDir, 'package.json');\n const readmePath = path.join(projectDir, 'README.md');\n\n console.log();\n ui.printHeader(`\uD83D\uDE80 Initializing Inworld graph project: ${projectName}`);\n ui.print(`\uD83D\uDCC2 Creating project in: ${projectDir}`);\n ui.print(`\uD83D\uDCCB Using template: ${selectedTemplate.metadata.displayName}`);\n console.log();\n\n // Create the graph file using the selected template\n ui.print('\uD83D\uDCDD Creating graph file...');\n const graphContent = createGraphTemplate(selectedTemplate.directory);\n fs.writeFileSync(graphFilePath, graphContent, 'utf-8');\n\n // Create package.json if not skipped\n if (!options.skipPackageJson) {\n ui.print('\uD83D\uDCE6 Creating package.json...');\n const packageJson = createPackageJson(graphFileName);\n packageJson.name = projectName; // Update project name\n fs.writeFileSync(\n packageJsonPath,\n JSON.stringify(packageJson, null, 2),\n 'utf-8',\n );\n }\n\n // Create README if not skipped\n if (!options.skipReadme) {\n ui.print('\uD83D\uDCDA Creating README.md...');\n const readmeContent = createReadme(\n selectedTemplate.directory,\n graphFileName,\n );\n fs.writeFileSync(readmePath, readmeContent, 'utf-8');\n }\n\n // Display template-specific information\n if (selectedTemplate.metadata.requirements?.apiKeys) {\n console.log();\n ui.print('\u26A0\uFE0F This template requires the following API keys:');\n for (const key of selectedTemplate.metadata.requirements.apiKeys) {\n ui.print(` \u2022 ${key}`);\n }\n }\n\n if (selectedTemplate.metadata.examples?.curlCommand) {\n console.log();\n ui.printHeader('\uD83D\uDCDD Example usage:');\n ui.print(` ${selectedTemplate.metadata.examples.curlCommand}`);\n }\n\n console.log();\n ui.success('\u2705 Inworld graph project initialized successfully!');\n\n // Ask about npm install if not skipped\n if (!options.skipInstall && !options.skipPackageJson) {\n const shouldInstall = await promptNpmInstall();\n if (shouldInstall) {\n try {\n await runNpmInstall(projectDir);\n } catch (_err) {\n console.log();\n ui.print('\u26A0\uFE0F You can install dependencies manually by running:');\n ui.print(` cd ${projectName} && npm install`);\n }\n }\n }\n\n console.log();\n ui.printHeader('\uD83D\uDCCC Next steps:');\n ui.print(` 1. ${chalk.bold(`cd ${projectName}`)}`);\n if (!options.skipInstall) {\n ui.print(` 2. ${chalk.bold('npm install')} (if not already done)`);\n ui.print(\n ` 3. ${chalk.bold('npm start')} or ${chalk.bold('npx inworld serve graph.ts')}`,\n );\n } else {\n ui.print(\n ` 2. ${chalk.bold('npm start')} or ${chalk.bold('npx inworld serve graph.ts')}`,\n );\n }\n\n if (selectedTemplate.metadata.requirements?.apiKeys) {\n console.log();\n ui.print('\uD83D\uDCA1 Remember to set your API keys before running!');\n }\n } catch (error) {\n ui.printError('\u274C Error initializing project:');\n console.error(error);\n process.exit(1);\n }\n};\n\n// Create the init subcommand\nconst makeInitCommand = (description: string) => {\n const availableTemplates = getAvailableTemplatesWithMetadata();\n\n return new Command('init')\n .description(description)\n .option('-n, --name <name>', 'Name of the project directory')\n .option(\n '-t, --template <template>',\n `Template to use: ${availableTemplates.map((t) => `\"${t.directory}\"`).join(' or ')}`,\n )\n .option('-l, --list-templates', 'List all available templates')\n .option('--skip-package-json', 'Skip creating package.json file')\n .option('--skip-readme', 'Skip creating README.md file')\n .option('--skip-install', 'Skip npm install prompt')\n .action(initAction);\n};\n\nexport const initCommand = makeInitCommand(\n 'Initialize a new Inworld graph project (interactive if no options provided)',\n);\n\nexport const initCommandAlias = makeInitCommand(\n `Alias for \"${chalk.bold('inworld graph init')}\"`,\n);\n", "// Import the necessary modules for the serve command\nimport chalk from 'chalk';\nimport { Command } from 'commander';\n\nimport { loadGraph } from '../../services/graph_loader';\n\n/**\n * User context attributes as key-value pairs.\n */\nexport interface UserContextAttributes {\n [key: string]: string;\n}\n\n/**\n * User context configuration.\n */\nexport interface UserContextInterface {\n /** User attributes as key-value pairs. */\n attributes: UserContextAttributes;\n /** Targeting key for user identification. */\n targetingKey: string;\n}\n\nexport interface ExecutionContext {\n executionId?: string;\n userContext?: UserContextInterface;\n dataStoreContent?: Record<string, any>;\n}\n\n// The actual run action handler\nconst runAction = async (file: string, request: string) => {\n try {\n const { graph } = await loadGraph(file);\n\n let requestJson;\n try {\n requestJson = JSON.parse(request);\n } catch (error) {\n console.error('Error parsing request:', error);\n process.exit(1);\n }\n\n const results = await graph.executeJsonRequest(requestJson);\n\n for await (const result of results) {\n console.log(result);\n }\n } catch (error) {\n console.error('Error starting server:', error);\n }\n};\n\nconst makeRunCommand = (description: string) => {\n return new Command('run')\n .description(description)\n .argument('<file>', 'Path to the graph file (e.g., test.ts)')\n .argument(\n '<request>',\n `\nGraph input, heavily depends on the exact graph. E.g.:\n\n{\"input\": \"Hello\"}\n\nAlso acceptes execution id, user context and data store content:\n\n'{\n \"input\": {\"my_complicated_input_object\": \"not really\"},\n \"executionId\": \"123e4567-e89b-12d3-a456-426614174000\",\n \"userContext\": {\"targetingKey\": \"id\", \"attributes\": {}},\n \"dataStoreContent\": {}\n}'\n\nMirrors the input format of the Inworld HTTP Graph Server.\n`,\n )\n .action(runAction);\n};\n// Create the run subcommand for graph\nexport const runCommand = makeRunCommand(\n 'Runs single execution against provided Inworld graph. Uses same input and output protocol as http server.',\n);\n\nexport const runCommandAlias = makeRunCommand(\n `Alias for \"${chalk.bold('inworld graph run')}\"`,\n);\n", "// Import the necessary modules for the serve command\nimport chalk from 'chalk';\nimport { Command } from 'commander';\n\nimport { loadGraph } from '../../services/graph_loader';\nimport * as ui from '../../utils/ui';\n\n// The actual serve action handler\nconst serveAction = async (\n file: string,\n options: {\n port: string;\n host: string;\n transport: string;\n swagger: boolean;\n },\n) => {\n try {\n const { graph } = await loadGraph(file);\n const port = parseInt(options.port, 10);\n const host = options.host;\n\n if (!['http', 'grpc'].includes(options.transport)) {\n ui.printError('Transport must be either \"http\" or \"grpc\"');\n process.exit(1);\n }\n\n await graph.serve({\n host,\n port,\n transport: options.transport,\n swagger: options.swagger,\n });\n } catch (error) {\n ui.printError('Error starting server:');\n console.error(error);\n process.exit(1);\n }\n};\n\n// Create the serve subcommand for graph\nconst makeServeCommand = (description: string) => {\n return new Command('serve')\n .description(description)\n .argument('<file>', 'Path to the graph file (e.g., test.ts)')\n .option('-p, --port <port>', 'Port to run the server on', '3000')\n .option('--host <host>', 'Host to bind the server to', 'localhost')\n .option(\n '-t, --transport <transport>',\n 'Transport protocol (http or grpc)',\n 'http',\n )\n .option(\n '--swagger',\n 'Enable Swagger UI documentation (HTTP transport only)',\n false,\n )\n .action(serveAction);\n};\n\nexport const serveCommand = makeServeCommand(\n 'Start a server that wraps an Inworld Runtime graph',\n);\n\nexport const serveCommandAlias = makeServeCommand(\n `Alias for \"${chalk.bold('inworld graph serve')}\"`,\n);\n", "import { Command } from 'commander';\n\nimport { deployCommand } from './graph/graph_deploy_command';\nimport { initCommand } from './graph/graph_init_command';\nimport { runCommand } from './graph/graph_run_command';\nimport { serveCommand } from './graph/graph_serve_command';\nimport { graphVariantCommand } from './graph/graph_variant_command';\nimport { visualizeCommand } from './graph/graph_visualize_command';\n\n// Create the graph parent command\nexport const graphCommand = new Command('graph')\n .description('Manage Inworld graph projects')\n .addCommand(initCommand)\n .addCommand(serveCommand)\n .addCommand(runCommand)\n .addCommand(deployCommand)\n .addCommand(visualizeCommand)\n .addCommand(graphVariantCommand)\n .action(() => {\n graphCommand.help();\n });\n", "import { Command } from 'commander';\n\nimport { graphListVariantsCommand } from './variant/graph_variant_list_command';\nimport { graphVariantPrintCommand } from './variant/graph_variant_print_command';\nimport { graphVariantRegisterCommand } from './variant/graph_variant_register_command';\n\nexport const graphVariantCommand = new Command('variant')\n .description('Manage Inworld graph variants')\n .addCommand(graphListVariantsCommand)\n .addCommand(graphVariantRegisterCommand)\n .addCommand(graphVariantPrintCommand)\n .action(() => {\n graphVariantCommand.help();\n });\n", "import { Command } from 'commander';\n\nimport { requireWorkspace } from '../../../auth/utils';\nimport { loadGraph } from '../../../services/graph_loader';\nimport { listGraphVariants } from '../../../services/graph_variant_service';\nimport * as ui from '../../../utils/ui';\n\nconst listVariantsAction = async (file: string) => {\n const workspaceId = await requireWorkspace();\n\n const { graph } = await loadGraph(file);\n const variants = await listGraphVariants(graph.graphId);\n if (!variants || variants.graphVariants?.length === 0) {\n console.log();\n ui.print(\n `No registered variants of the graph \"${graph.graphId}\" found in workspace \"${workspaceId}\"`,\n );\n return;\n }\n\n console.log();\n ui.printHeader(\n `Registered variants of the graph \"${graph.graphId}\" in workspace \"${workspaceId}\":`,\n );\n variants.graphVariants?.forEach((variant) => {\n ui.printListItem(`${variant.name} - ${variant.displayName}`);\n });\n};\n\nexport const graphListVariantsCommand = new Command('list')\n .description('List all registered variants of the graph.')\n .argument('<file>', 'Path to the graph file (e.g., graph.ts)')\n .action(listVariantsAction);\n", "import { GraphsService } from '../../proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb';\nimport { authenticatedInworldRequest, requireWorkspace } from '../auth/utils';\nimport { checkLRO } from '../utils/long_running_operations';\nimport {\n getGraphResourceName,\n getGraphVariantResourceName,\n} from '../utils/resource_name_helper';\nimport { ensureGraphRegistered } from './deploy_service';\n\nexport const listGraphVariants = async (graphId: string) => {\n const workspaceId = await requireWorkspace();\n const graphResourceName = getGraphResourceName(workspaceId, graphId);\n return await authenticatedInworldRequest(GraphsService.ListGraphVariants, {\n parent: graphResourceName,\n });\n};\n\n/**\n * Converts the input string to a string containing only alphanumeric characters,\n * dashes, and underscores. Spaces are replaced with underscores, all other\n * non-alphanumeric/dash/underscore characters are removed, and the result is lowercased.\n *\n * @param input - The string to sanitize.\n * @returns The sanitized, lowercased string containing only [a-z0-9-_], with spaces replaced by underscores.\n */\nexport function toAlphanumericDashUnderscore(input: string): string {\n return input\n .replace(/\\s+/g, '_') // Replace spaces with underscores\n .replace(/[^a-zA-Z0-9-_]/g, '') // Remove all non-alphanumeric, non-dash, non-underscore\n .toLowerCase(); // Convert to lowercase\n}\n\nexport const registerGraphVariant = async (\n graphId: string,\n variantDisplayName: string,\n variantConfig: string,\n force: boolean = false,\n) => {\n const request = force\n ? GraphsService.UpdateGraphVariant\n : GraphsService.CreateGraphVariant;\n\n const workspaceId = await requireWorkspace();\n const graphResourceName = getGraphResourceName(workspaceId, graphId);\n const variantResourceName = getGraphVariantResourceName(\n workspaceId,\n graphId,\n toAlphanumericDashUnderscore(variantDisplayName),\n );\n\n await ensureGraphRegistered(workspaceId, graphId);\n\n try {\n const operation = await authenticatedInworldRequest(request, {\n parent: graphResourceName,\n graphVariant: {\n config: {\n rawContent: variantConfig,\n },\n displayName: variantDisplayName,\n name: variantResourceName,\n graph: graphResourceName,\n },\n });\n\n await checkLRO({ operationName: operation.name });\n\n const graph = await ensureGraphRegistered(workspaceId, graphId);\n if (graph && graph.targeting?.rawContent === '{}') {\n console.log(\n `Graph \"${graphId}\" has no targeting, setting up registered variant as default...`,\n );\n // graph has no targeting, so we need to setup registered variant as default.\n const operation = await authenticatedInworldRequest(\n GraphsService.UpdateGraph,\n {\n graph: {\n ...graph,\n targeting: { rawContent: `{\"if\": [\"${variantResourceName}\"]}` },\n },\n },\n );\n await checkLRO({ operationName: operation.name });\n }\n } catch (error) {\n return error;\n }\n return true;\n};\n", "import { Command } from 'commander';\nimport path from 'path';\n\nimport { loadGraph } from '../../../services/graph_loader';\nimport * as ui from '../../../utils/ui';\n\n/**\n * Handler for the to_json action.\n * Loads a graph and converts it to JSON format.\n *\n * @param file - Path to the graph file\n * @param options - Command options\n */\nconst graphVariantPrintAction = async (\n file: string,\n options: {\n output?: string;\n },\n) => {\n try {\n const { graph } = await loadGraph(file);\n\n // Call toJson on the graph object\n const jsonResult: string = await graph.toJSON();\n\n // Output the JSON\n if (options.output) {\n // If output file is specified, write to file\n const outputPath = path.resolve(options.output);\n\n const fs = await import('fs/promises');\n await fs.writeFile(options.output, jsonResult);\n ui.success(`JSON saved to ${outputPath}`);\n } else {\n // Otherwise, output to console\n console.log(jsonResult);\n }\n } catch (error) {\n ui.printError('Error converting graph to JSON:');\n console.error(error);\n process.exit(1);\n }\n};\n\n/**\n * Command for converting an Inworld Runtime graph to JSON format.\n * Serializes the graph structure and configuration to JSON.\n */\nexport const graphVariantPrintCommand = new Command('print')\n .description('Print JSON representation of the graph variant')\n .argument('<file>', 'Path to the graph file (e.g., test.ts)')\n .option(\n '-o, --output <file>',\n 'Output file path (if not specified, outputs to console)',\n )\n .action(graphVariantPrintAction);\n", "import chalk from 'chalk';\nimport { Command } from 'commander';\n\nimport { requireWorkspace } from '../../../auth/utils';\nimport { PLATFORM_URL } from '../../../constants';\nimport { isGrpcError } from '../../../grpc/core/InworldError';\nimport { GrpcStatusCode } from '../../../grpc/core/statusCodes';\nimport { loadGraph } from '../../../services/graph_loader';\nimport { registerGraphVariant } from '../../../services/graph_variant_service';\nimport { getGraphResourceName } from '../../../utils/resource_name_helper';\nimport * as ui from '../../../utils/ui';\n\nconst registerVariantsAction = async (\n file: string,\n options: { displayName: string; force: boolean },\n) => {\n const workspaceId = await requireWorkspace();\n\n const { graph } = await loadGraph(file);\n let response = await registerGraphVariant(\n graph.graphId,\n options.displayName,\n graph.toJSON(),\n );\n\n if (\n response !== true &&\n isGrpcError(response) &&\n response.code === GrpcStatusCode.ALREADY_EXISTS\n ) {\n if (options.force) {\n response = await registerGraphVariant(\n graph.graphId,\n options.displayName,\n graph.toJSON(),\n true,\n );\n }\n }\n\n if (response === true) {\n const uri = `${PLATFORM_URL}/v2/${getGraphResourceName(workspaceId, graph.graphId)}/targeting`;\n\n console.log();\n ui.success(\n `Variant \"${options.displayName}\" ${options.force ? 'updated' : 'registered'} successfully`,\n );\n console.log();\n ui.print(\n `Now you can open ${chalk.cyan.underline(uri)} and setup targeting for different variants`,\n );\n } else {\n if (\n isGrpcError(response) &&\n response.code === GrpcStatusCode.ALREADY_EXISTS\n ) {\n console.log();\n ui.printError(\n `Variant \"${options.displayName}\" already registered for graph \"${graph.graphId}\" in workspace \"${workspaceId}\", use --force option to update it`,\n );\n } else {\n ui.printError(`Failed to register variant \"${options.displayName}\"`);\n }\n }\n};\n\nexport const graphVariantRegisterCommand = new Command('register')\n .description('List all registered variants of the graph.')\n .argument('<file>', 'Path to the graph file (e.g., graph.ts)')\n .requiredOption(\n '-d, --display-name <variantDisplayName>',\n 'The display name of the variant',\n )\n .option('-f, --force', 'Updates the variant if it already exists', false)\n .action(registerVariantsAction);\n", "import { Command } from 'commander';\nimport path from 'path';\n\nimport { loadGraph } from '../../services/graph_loader';\nimport * as ui from '../../utils/ui';\n\n/**\n * Handler for the visualize action.\n * Loads a graph and generates its visualization.\n *\n * @param file - Path to the graph file\n * @param options - Command options\n */\nconst visualizeAction = async (file: string, options: { output: string }) => {\n try {\n const { graph } = await loadGraph(file);\n\n const outputPath = path.resolve(options.output);\n\n ui.print(`Storing graph visualization to ${outputPath}`);\n // Call visualize on the graph object\n await graph.visualize(outputPath);\n } catch (error) {\n ui.printError('Error visualizing graph:');\n console.error(error);\n process.exit(1);\n }\n};\n\n/**\n * Command for visualizing an Inworld Runtime graph.\n * Generates a visual representation of the graph structure.\n */\nexport const visualizeCommand = new Command('visualize')\n .description('Generate a visualization of an Inworld Runtime graph')\n .argument('<file>', 'Path to the graph file (e.g., test.ts)')\n .option(\n '-o, --output <file>',\n 'Output file path (if not specified, outputs to graph.png in current directory)',\n './graph.png',\n )\n .action(visualizeAction);\n", "import chalk from 'chalk';\nimport { Command } from 'commander';\nimport { writeFile } from 'fs/promises';\nimport { resolve } from 'path';\n\nimport {\n type StreamingMetrics,\n TTSModel,\n ttsService,\n} from '../services/tts_service.js';\n\n/**\n * Helper function to wrap text to a specific width\n */\nfunction wrapText(text: string, maxWidth: number): string[] {\n const words = text.split(' ');\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= maxWidth) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n if (currentLine) lines.push(currentLine);\n currentLine = word;\n }\n }\n if (currentLine) lines.push(currentLine);\n\n return lines;\n}\n\n/**\n * List voices command\n * Displays all available TTS voices in a formatted output\n */\nexport const listVoicesCommand = new Command('list-voices')\n .description('List all available voices from the workspace')\n .option('-f, --filter <filter>', 'Filter voices (e.g., \"language=en\")')\n .option('-j, --json', 'Output as JSON')\n .option('-c, --compact', 'Compact output (voice IDs only)')\n .action(async (options) => {\n try {\n const response = await ttsService.listVoices(options.filter);\n\n if (options.json) {\n console.log(JSON.stringify(response, null, 2));\n process.exit(0);\n return;\n }\n\n if (!response.voices || response.voices.length === 0) {\n console.log(chalk.yellow('\u26A0\uFE0F No voices found'));\n process.exit(0);\n return;\n }\n\n // Compact mode - just list voice IDs\n if (options.compact) {\n console.log('\\n' + chalk.bold.green('\uD83C\uDFA4 Available Voice IDs:'));\n console.log(chalk.gray('\u2500'.repeat(50)));\n response.voices\n .sort((a, b) => a.voiceId.localeCompare(b.voiceId))\n .forEach((voice) => {\n console.log(` ${chalk.cyan('\u2022')} ${voice.voiceId}`);\n });\n console.log();\n process.exit(0);\n return;\n }\n\n // Group voices by language for better organization\n const voicesByLanguage = new Map<string, typeof response.voices>();\n\n response.voices.forEach((voice) => {\n const languages = voice.languages || [];\n const primaryLang = languages[0] || 'unknown';\n\n if (!voicesByLanguage.has(primaryLang)) {\n voicesByLanguage.set(primaryLang, []);\n }\n voicesByLanguage.get(primaryLang)!.push(voice);\n });\n\n // Sort languages alphabetically\n const sortedLanguages = Array.from(voicesByLanguage.keys()).sort();\n\n // Header\n console.log('\\n' + chalk.bold.green('Available TTS Voices'));\n console.log(\n chalk.gray(\n `Found ${response.voices.length} voices across ${sortedLanguages.length} languages`,\n ),\n );\n console.log(chalk.gray('\u2500'.repeat(80)));\n\n // Display voices grouped by language\n sortedLanguages.forEach((lang, langIndex) => {\n const voices = voicesByLanguage.get(lang)!;\n\n // Language header with emoji flags for common languages\n const languageFlags: Record<string, string> = {\n en: '\uD83C\uDDEC\uD83C\uDDE7',\n es: '\uD83C\uDDEA\uD83C\uDDF8',\n fr: '\uD83C\uDDEB\uD83C\uDDF7',\n de: '\uD83C\uDDE9\uD83C\uDDEA',\n it: '\uD83C\uDDEE\uD83C\uDDF9',\n pt: '\uD83C\uDDF5\uD83C\uDDF9',\n nl: '\uD83C\uDDF3\uD83C\uDDF1',\n pl: '\uD83C\uDDF5\uD83C\uDDF1',\n ru: '\uD83C\uDDF7\uD83C\uDDFA',\n ja: '\uD83C\uDDEF\uD83C\uDDF5',\n ko: '\uD83C\uDDF0\uD83C\uDDF7',\n zh: '\uD83C\uDDE8\uD83C\uDDF3',\n };\n\n const flag = languageFlags[lang] || '\uD83C\uDF10';\n console.log(\n `\\n${flag} ${chalk.bold.yellow(lang.toUpperCase())} ${chalk.gray(`(${voices.length} voices)`)}`,\n );\n console.log(chalk.gray('\u2500'.repeat(80)));\n\n // Display voices for this language\n voices\n .sort((a, b) => a.voiceId.localeCompare(b.voiceId))\n .forEach((voice) => {\n // Voice ID and Display Name\n const displayName =\n voice.displayName && voice.displayName !== voice.voiceId\n ? chalk.gray(` (${voice.displayName})`)\n : '';\n console.log(\n ` ${chalk.cyan('\u25B8')} ${chalk.bold.white(voice.voiceId)}${displayName}`,\n );\n\n // Description (wrapped for readability)\n if (voice.description) {\n const maxWidth = 76;\n const descriptionLines = wrapText(voice.description, maxWidth);\n descriptionLines.forEach((line) => {\n console.log(` ${chalk.gray(line)}`);\n });\n }\n });\n\n // Add spacing between language groups except for the last one\n if (langIndex < sortedLanguages.length - 1) {\n console.log();\n }\n });\n\n // Footer with tips\n console.log('\\n' + chalk.gray('\u2500'.repeat(80)));\n console.log(chalk.gray('Tips:'));\n console.log(\n chalk.gray(' \u2022 Use --filter \"language=<code>\" to filter by language'),\n );\n console.log(\n chalk.gray(' \u2022 Use --compact for a simple list of voice IDs'),\n );\n console.log(chalk.gray(' \u2022 Use --json for machine-readable output'));\n console.log(\n chalk.gray('\\nExample: inworld tts list-voices --filter \"language=en\"'),\n );\n console.log();\n } catch (error) {\n console.error(chalk.red('\u274C Error listing voices:'), error);\n process.exit(1);\n }\n\n process.exit(0);\n });\n\n/**\n * Synthesize speech command\n * Converts text to speech using specified voice and settings\n */\nexport const synthesizeCommand = new Command('synthesize')\n .description('Synthesize text to speech')\n .argument('<text>', 'Text to synthesize (max 2000 characters)')\n .requiredOption(\n '-v, --voice <voiceId>',\n 'Voice ID to use for synthesis',\n 'Dennis',\n )\n .option('-o, --output <file>', 'Output audio file path (default: output.mp3)')\n .option(\n '-m, --model <model>',\n 'TTS model to use (inworld-tts-1 or inworld-tts-1-max)',\n 'inworld-tts-1',\n )\n .option(\n '-t, --temperature <temp>',\n 'Temperature (0.0-2.0, default: 1.1)',\n '1.1',\n )\n .option('--format <format>', 'Audio format (MP3, LINEAR16, OGG_OPUS)', 'MP3')\n .option('--timestamps <type>', 'Include timestamps (WORD or CHARACTER)')\n .option('-j, --json', 'Output response as JSON (includes base64 audio)')\n .option('--stats', 'Show request performance statistics')\n .option('--stream', 'Use streaming API for synthesis')\n .action(async (text, options) => {\n try {\n // Validate text length\n if (text.length > 2000) {\n console.error(chalk.red('\u274C Error: Text exceeds 2000 character limit'));\n console.log(chalk.gray(`Current length: ${text.length} characters`));\n process.exit(1);\n }\n\n // Parse temperature\n const temperature = parseFloat(options.temperature);\n if (isNaN(temperature) || temperature < 0 || temperature > 2) {\n console.error(\n chalk.red('\u274C Error: Temperature must be between 0.0 and 2.0'),\n );\n process.exit(1);\n }\n\n // Map model name\n const modelMap: Record<string, TTSModel> = {\n 'inworld-tts-1': TTSModel.INWORLD_TTS_1,\n 'inworld-tts-1-max': TTSModel.INWORLD_TTS_1_MAX,\n };\n const modelId = modelMap[options.model] || TTSModel.INWORLD_TTS_1_MAX;\n\n console.log(chalk.cyan('\uD83C\uDF99\uFE0F Synthesizing speech...'));\n console.log(chalk.gray(`Voice: ${options.voice}`));\n console.log(chalk.gray(`Model: ${options.model}`));\n console.log(chalk.gray(`Text length: ${text.length} characters`));\n\n // Build synthesis request\n const request: any = {\n text,\n voiceId: options.voice,\n modelId,\n temperature,\n };\n\n // Add audio config if format is specified\n if (options.format) {\n request.audioConfig = {\n audioEncoding: options.format,\n };\n }\n\n // Add timestamp type if specified\n if (options.timestamps) {\n request.timestampType = options.timestamps;\n }\n\n let response: any;\n let audioBuffer: Buffer | undefined;\n let fileExtension = '.mp3'; // Default extension\n\n // Use streaming or regular synthesis\n if (options.stream) {\n // Determine the best format for streaming\n let streamFormat = options.format || 'LINEAR16';\n fileExtension = '.wav'; // Update based on format\n // Handle different audio formats for streaming\n if (options.format === 'MP3') {\n console.log(\n chalk.yellow(\n '\u26A0\uFE0F Warning: MP3 streaming requires special handling.',\n ),\n );\n console.log(\n chalk.yellow(' Audio chunks may not concatenate perfectly.'),\n );\n console.log(\n chalk.yellow(\n ' Consider using LINEAR16 or OGG_OPUS for better streaming.',\n ),\n );\n fileExtension = '.mp3';\n } else if (options.format === 'OGG_OPUS') {\n // OGG_OPUS is designed for streaming and works well\n fileExtension = '.ogg';\n } else if (options.format === 'ALAW' || options.format === 'MULAW') {\n fileExtension = '.raw';\n } else if (!options.format || options.format === 'LINEAR16') {\n // Default to LINEAR16 for best streaming compatibility\n streamFormat = 'LINEAR16';\n fileExtension = '.wav';\n }\n\n console.log(chalk.cyan('\uD83D\uDD04 Using streaming synthesis...'));\n console.log(chalk.gray(`Format: ${streamFormat}${fileExtension}`));\n\n // Update request for streaming-compatible format\n const streamRequest = {\n ...request,\n audioConfig: {\n ...request.audioConfig,\n audioEncoding: streamFormat,\n },\n };\n\n // Collect audio chunks as buffers\n const audioChunks: Buffer[] = [];\n let timestampInfo: any = null;\n let streamError: any = null;\n let chunkCount = 0;\n let isFirstChunk = true;\n\n // For accumulating timestamps across chunks\n const allWordAlignments: {\n words: string[];\n wordStartTimeSeconds: number[];\n wordEndTimeSeconds: number[];\n } = {\n words: [],\n wordStartTimeSeconds: [],\n wordEndTimeSeconds: [],\n };\n\n const allCharacterAlignments: {\n characters: string[];\n characterStartTimeSeconds: number[];\n characterEndTimeSeconds: number[];\n } = {\n characters: [],\n characterStartTimeSeconds: [],\n characterEndTimeSeconds: [],\n };\n\n // Stream with metrics tracking\n const streamResult = await ttsService.synthesizeSpeechStream(\n streamRequest,\n (chunk) => {\n chunkCount++;\n\n if (chunk.error) {\n streamError = chunk.error;\n console.error(\n chalk.red(`\u274C Stream error: ${chunk.error.message}`),\n );\n } else {\n if (chunk.audioContent) {\n const chunkBuffer = Buffer.from(chunk.audioContent, 'base64');\n\n // Handle different formats for streaming\n if (streamFormat === 'LINEAR16') {\n // For LINEAR16/WAV format, each chunk has a WAV header\n // We need to strip the header from subsequent chunks\n if (!isFirstChunk) {\n // WAV header is typically 44 bytes\n const headerSize = 44;\n if (chunkBuffer.length > headerSize) {\n // Skip the WAV header in subsequent chunks\n audioChunks.push(chunkBuffer.slice(headerSize));\n }\n } else {\n audioChunks.push(chunkBuffer);\n isFirstChunk = false;\n }\n } else if (streamFormat === 'OGG_OPUS') {\n // OGG_OPUS is container-based and designed for streaming\n // Can be concatenated directly\n audioChunks.push(chunkBuffer);\n } else if (streamFormat === 'MP3') {\n // MP3 chunks might have headers/metadata that don't concatenate well\n // but we'll try anyway with a warning\n audioChunks.push(chunkBuffer);\n } else {\n // For other formats (ALAW, MULAW), just concatenate\n audioChunks.push(chunkBuffer);\n }\n\n if (!options.json && !options.stats) {\n // Show progress with chunk size\n const chunkSizeKB = (chunkBuffer.length / 1024).toFixed(2);\n process.stdout.write(\n chalk.gray(\n `\\rReceived chunk ${chunkCount} (${chunkSizeKB} KB)...`,\n ),\n );\n }\n }\n if (chunk.timestampInfo) {\n // Accumulate word alignments\n if (chunk.timestampInfo.wordAlignment) {\n const wa = chunk.timestampInfo.wordAlignment;\n allWordAlignments.words.push(...(wa.words || []));\n allWordAlignments.wordStartTimeSeconds.push(\n ...(wa.wordStartTimeSeconds || []),\n );\n allWordAlignments.wordEndTimeSeconds.push(\n ...(wa.wordEndTimeSeconds || []),\n );\n }\n\n // Accumulate character alignments\n if (chunk.timestampInfo.characterAlignment) {\n const ca = chunk.timestampInfo.characterAlignment;\n allCharacterAlignments.characters.push(\n ...(ca.characters || []),\n );\n allCharacterAlignments.characterStartTimeSeconds.push(\n ...(ca.characterStartTimeSeconds || []),\n );\n allCharacterAlignments.characterEndTimeSeconds.push(\n ...(ca.characterEndTimeSeconds || []),\n );\n }\n }\n }\n },\n options.stats, // trackMetrics\n );\n\n if (!options.json && !options.stats && chunkCount > 0) {\n process.stdout.write('\\r' + ' '.repeat(50) + '\\r'); // Clear progress line\n }\n\n if (streamError) {\n throw new Error(`Stream error: ${streamError.message}`);\n }\n\n // Combine audio chunks\n audioBuffer = Buffer.concat(audioChunks);\n\n // Build combined timestamp info from all chunks\n if (\n allWordAlignments.words.length > 0 ||\n allCharacterAlignments.characters.length > 0\n ) {\n timestampInfo = {};\n\n if (allWordAlignments.words.length > 0) {\n timestampInfo.wordAlignment = {\n words: allWordAlignments.words,\n wordStartTimeSeconds: allWordAlignments.wordStartTimeSeconds,\n wordEndTimeSeconds: allWordAlignments.wordEndTimeSeconds,\n };\n }\n\n if (allCharacterAlignments.characters.length > 0) {\n timestampInfo.characterAlignment = {\n characters: allCharacterAlignments.characters,\n characterStartTimeSeconds:\n allCharacterAlignments.characterStartTimeSeconds,\n characterEndTimeSeconds:\n allCharacterAlignments.characterEndTimeSeconds,\n };\n }\n }\n\n // Create response object similar to non-streaming for consistency\n const combinedAudioBase64 = audioBuffer.toString('base64');\n response = {\n audioContent: combinedAudioBase64,\n timestampInfo,\n _metrics: streamResult._metrics,\n };\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n audioContent: combinedAudioBase64,\n timestampInfo,\n streamMetrics: streamResult._metrics,\n },\n null,\n 2,\n ),\n );\n } else {\n // Save audio file with appropriate extension\n const outputPath = resolve(\n options.output || `output${fileExtension}`,\n );\n await writeFile(outputPath, audioBuffer);\n\n console.log(chalk.green(`\u2705 Audio saved to: ${outputPath}`));\n console.log(\n chalk.gray(\n `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`,\n ),\n );\n console.log(chalk.gray(`Chunks received: ${chunkCount}`));\n\n // Show timestamp collection info if available\n if (allWordAlignments.words.length > 0) {\n console.log(\n chalk.gray(\n `Word timestamps collected: ${allWordAlignments.words.length}`,\n ),\n );\n }\n if (allCharacterAlignments.characters.length > 0) {\n console.log(\n chalk.gray(\n `Character timestamps collected: ${allCharacterAlignments.characters.length}`,\n ),\n );\n }\n }\n } else {\n // Regular synthesis (non-streaming)\n console.log(chalk.cyan('\uD83C\uDF99\uFE0F Synthesizing speech...'));\n console.log(chalk.gray(`Voice: ${options.voice}`));\n console.log(chalk.gray(`Model: ${options.model}`));\n console.log(chalk.gray(`Text length: ${text.length} characters`));\n console.log(chalk.gray(`Format: ${options.format || 'MP3 (default)'}`));\n\n // Set file extension based on format for non-streaming\n if (options.format === 'LINEAR16') {\n fileExtension = '.wav';\n } else if (options.format === 'OGG_OPUS') {\n fileExtension = '.ogg';\n } else if (options.format === 'ALAW' || options.format === 'MULAW') {\n fileExtension = '.raw';\n } else {\n fileExtension = '.mp3'; // Default to MP3\n }\n\n response = options.stats\n ? await ttsService.synthesizeSpeechWithMetrics(request)\n : await ttsService.synthesizeSpeech(request);\n\n audioBuffer = Buffer.from(response.audioContent, 'base64');\n\n if (options.json) {\n console.log(JSON.stringify(response, null, 2));\n } else {\n // Save audio file\n const outputPath = resolve(\n options.output || `output${fileExtension}`,\n );\n await writeFile(outputPath, audioBuffer);\n\n console.log(chalk.green(`\u2705 Audio saved to: ${outputPath}`));\n console.log(\n chalk.gray(\n `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`,\n ),\n );\n }\n }\n\n // Skip further processing if JSON output was requested\n if (options.json) {\n process.exit(0);\n return;\n }\n\n // Display performance statistics if requested\n if (options.stats && response._metrics) {\n const m = response._metrics;\n\n // Check if this is streaming metrics\n const isStreaming = 'timeToFirstChunk' in m;\n\n if (isStreaming) {\n // Display streaming-specific metrics\n const sm = m as StreamingMetrics;\n console.log(\n '\\n' + chalk.cyan('\uD83D\uDCCA Streaming Performance Statistics:'),\n );\n console.log(chalk.gray('\u2550'.repeat(50)));\n\n // Streaming Timeline\n console.log(chalk.bold.white('\\n Streaming Timeline:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n console.log(\n chalk.white(' \u23F1\uFE0F Time to First Chunk: ') +\n chalk.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`),\n );\n console.log(\n chalk.white(' \u23F2\uFE0F Total Stream Time: ') +\n chalk.bold.yellow(`${sm.totalTime.toFixed(0)} ms`),\n );\n\n // Chunk Statistics\n console.log(chalk.bold.white('\\n Chunk Statistics:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n console.log(\n chalk.white(' \uD83D\uDCE6 Chunks Received: ') +\n chalk.yellow(`${sm.chunksReceived}`),\n );\n\n if (sm.errorChunks > 0) {\n console.log(\n chalk.white(' \u26A0\uFE0F Error Chunks: ') +\n chalk.red(`${sm.errorChunks}`),\n );\n }\n\n // Calculate chunk statistics\n if (sm.chunkSizes.length > 0) {\n const avgChunkSize =\n sm.chunkSizes.reduce((a, b) => a + b, 0) / sm.chunkSizes.length;\n const minChunkSize = Math.min(...sm.chunkSizes);\n const maxChunkSize = Math.max(...sm.chunkSizes);\n\n console.log(\n chalk.white(' \uD83D\uDCCF Avg Chunk Size: ') +\n chalk.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`),\n );\n console.log(\n chalk.gray(' Min/Max: ') +\n chalk.gray(\n `${(minChunkSize / 1024).toFixed(2)} - ${(maxChunkSize / 1024).toFixed(2)} KB`,\n ),\n );\n }\n\n if (sm.chunkIntervals.length > 0) {\n const avgInterval =\n sm.chunkIntervals.reduce((a, b) => a + b, 0) /\n sm.chunkIntervals.length;\n const minInterval = Math.min(...sm.chunkIntervals);\n const maxInterval = Math.max(...sm.chunkIntervals);\n\n console.log(\n chalk.white(' \u23F3 Avg Chunk Interval: ') +\n chalk.yellow(`${avgInterval.toFixed(0)} ms`),\n );\n console.log(\n chalk.gray(' Min/Max: ') +\n chalk.gray(\n `${minInterval.toFixed(0)} - ${maxInterval.toFixed(0)} ms`,\n ),\n );\n }\n\n // Data Transfer\n console.log(chalk.bold.white('\\n Data Transfer:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n console.log(\n chalk.white(' \uD83D\uDCE5 Total Data: ') +\n chalk.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`),\n );\n console.log(\n chalk.white(' \uD83C\uDFB5 Audio File: ') +\n chalk.yellow(\n `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`,\n ),\n );\n\n // Performance Metrics\n console.log(chalk.bold.white('\\n Performance Metrics:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n\n // Calculate streaming throughput\n const throughputKBps = sm.totalBytes / 1024 / (sm.totalTime / 1000);\n console.log(\n chalk.white(' \uD83D\uDCF6 Stream Throughput: ') +\n chalk.yellow(`${throughputKBps.toFixed(2)} KB/s`),\n );\n\n // Calculate audio duration (rough estimate for MP3)\n const audioDuration = (audioBuffer?.length || 0) / (128 * 125); // 128kbps default\n const realTimeRatio = audioDuration / (sm.totalTime / 1000);\n\n console.log(\n chalk.white(' \uD83C\uDFB5 Audio Duration: ') +\n chalk.yellow(`${audioDuration.toFixed(2)} seconds`),\n );\n\n console.log(\n chalk.white(' \u26A1 Real-time Factor: ') +\n (realTimeRatio > 1\n ? chalk.green(`${realTimeRatio.toFixed(2)}x faster`)\n : chalk.yellow(`${realTimeRatio.toFixed(2)}x`)),\n );\n\n // Streaming efficiency\n const streamingEfficiency =\n ((sm.totalTime - sm.timeToFirstChunk) / sm.totalTime) * 100;\n console.log(\n chalk.white(' \uD83D\uDCC8 Stream Efficiency: ') +\n chalk.yellow(`${streamingEfficiency.toFixed(1)}%`),\n );\n\n console.log(chalk.gray('\u2550'.repeat(50)));\n } else {\n // Display regular (non-streaming) metrics\n console.log('\\n' + chalk.cyan('\uD83D\uDCCA Performance Statistics:'));\n console.log(chalk.gray('\u2550'.repeat(50)));\n\n // Network Timing Breakdown\n console.log(chalk.bold.white('\\n Network Timing:'));\n\n console.log(chalk.gray(' \u2500'.repeat(23)));\n console.log(\n chalk.white(' \u23F1\uFE0F Time to First Byte: ') +\n chalk.yellow(`${m.ttfb.toFixed(0)} ms`),\n );\n\n if (m.downloadTime !== undefined) {\n console.log(\n chalk.white(' \u2B07\uFE0F Content Download: ') +\n chalk.yellow(`${m.downloadTime.toFixed(0)} ms`),\n );\n }\n\n console.log(\n chalk.white(' \u23F2\uFE0F Total Time: ') +\n chalk.bold.yellow(`${m.totalTime.toFixed(0)} ms`),\n );\n\n // Data Transfer\n console.log(chalk.bold.white('\\n Data Transfer:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n\n if (m.requestSize) {\n console.log(\n chalk.white(' \u2B06\uFE0F Request Size: ') +\n chalk.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`),\n );\n }\n\n console.log(\n chalk.white(' \u2B07\uFE0F Response Size: ') +\n chalk.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`),\n );\n\n console.log(\n chalk.white(' \uD83C\uDFB5 Audio File: ') +\n chalk.yellow(\n `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`,\n ),\n );\n\n // Performance Metrics\n console.log(chalk.bold.white('\\n Performance Metrics:'));\n console.log(chalk.gray(' \u2500'.repeat(23)));\n\n // Calculate approximate audio duration (rough estimate for MP3)\n const audioDuration = (audioBuffer?.length || 0) / (128 * 125); // 128kbps default\n const realTimeRatio = audioDuration / (m.totalTime / 1000);\n\n // Server processing time estimate\n const serverTime = m.ttfb;\n\n console.log(\n chalk.white(' \uD83D\uDDA5\uFE0F Server Processing: ') +\n chalk.yellow(`${Math.max(0, serverTime).toFixed(0)} ms`),\n );\n\n console.log(\n chalk.white(' \uD83C\uDFB5 Audio Duration: ') +\n chalk.yellow(`${audioDuration.toFixed(2)} seconds`),\n );\n\n console.log(\n chalk.white(' \u26A1 Real-time Factor: ') +\n (realTimeRatio > 1\n ? chalk.green(`${realTimeRatio.toFixed(2)}x faster`)\n : chalk.yellow(`${realTimeRatio.toFixed(2)}x`)),\n );\n\n // Throughput calculation\n const throughputMbps =\n ((m.responseSize + (audioBuffer?.length || 0)) * 8) /\n (m.totalTime * 1000);\n console.log(\n chalk.white(' \uD83D\uDCF6 Throughput: ') +\n chalk.yellow(`${throughputMbps.toFixed(2)} Mbps`),\n );\n\n console.log(chalk.gray('\u2550'.repeat(50)));\n }\n }\n\n // Display timestamp info if available\n if (response.timestampInfo?.wordAlignment) {\n const alignment = response.timestampInfo.wordAlignment;\n console.log('\\n' + chalk.cyan('\uD83D\uDCDD Word Timestamps:'));\n alignment.words.forEach((word: string, i: number) => {\n const start = alignment.wordStartTimeSeconds[i].toFixed(3);\n const end = alignment.wordEndTimeSeconds[i].toFixed(3);\n console.log(chalk.gray(` ${start}s - ${end}s: ${word}`));\n });\n }\n\n if (response.timestampInfo?.characterAlignment) {\n console.log('\\n' + chalk.cyan('\uD83D\uDCDD Character Timestamps:'));\n console.log(\n chalk.gray(\n ' (Too detailed to display - use --json to see full data)',\n ),\n );\n }\n\n process.exit(0);\n } catch (error: any) {\n console.error(chalk.red('\u274C Error synthesizing speech:'));\n console.error(chalk.red(error.message || error));\n process.exit(1);\n }\n });\n\n/**\n * Main TTS command with subcommands\n * Manages text-to-speech functionality\n */\nexport const ttsCommand = new Command('tts')\n .description('Text-to-speech functionality')\n .addCommand(listVoicesCommand)\n .addCommand(synthesizeCommand)\n .action(() => {\n ttsCommand.help();\n });\n", "import { requireApiKey } from '../auth/utils';\nimport { PLATFORM_URL } from '../constants';\n\n/**\n * Audio encoding options for TTS\n * @see {@link https://api.inworld.ai/docs/models#tts}\n */\nexport enum AudioEncoding {\n LINEAR16 = 'LINEAR16',\n MP3 = 'MP3',\n OGG_OPUS = 'OGG_OPUS',\n ALAW = 'ALAW',\n MULAW = 'MULAW',\n}\n\n/**\n * Available TTS models\n * @see {@link https://api.inworld.ai/docs/models#tts}\n */\nexport enum TTSModel {\n INWORLD_TTS_1 = 'inworld-tts-1',\n INWORLD_TTS_1_MAX = 'inworld-tts-1-max',\n}\n\n/**\n * Timestamp types for alignment data\n */\nexport enum TimestampType {\n UNSPECIFIED = 'TIMESTAMP_TYPE_UNSPECIFIED',\n WORD = 'WORD',\n CHARACTER = 'CHARACTER',\n}\n\n/**\n * Audio configuration for TTS synthesis\n * @description Configurations to use when synthesizing speech\n */\nexport interface AudioConfig {\n /** The desired output format of the synthesized audio. Defaults to MP3. */\n audioEncoding?: AudioEncoding;\n /** Bits per second of the audio. Only for compressed audio formats (MP3, OGG_OPUS). Default is 128,000. */\n bitRate?: number;\n /** The synthesis sample rate (in hertz) for this audio. Accepts values within the range [8000, 48000]. Default is 48,000. */\n sampleRateHertz?: number;\n /** Modifies the pitch of the synthesized speech. Range [-5.0, 5.0]. 0.0 is original pitch. Default is 0.0. */\n pitch?: number;\n /** Speaking rate/speed, in the range [0.5, 1.5]. Not supported for streaming. Default is 1.0. */\n speakingRate?: number;\n}\n\n/**\n * Request options for synthesizing speech\n * @description Parameters for the TTS synthesis request\n */\nexport interface SynthesizeSpeechRequest {\n /** The text to be synthesized into speech. Maximum input of 2,000 characters. */\n text: string;\n /** The ID of the voice to use for synthesizing speech. */\n voiceId: string;\n /** The ID of the model to use for synthesizing speech. */\n modelId: TTSModel;\n /** Audio configuration options. */\n audioConfig?: AudioConfig;\n /** Determines the degree of randomness when sampling audio tokens. Range [0, 2]. Default is 0.8. */\n temperature?: number;\n /** Controls timestamp metadata returned with the audio. */\n timestampType?: TimestampType;\n}\n\n/**\n * Word alignment information\n * @description Word-level timestamp alignment data\n */\nexport interface WordAlignment {\n /** Aligned words in order. */\n words: string[];\n /** Start time for each word in seconds from the beginning of the audio. */\n wordStartTimeSeconds: number[];\n /** End time for each word in seconds from the beginning of the audio. */\n wordEndTimeSeconds: number[];\n}\n\n/**\n * Character alignment information\n * @description Character-level timestamp alignment data\n */\nexport interface CharacterAlignment {\n /** Aligned characters (including punctuation and spaces) in order. */\n characters: string[];\n /** Start time for each character in seconds from the beginning of the audio. */\n characterStartTimeSeconds: number[];\n /** End time for each character in seconds from the beginning of the audio. */\n characterEndTimeSeconds: number[];\n}\n\n/**\n * Timestamp information for synthesized speech\n * @description Alignment information present when alignment is enabled\n */\nexport interface TimestampInfo {\n /** Word-level alignment when timestampType is WORD. */\n wordAlignment?: WordAlignment;\n /** Character-level alignment when timestampType is CHARACTER. */\n characterAlignment?: CharacterAlignment;\n}\n\n/**\n * Response from synthesizing speech\n * @description The response containing the synthesized audio and optional timestamp information\n */\nexport interface SynthesizeSpeechResponse {\n /** The audio data bytes encoded in the format specified in the request. Base64 encoded. */\n audioContent: string;\n /** Timestamp alignment information (present when alignment is enabled). */\n timestampInfo?: TimestampInfo;\n}\n\n/**\n * Voice information\n * @description Information about an available TTS voice\n */\nexport interface Voice {\n /** The language(s) of the original voice audio. */\n languages: string[];\n /** The ID of the voice. */\n voiceId: string;\n /** The display name of the voice. */\n displayName?: string;\n /** The description of the voice. */\n description?: string;\n}\n\n/**\n * Response from listing voices\n * @description The response containing the list of available voices\n */\nexport interface ListVoicesResponse {\n /** The list of voices. */\n voices: Voice[];\n}\n\n/**\n * Error response from the API\n * @description Standard error response format\n */\nexport interface ErrorResponse {\n /** The error code, as specified by gRPC status codes. */\n code: number;\n /** A short description of the error. */\n message: string;\n /** Additional error details. */\n details?: any[];\n}\n\n/**\n * Request performance metrics\n * @description Timing and size metrics for API requests\n */\nexport interface RequestMetrics {\n /** Time when the request started (ms) */\n startTime: number;\n /** Time to first byte (ms) */\n ttfb: number;\n /** Total request time (ms) */\n totalTime: number;\n /** Estimated response size in bytes */\n responseSize: number;\n}\n\n/**\n * Streaming performance metrics\n * @description Timing and chunk metrics for streaming requests\n */\nexport interface StreamingMetrics {\n /** Time when the request started (ms) */\n startTime: number;\n /** Time to first chunk (ms) */\n timeToFirstChunk: number;\n /** Total streaming time (ms) */\n totalTime: number;\n /** Number of chunks received */\n chunksReceived: number;\n /** Total bytes received */\n totalBytes: number;\n /** Individual chunk sizes */\n chunkSizes: number[];\n /** Time between chunks (ms) */\n chunkIntervals: number[];\n /** Error chunks received */\n errorChunks: number;\n}\n\n/**\n * TTS Service for interacting with Inworld's Text-to-Speech API\n * @description Provides methods for listing voices and synthesizing speech\n */\nexport class TTSService {\n private apiKey: string | null = null;\n\n /**\n * Ensures the API key is available\n * @private\n */\n private async ensureApiKey(): Promise<string> {\n if (!this.apiKey) {\n this.apiKey = await requireApiKey();\n }\n return this.apiKey!;\n }\n\n /**\n * Makes an authenticated request to the Inworld API\n * @private\n */\n private async makeRequest<T>(\n endpoint: string,\n options: RequestInit = {},\n trackMetrics = false,\n ): Promise<T & { _metrics?: RequestMetrics }> {\n const apiKey = await this.ensureApiKey();\n const url = `${PLATFORM_URL.replace('platform', 'api')}${endpoint}`;\n\n const metrics: RequestMetrics = trackMetrics\n ? {\n startTime: Date.now(),\n ttfb: 0,\n totalTime: 0,\n responseSize: 0,\n }\n : ({} as RequestMetrics);\n\n const response = await fetch(url, {\n ...options,\n headers: {\n Authorization: `Basic ${apiKey}`,\n 'Content-Type': 'application/json',\n ...options.headers,\n },\n });\n\n if (trackMetrics) {\n metrics.ttfb = Date.now() - metrics.startTime;\n }\n\n const data = await response.json();\n\n if (trackMetrics) {\n metrics.totalTime = Date.now() - metrics.startTime;\n // Estimate response size from JSON string\n metrics.responseSize = JSON.stringify(data).length;\n }\n\n if (!response.ok) {\n const error = data as ErrorResponse;\n throw new Error(\n `TTS API Error [${error.code || response.status}]: ${error.message || 'Unknown error'}`,\n );\n }\n\n const result = data as T & { _metrics?: RequestMetrics };\n if (trackMetrics) {\n result._metrics = metrics;\n }\n\n return result;\n }\n\n /**\n * Lists all available voices based on the provided filter\n * @param filter - Optional filter expression (e.g., \"language=en\")\n * @returns Promise resolving to the list of available voices\n * @example\n * ```typescript\n * const ttsService = new TTSService();\n * const voices = await ttsService.listVoices('language=en');\n * console.log(voices.voices);\n * ```\n */\n async listVoices(filter?: string): Promise<ListVoicesResponse> {\n const params = filter ? `?filter=${encodeURIComponent(filter)}` : '';\n return this.makeRequest<ListVoicesResponse>(`/tts/v1/voices${params}`, {\n method: 'GET',\n });\n }\n\n /**\n * Synthesizes speech from text\n * @param request - The synthesis request parameters\n * @returns Promise resolving to the synthesized audio data and optional timestamp information\n * @example\n * ```typescript\n * const ttsService = new TTSService();\n * const result = await ttsService.synthesizeSpeech({\n * text: 'Hello, world!',\n * voiceId: 'Dennis',\n * modelId: TTSModel.INWORLD_TTS_1,\n * timestampType: TimestampType.WORD,\n * });\n * // result.audioContent is base64 encoded audio data\n * ```\n */\n async synthesizeSpeech(\n request: SynthesizeSpeechRequest,\n ): Promise<SynthesizeSpeechResponse> {\n return this.makeRequest<SynthesizeSpeechResponse>('/tts/v1/voice', {\n method: 'POST',\n body: JSON.stringify(request),\n });\n }\n\n /**\n * Synthesizes speech from text with performance metrics\n * @param request - The synthesis request parameters\n * @returns Promise resolving to the synthesized audio data with metrics\n */\n async synthesizeSpeechWithMetrics(\n request: SynthesizeSpeechRequest,\n ): Promise<SynthesizeSpeechResponse & { _metrics?: RequestMetrics }> {\n return this.makeRequest<SynthesizeSpeechResponse>(\n '/tts/v1/voice',\n {\n method: 'POST',\n body: JSON.stringify(request),\n },\n true, // trackMetrics\n );\n }\n\n /**\n * Synthesizes speech using streaming API\n * @param request - The synthesis request parameters\n * @param onChunk - Callback for each audio chunk received\n * @param trackMetrics - Whether to track streaming metrics\n * @returns Promise resolving when stream completes, with optional metrics\n */\n async synthesizeSpeechStream(\n request: SynthesizeSpeechRequest,\n onChunk: (chunk: {\n audioContent?: string;\n timestampInfo?: TimestampInfo;\n error?: ErrorResponse;\n }) => void,\n trackMetrics = false,\n ): Promise<{ _metrics?: StreamingMetrics }> {\n const apiKey = await this.ensureApiKey();\n const url = `${PLATFORM_URL.replace('platform', 'api')}/tts/v1/voice:stream`;\n\n const metrics: StreamingMetrics = trackMetrics\n ? {\n startTime: Date.now(),\n timeToFirstChunk: 0,\n totalTime: 0,\n chunksReceived: 0,\n totalBytes: 0,\n chunkSizes: [],\n chunkIntervals: [],\n errorChunks: 0,\n }\n : ({} as StreamingMetrics);\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(request),\n });\n\n if (!response.ok) {\n const error = (await response.json()) as ErrorResponse;\n throw new Error(\n `TTS Stream API Error [${error.code || response.status}]: ${error.message || 'Unknown error'}`,\n );\n }\n\n if (!response.body) {\n throw new Error('No response body received from streaming endpoint');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let lastChunkTime = trackMetrics ? Date.now() : 0;\n let isFirstChunk = true;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) break;\n\n // Decode the chunk\n buffer += decoder.decode(value, { stream: true });\n\n // Process complete lines\n const lines = buffer.split('\\n');\n buffer = lines.pop() || ''; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue; // Skip empty lines\n\n try {\n const data = JSON.parse(line);\n\n if (trackMetrics) {\n const now = Date.now();\n\n if (isFirstChunk) {\n metrics.timeToFirstChunk = now - metrics.startTime;\n isFirstChunk = false;\n } else {\n metrics.chunkIntervals.push(now - lastChunkTime);\n }\n\n lastChunkTime = now;\n metrics.chunksReceived++;\n\n if (data.result?.audioContent) {\n const chunkSize = data.result.audioContent.length;\n metrics.chunkSizes.push(chunkSize);\n metrics.totalBytes += chunkSize;\n }\n\n if (data.error) {\n metrics.errorChunks++;\n }\n }\n\n // Pass the chunk to the callback\n if (data.result) {\n onChunk(data.result);\n } else if (data.error) {\n onChunk({ error: data.error });\n }\n } catch (e) {\n console.error('Failed to parse streaming chunk:', e);\n }\n }\n }\n\n // Process any remaining data in buffer\n if (buffer.trim()) {\n try {\n const data = JSON.parse(buffer);\n if (data.result) {\n onChunk(data.result);\n } else if (data.error) {\n onChunk({ error: data.error });\n }\n } catch (e) {\n console.error('Failed to parse final chunk:', e);\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n if (trackMetrics) {\n metrics.totalTime = Date.now() - metrics.startTime;\n }\n\n return trackMetrics ? { _metrics: metrics } : {};\n }\n\n /**\n * Helper method to synthesize speech with simple parameters\n * @param text - The text to synthesize\n * @param voiceId - The voice ID to use\n * @param modelId - The model ID to use (defaults to inworld-tts-1-max)\n * @returns Promise resolving to the synthesized audio data\n * @example\n * ```typescript\n * const ttsService = new TTSService();\n * const result = await ttsService.synthesize('Hello, world!', 'Dennis');\n * const audioBuffer = Buffer.from(result.audioContent, 'base64');\n * ```\n */\n async synthesize(\n text: string,\n voiceId: string,\n modelId: TTSModel = TTSModel.INWORLD_TTS_1_MAX,\n ): Promise<SynthesizeSpeechResponse> {\n return this.synthesizeSpeech({\n text,\n voiceId,\n modelId,\n });\n }\n\n /**\n * Saves synthesized audio to a file\n * @param audioContent - Base64 encoded audio content\n * @param filepath - Path where the audio file should be saved\n * @returns Promise that resolves when the file is written\n * @example\n * ```typescript\n * const ttsService = new TTSService();\n * const result = await ttsService.synthesize('Hello, world!', 'Dennis');\n * await ttsService.saveAudioToFile(result.audioContent, 'output.mp3');\n * ```\n */\n async saveAudioToFile(audioContent: string, filepath: string): Promise<void> {\n const { writeFile } = await import('fs/promises');\n const audioBuffer = Buffer.from(audioContent, 'base64');\n await writeFile(filepath, audioBuffer);\n }\n}\n\n// Export a singleton instance for convenience\nexport const ttsService = new TTSService();\n\n// Re-export the main synthesis function for backward compatibility\nexport const synthesizeSpeech = async (\n text: string,\n voice: string,\n): Promise<SynthesizeSpeechResponse> => {\n return ttsService.synthesize(text, voice);\n};\n", "import { Command } from 'commander';\n\nimport { requireAuth } from '../auth/utils.js';\nimport { WorkspaceService } from '../services/workspace_service.js';\nimport { printError } from '../utils/ui';\n\n/**\n * Activate workspace command\n * Sets the active workspace for subsequent CLI operations\n */\nexport const selectWorkspaceCommand = new Command('select')\n .description('Select a workspace for CLI operations')\n .action(async () => {\n await requireAuth();\n try {\n await WorkspaceService.activateWorkspace();\n process.exit(0);\n } catch (_error) {\n printError('\\nFailed to select workspace:');\n process.exit(1);\n }\n });\n\n/**\n * Main workspace command with subcommands\n * Manages user workspaces\n */\nexport const workspaceCommand = new Command('workspace')\n .description('Manage Inworld workspaces')\n .alias('ws')\n .addCommand(selectWorkspaceCommand)\n .action(() => {\n workspaceCommand.help();\n });\n"],
5
- "mappings": ";;;;AAAA,OAAOA,aAAW;AAClB,SAAS,WAAAC,iBAAe;;;ACDxB,OAAOC,YAAW;AAClB,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,YAAYC,eAAc;AAC1B,SAAS,iBAAiB;;;ACJ1B,YAAY,UAAU;;;ACAtB;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,KAAO;AAAA,IACL,SAAW;AAAA,EACb;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,aAAa;AAAA,IACb,eAAe;AAAA,IACf,aAAa;AAAA,IACb,OAAS;AAAA,IACT,KAAO;AAAA,EACT;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AAAA,EACV,SAAW;AAAA,EACX,aAAe;AAAA,EACf,iBAAm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AAqB,cAAc,eAAe,EAAE,MAAM,MAAM;AAAA,MAEtE,CAAC;AAGD,YAAM,iBAAiB,IAAI;AAAA,QAAQ,CAACC,aAClC,WAAWA,UAAS,GAAI;AAAA,MAC1B;AACA,YAAM,QAAQ,KAAK,CAAC,oBAAoB,cAAc,CAAC;AAEvD,YAAM,KAAK,QAAQ,WAAW,IAAI;AAAA,IACpC,SAAS,OAAO;AACd,cAAQ;AAAA,QACNC,QAAM,IAAI,QAAQ;AAAA,QAClB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MACvD;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAGA,IAAM,MAAM,IAAI,WAAW;AAC3B,IAAI,IAAI,EAAE,MAAM,CAAC,UAAU;AACzB,UAAQ,MAAMA,QAAM,IAAI,cAAc,GAAG,KAAK;AAC9C,UAAQ,KAAK,CAAC;AAChB,CAAC;",
6
- "names": ["chalk", "Command", "chalk", "readline", "resolve", "path", "path", "GrpcStatusCode", "resolve", "isAuthenticated", "InworldError", "signal", "resolve", "chalk", "resolve", "readline", "resolve", "chalk", "resolve", "result", "success", "chalk", "chalk", "Command", "isAuthenticated", "Command", "chalk", "chalk", "Command", "chalk", "Command", "Command", "Command", "success", "Command", "Command", "Command", "Command", "Command", "Command", "chalk", "Command", "fs", "path", "chalk", "chalk", "chalk", "deployment", "path", "fs", "resolve", "Command", "chalk", "chalk", "Command", "fs", "path", "readline", "path", "fs", "resolve", "templates", "chalk", "Command", "chalk", "Command", "Command", "chalk", "chalk", "Command", "Command", "chalk", "Command", "Command", "Command", "operation", "Command", "Command", "path", "path", "fs", "Command", "chalk", "Command", "chalk", "Command", "Command", "Command", "path", "path", "Command", "Command", "chalk", "Command", "writeFile", "Command", "chalk", "Command", "Command", "Command", "resolve", "chalk"]
7
- }