cloving 0.3.17 → 0.3.19

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 (102) hide show
  1. package/.DS_Store +0 -0
  2. package/.aider.chat.history.md +16978 -0
  3. package/.aider.input.history +15 -0
  4. package/.aider.tags.cache.v3/cache.db +0 -0
  5. package/.aider.tags.cache.v3/cache.db-shm +0 -0
  6. package/.aider.tags.cache.v3/cache.db-wal +0 -0
  7. package/.cursorrules +77 -0
  8. package/.github/workflows/auto-release.yml +83 -0
  9. package/.github/workflows/ci.yml +32 -0
  10. package/.github/workflows/npm-publish.yml +34 -0
  11. package/.gitignore +67 -0
  12. package/.husky/_/.gitignore +1 -0
  13. package/.husky/_/applypatch-msg +2 -0
  14. package/.husky/_/commit-msg +2 -0
  15. package/.husky/_/h +22 -0
  16. package/.husky/_/husky.sh +9 -0
  17. package/.husky/_/post-applypatch +2 -0
  18. package/.husky/_/post-checkout +2 -0
  19. package/.husky/_/post-commit +2 -0
  20. package/.husky/_/post-merge +2 -0
  21. package/.husky/_/post-rewrite +2 -0
  22. package/.husky/_/pre-applypatch +2 -0
  23. package/.husky/_/pre-auto-gc +2 -0
  24. package/.husky/_/pre-commit +2 -0
  25. package/.husky/_/pre-merge-commit +2 -0
  26. package/.husky/_/pre-push +2 -0
  27. package/.husky/_/pre-rebase +2 -0
  28. package/.husky/_/prepare-commit-msg +2 -0
  29. package/.husky/pre-commit +1 -0
  30. package/.husky/pre-push +1 -0
  31. package/.prettierrc.json +7 -0
  32. package/.tool-versions +2 -0
  33. package/SECURITY.md +15 -0
  34. package/cloving.json +67 -0
  35. package/dist/cloving_gpt/adapters/openai.js +2 -0
  36. package/dist/commands/generate/context.js +1 -1
  37. package/dist/commands/tokens.js +1 -1
  38. package/dist/managers/CommitManager.js +8 -2
  39. package/dist/managers/ProxyManager.js +9 -2
  40. package/dist/managers/StreamManager.js +1 -1
  41. package/dist/package.json +26 -26
  42. package/dist/utils/config_utils.js +21 -4
  43. package/dist/utils/git_utils.js +109 -7
  44. package/dist/utils/prompt_utils.js +3 -3
  45. package/jest.config.js +11 -0
  46. package/package.json +23 -23
  47. package/src/cloving_gpt/adapters/azureopenai.ts +83 -0
  48. package/src/cloving_gpt/adapters/claude.ts +140 -0
  49. package/src/cloving_gpt/adapters/gemini.ts +146 -0
  50. package/src/cloving_gpt/adapters/index.ts +43 -0
  51. package/src/cloving_gpt/adapters/mistral.ts +142 -0
  52. package/src/cloving_gpt/adapters/ollama.ts +136 -0
  53. package/src/cloving_gpt/adapters/openai.ts +113 -0
  54. package/src/cloving_gpt/index.ts +229 -0
  55. package/src/commands/chat.ts +12 -0
  56. package/src/commands/config.ts +192 -0
  57. package/src/commands/generate/code.ts +18 -0
  58. package/src/commands/generate/commit.ts +9 -0
  59. package/src/commands/generate/context.ts +93 -0
  60. package/src/commands/generate/docs.ts +9 -0
  61. package/src/commands/generate/review.ts +9 -0
  62. package/src/commands/generate/shell.ts +9 -0
  63. package/src/commands/generate/unit_tests.ts +9 -0
  64. package/src/commands/init.ts +9 -0
  65. package/src/commands/models.ts +21 -0
  66. package/src/commands/proxy.ts +9 -0
  67. package/src/commands/tokens.ts +82 -0
  68. package/src/index.ts +197 -0
  69. package/src/managers/BlockManager.ts +126 -0
  70. package/src/managers/ChatManager.ts +755 -0
  71. package/src/managers/ChunkManager.ts +31 -0
  72. package/src/managers/CodeManager.ts +226 -0
  73. package/src/managers/CommitManager.ts +71 -0
  74. package/src/managers/DocsManager.ts +101 -0
  75. package/src/managers/InitManager.ts +263 -0
  76. package/src/managers/ProxyManager.ts +240 -0
  77. package/src/managers/ReviewManager.ts +154 -0
  78. package/src/managers/ShellManager.ts +172 -0
  79. package/src/managers/StreamManager.ts +353 -0
  80. package/src/managers/UnitTestManager.ts +293 -0
  81. package/src/utils/config_utils.ts +271 -0
  82. package/src/utils/git_utils.ts +230 -0
  83. package/src/utils/model_utils.ts +3 -0
  84. package/src/utils/prompt_utils.ts +375 -0
  85. package/src/utils/prompts/CODEGEN_COULDNT_APPLY.md +5 -0
  86. package/src/utils/prompts/CODEGEN_EXAMPLES.md +82 -0
  87. package/src/utils/prompts/CODEGEN_INSTRUCTIONS.md +43 -0
  88. package/src/utils/prompts/DOCS_INSTRUCTIONS.md +9 -0
  89. package/src/utils/prompts/INIT_INSTRUCTIONS.md +132 -0
  90. package/src/utils/prompts/REVIEW_INSTRUCTIONS.md +49 -0
  91. package/src/utils/prompts/SHELL_INSTRUCTIONS.md +15 -0
  92. package/src/utils/prompts/SPECIAL_FILES.md +66 -0
  93. package/src/utils/prompts/index.ts +37 -0
  94. package/src/utils/string_utils.ts +552 -0
  95. package/src/utils/types.ts +127 -0
  96. package/tests/commands/generate/unit_tests.test.ts +27 -0
  97. package/tests/utils/git_utils.test.ts +116 -0
  98. package/tests/utils/model_utils.test.ts +27 -0
  99. package/tests/utils/prompt_utils.test.ts +33 -0
  100. package/tests/utils/string_utils.test.ts +560 -0
  101. package/tsconfig.json +14 -0
  102. package/yarn.lock +5823 -0
@@ -0,0 +1,240 @@
1
+ import express, { Request, Response } from 'express'
2
+ import bodyParser from 'body-parser'
3
+ import fs from 'fs'
4
+ import path from 'path'
5
+
6
+ import ClovingGPT from '../cloving_gpt'
7
+ import ChunkManager from './ChunkManager'
8
+ import { getNearestClovingConfig } from '../utils/config_utils'
9
+ import { getAllFilesInDirectory } from '../utils/prompt_utils'
10
+ import type { ClovingGPTOptions } from '../utils/types'
11
+
12
+ class ProxyManager {
13
+ private gpt: ClovingGPT
14
+ private app: express.Application
15
+ private contextFiles: Record<string, string> = {}
16
+ private chunkManager: ChunkManager
17
+
18
+ /**
19
+ * Creates an instance of ProxyManager.
20
+ * @param {ClovingGPTOptions} options - Configuration options for the ProxyManager.
21
+ * @description
22
+ * Initializes the ProxyManager with the given options. It sets up:
23
+ * - A ClovingGPT instance with silent and stream options enabled
24
+ * - An Express application with JSON body parsing
25
+ * - A ChunkManager for handling streaming responses
26
+ */
27
+ constructor(private options: ClovingGPTOptions) {
28
+ this.options.silent = true
29
+ this.options.stream = true
30
+ this.gpt = new ClovingGPT(this.options)
31
+ this.app = express()
32
+ this.app.use(bodyParser.json())
33
+ this.chunkManager = new ChunkManager()
34
+ }
35
+
36
+ async initialize() {
37
+ await this.setupRoutes()
38
+ await this.loadContextFiles()
39
+ this.startServer()
40
+ }
41
+
42
+ private async setupRoutes() {
43
+ this.app.get('/', (_req: Request, res: Response) => {
44
+ res.json({ message: 'ClovingGPT proxy server running' })
45
+ })
46
+
47
+ this.app.post('/v1/chat/completions', async (req, res, next) => {
48
+ try {
49
+ await this.handleChatCompletions(req, res)
50
+ } catch (error) {
51
+ next(error)
52
+ }
53
+ })
54
+ }
55
+
56
+ private async loadContextFiles() {
57
+ let files = this.options.files || '.'
58
+
59
+ let expandedFiles: string[] = []
60
+ for (const file of files) {
61
+ const filePath = path.resolve(file)
62
+ if (
63
+ await fs.promises
64
+ .stat(filePath)
65
+ .then((stat) => stat.isDirectory())
66
+ .catch(() => false)
67
+ ) {
68
+ const dirFiles = await getAllFilesInDirectory(filePath)
69
+ expandedFiles = expandedFiles.concat(dirFiles.map((f) => path.relative(process.cwd(), f)))
70
+ } else {
71
+ expandedFiles.push(path.relative(process.cwd(), filePath))
72
+ }
73
+ }
74
+ files = expandedFiles
75
+
76
+ for (const file of files) {
77
+ const filePath = path.resolve(file)
78
+ if (
79
+ await fs.promises
80
+ .stat(filePath)
81
+ .then((stat) => stat.isFile())
82
+ .catch(() => false)
83
+ ) {
84
+ const content = await fs.promises.readFile(filePath, 'utf-8')
85
+ this.contextFiles[file] = content
86
+ }
87
+ }
88
+ }
89
+
90
+ private async handleChatCompletions(req: Request, res: Response) {
91
+ try {
92
+ const { messages, stream } = req.body
93
+
94
+ if (!Array.isArray(messages)) {
95
+ return res.status(400).json({ error: 'Invalid request body: messages must be an array' })
96
+ }
97
+
98
+ const content = messages
99
+ .map((message: any) => {
100
+ if (typeof message !== 'object' || typeof message.content !== 'string') {
101
+ throw new Error('Invalid message format')
102
+ }
103
+ return message.content
104
+ })
105
+ .join('\n\n')
106
+
107
+ const contextFileContents = Object.keys(this.contextFiles)
108
+ .map((file) => `### Contents of ${file}\n\n${this.contextFiles[file]}\n\n`)
109
+ .join('\n')
110
+ const prompt = `# Task
111
+
112
+ ${content}
113
+
114
+ ### Description of App
115
+
116
+ ${JSON.stringify(getNearestClovingConfig().config, null, 2)}
117
+
118
+ ${contextFileContents}
119
+
120
+ # Task
121
+
122
+ ${content}`
123
+
124
+ if (stream) {
125
+ await this.handleStreamResponse(prompt, res)
126
+ } else {
127
+ await this.handleNonStreamResponse(prompt, res)
128
+ }
129
+ } catch (error) {
130
+ console.error('Error processing request:', error)
131
+ if (error instanceof Error && error.message === 'Invalid message format') {
132
+ res.status(400).json({
133
+ error: 'Invalid request body: each message must have a content property of type string',
134
+ })
135
+ } else {
136
+ res.status(500).json({ error: 'Internal server error' })
137
+ }
138
+ }
139
+ }
140
+
141
+ private async handleStreamResponse(prompt: string, res: Response) {
142
+ const shortPrompt = prompt.replace('### Task', '').trim().slice(0, 50).replace(/\n/g, ' ')
143
+ const promptTokens = Math.ceil(prompt.length / 4).toLocaleString()
144
+ console.log(`> sending ${promptTokens} token prompt:`, shortPrompt)
145
+ const responseStream = await this.gpt.streamText({ prompt })
146
+
147
+ res.setHeader('Content-Type', 'application/json')
148
+ res.setHeader('Transfer-Encoding', 'chunked')
149
+
150
+ let convertedStreams: string[] = []
151
+ // Add initial stream to indicate the start of the response
152
+ convertedStreams.push(
153
+ '{"id":"chatcmpl-9tLvSuRQaYzQIiKRAwI5a7WqdJspq","object":"chat.completion.chunk","created":1722979349,"model":"cloving","system_fingerprint":"fp_3aa7262c27","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]}',
154
+ )
155
+
156
+ this.chunkManager.on('content', (buffer: string) => {
157
+ let convertedStream = this.gpt.convertStream(buffer)
158
+
159
+ while (convertedStream !== null) {
160
+ const { output, lastChar } = convertedStream
161
+ const content = JSON.stringify({
162
+ id: 'chatcmpl-9tLvSuRQaYzQIiKRAwI5a7WqdJspq',
163
+ object: 'chat.completion.chunk',
164
+ created: 1722979350,
165
+ model: 'cloving',
166
+ system_fingerprint: 'fp_3aa7262c27',
167
+ choices: [{ index: 0, delta: { content: output }, logprobs: null, finish_reason: null }],
168
+ })
169
+
170
+ convertedStreams.push(content)
171
+
172
+ if (convertedStreams.length >= 2) {
173
+ const dataToSend = convertedStreams.map((c) => `data: ${c}`).join('\n\n')
174
+ res.write(`${dataToSend}\n\n`)
175
+ convertedStreams = []
176
+ }
177
+
178
+ buffer = buffer.slice(lastChar)
179
+ convertedStream = this.gpt.convertStream(buffer)
180
+ }
181
+ })
182
+
183
+ responseStream.data.on('data', (chunk: Buffer) => {
184
+ const chunkString = chunk.toString()
185
+ this.chunkManager.addChunk(chunkString)
186
+ })
187
+
188
+ responseStream.data.on('end', () => {
189
+ // Send any remaining converted streams
190
+ const dataToSend = convertedStreams.map((c) => `data: ${c}`).join('\n\n')
191
+ res.write(`${dataToSend}\n\ndata: [DONE]\n\n`)
192
+ res.end()
193
+ })
194
+
195
+ responseStream.data.on('error', (error: Error) => {
196
+ console.error('Error streaming response:', error)
197
+ res.status(500).json({ error: 'Internal server error' })
198
+ })
199
+ }
200
+
201
+ private async handleNonStreamResponse(prompt: string, res: Response) {
202
+ const content = await this.gpt.generateText({ prompt })
203
+
204
+ const response = {
205
+ id: 'chatcmpl-' + Date.now(),
206
+ object: 'chat.completion',
207
+ created: Math.floor(Date.now() / 1000),
208
+ model: 'cloving',
209
+ choices: [
210
+ {
211
+ index: 0,
212
+ message: {
213
+ role: 'assistant',
214
+ content,
215
+ },
216
+ logprobs: null,
217
+ finish_reason: 'stop',
218
+ },
219
+ ],
220
+ usage: {
221
+ prompt_tokens: Math.ceil(prompt.length / 4),
222
+ completion_tokens: Math.ceil(content.length / 4),
223
+ total_tokens: Math.ceil(prompt.length / 4) + Math.ceil(content.length / 4),
224
+ },
225
+ system_fingerprint: 'fp_3cd8b62c3b',
226
+ }
227
+
228
+ res.json(response)
229
+ }
230
+
231
+ private startServer() {
232
+ const port = parseInt(`${process.env.PORT || this.options.port || 3000}`, 10)
233
+
234
+ this.app.listen(port, () => {
235
+ console.log(`ClovingGPT proxy server running on port ${port}`)
236
+ })
237
+ }
238
+ }
239
+
240
+ export default ProxyManager
@@ -0,0 +1,154 @@
1
+ import ncp from 'copy-paste'
2
+ import colors from 'colors'
3
+ import { select } from '@inquirer/prompts'
4
+ import { AxiosError } from 'axios'
5
+
6
+ import ClovingGPT from '../cloving_gpt'
7
+ import { getGitDiff } from '../utils/git_utils'
8
+ import { generateReviewPrompt } from '../utils/prompt_utils'
9
+ import { getConfig } from '../utils/config_utils'
10
+ import StreamManager from './StreamManager'
11
+ import type { ClovingGPTOptions } from '../utils/types'
12
+
13
+ class ReviewManager extends StreamManager {
14
+ constructor(options: ClovingGPTOptions) {
15
+ super(options)
16
+ options.silent = getConfig(options).globalSilent || false
17
+ options.stream = true
18
+ this.gpt = new ClovingGPT(options)
19
+ }
20
+
21
+ private async getGitDiffPrompt(): Promise<string> {
22
+ const gitDiff = await getGitDiff()
23
+ return `${generateReviewPrompt(this.options, this.contextFiles)}
24
+
25
+ ## Diff Content
26
+ ${gitDiff}
27
+
28
+ # Task
29
+
30
+ ${this.options.prompt || 'Please provide a code review.'}`
31
+ }
32
+
33
+ private async handleUserAction(analysis: string) {
34
+ const extractSection = (section: string): string => {
35
+ const regex = new RegExp(
36
+ `## ${section}[\\s\\S]*?(?=\\n## Potential Bugs and Recommended Fixes|$)`,
37
+ 'g',
38
+ )
39
+ const match = analysis.match(regex)
40
+ return match ? match[0].trim() : ''
41
+ }
42
+
43
+ const clipboardOption = await select({
44
+ message: 'What would you like to copy to the clipboard?',
45
+ choices: [
46
+ { name: 'Copy only the Changes Overview', value: 'Changes Overview' },
47
+ {
48
+ name: 'Copy only the Potential Bugs and Recommended Fixes',
49
+ value: 'Potential Bugs and Recommended Fixes',
50
+ },
51
+ { name: 'Copy everything', value: 'Everything' },
52
+ { name: 'Done', value: 'Done' },
53
+ ],
54
+ })
55
+
56
+ let contentToCopy = ''
57
+
58
+ switch (clipboardOption) {
59
+ case 'Changes Overview':
60
+ contentToCopy = extractSection('Changes Overview')
61
+ break
62
+ case 'Potential Bugs and Recommended Fixes':
63
+ contentToCopy = extractSection('Potential Bugs and Recommended Fixes')
64
+ break
65
+ case 'Everything':
66
+ contentToCopy = analysis
67
+ break
68
+ case 'Done':
69
+ console.log('No content copied to clipboard.')
70
+ return
71
+ }
72
+
73
+ if (contentToCopy) {
74
+ ncp.copy(contentToCopy, (err) => {
75
+ if (err) {
76
+ console.error(colors.red('Error: Unable to copy to clipboard.'), err)
77
+ } else {
78
+ console.log(colors.green('Selected content copied to clipboard'))
79
+ }
80
+ })
81
+ }
82
+ }
83
+
84
+ public async generateReview(extraPrompt?: string): Promise<void> {
85
+ try {
86
+ await this.checkForLatestVersion()
87
+ await this.loadContextFiles()
88
+
89
+ if (this.options.files) {
90
+ if (this.chatHistory.length === 0) {
91
+ this.addUserPrompt(`${generateReviewPrompt(this.options, this.contextFiles)}`)
92
+ this.addAssistantResponse('What would you like to do?')
93
+ }
94
+ this.addUserPrompt(
95
+ `${this.options.prompt || 'Please provide a code review.'}\n\n${extraPrompt || ''}`,
96
+ )
97
+ } else {
98
+ if (this.chatHistory.length === 0) {
99
+ this.addUserPrompt(await this.getGitDiffPrompt())
100
+ this.addAssistantResponse('What would you like to do?')
101
+ }
102
+ this.addUserPrompt(
103
+ `${this.options.prompt || 'Please provide a code review.'}\n\n${extraPrompt || ''}`,
104
+ )
105
+ }
106
+
107
+ const responseStream = await this.gpt.streamText({
108
+ prompt: this.prompt,
109
+ messages: this.chatHistory,
110
+ })
111
+
112
+ this.handleResponseStream(responseStream)
113
+ } catch (error) {
114
+ this.handleError(error as AxiosError)
115
+ }
116
+ }
117
+
118
+ private handleError(error: AxiosError) {
119
+ let errorMessage = error.message || 'An error occurred.'
120
+ const errorNumber = error.response?.status || 'unknown'
121
+
122
+ switch (errorNumber) {
123
+ case 400:
124
+ errorMessage = 'Invalid model or prompt size too large. Try specifying fewer files.'
125
+ break
126
+ case 403:
127
+ errorMessage = 'Inactive subscription or usage limit reached'
128
+ break
129
+ case 429:
130
+ errorMessage = 'Rate limit error'
131
+ break
132
+ case 500:
133
+ errorMessage = 'Internal server error'
134
+ break
135
+ }
136
+
137
+ const statusMessage = (error.response?.data as any)?.statusMessage
138
+ console.error(
139
+ colors.red(
140
+ `\nError (${errorNumber}) while submitting the prompt to the AI API\n\n${statusMessage}\n`,
141
+ ),
142
+ )
143
+ this.isProcessing = false
144
+ }
145
+
146
+ protected async finalizeResponse(): Promise<void> {
147
+ this.addAssistantResponse(this.responseString)
148
+ this.isProcessing = false
149
+
150
+ await this.handleUserAction(this.responseString)
151
+ }
152
+ }
153
+
154
+ export default ReviewManager
@@ -0,0 +1,172 @@
1
+ import highlight from 'cli-highlight'
2
+ import ncp from 'copy-paste'
3
+ import { execSync } from 'child_process'
4
+ import { select, input } from '@inquirer/prompts'
5
+
6
+ import ClovingGPT from '../cloving_gpt'
7
+ import { generateShellPrompt } from '../utils/prompt_utils'
8
+ import { extractMarkdown } from '../utils/string_utils'
9
+ import { getConfig } from '../utils/config_utils'
10
+
11
+ import type { ClovingGPTOptions, ChatMessage } from '../utils/types'
12
+
13
+ /**
14
+ * ShellManager class for handling shell script generation and execution.
15
+ */
16
+ class ShellManager {
17
+ private gpt: ClovingGPT
18
+ private chatHistory: ChatMessage[] = []
19
+
20
+ /**
21
+ * Creates an instance of ShellManager.
22
+ * @param {ClovingGPTOptions} options - The options for ClovingGPT.
23
+ */
24
+ constructor(private options: ClovingGPTOptions) {
25
+ options.silent = getConfig(options).globalSilent || false
26
+ this.gpt = new ClovingGPT(options)
27
+ }
28
+
29
+ /**
30
+ * Generates a prompt to explain a shell script.
31
+ * @param {string} prompt - The original shell script prompt.
32
+ * @returns {string} The prompt for explaining the shell script.
33
+ * @private
34
+ */
35
+ private generateExplainShellPrompt(prompt: string): string {
36
+ return `${prompt}
37
+
38
+ # Task
39
+
40
+ Please briefly explain how this shell script works.`
41
+ }
42
+
43
+ /**
44
+ * Generates a shell script based on the given prompt.
45
+ * @param {string} prompt - The user's prompt for generating a shell script.
46
+ * @returns {Promise<string>} A promise that resolves to the generated shell script.
47
+ * @private
48
+ */
49
+ private async generateShell(prompt: string): Promise<string> {
50
+ if (this.chatHistory.length === 0) {
51
+ const systemPrompt = generateShellPrompt()
52
+ this.chatHistory.push({ role: 'user', content: systemPrompt })
53
+ this.chatHistory.push({ role: 'assistant', content: 'What would you like to do?' })
54
+ }
55
+ this.chatHistory.push({ role: 'user', content: prompt })
56
+ return await this.gpt.generateText({ prompt, messages: this.chatHistory })
57
+ }
58
+
59
+ /**
60
+ * Displays the generated shell script with syntax highlighting.
61
+ * @param {string} rawShellCommand - The raw shell command to display.
62
+ * @private
63
+ */
64
+ private displayGeneratedShell(rawShellCommand: string) {
65
+ const generatedShell = extractMarkdown(rawShellCommand)
66
+ const generatedShellWithoutShebang = generatedShell.replace(/^#!.*?\s/, '')
67
+ console.log(highlight(generatedShellWithoutShebang))
68
+ }
69
+
70
+ /**
71
+ * Handles user actions after generating a shell script.
72
+ * @param {string} response - The generated shell script.
73
+ * @param {string} prompt - The original user prompt.
74
+ * @returns {Promise<void>}
75
+ * @private
76
+ */
77
+ private async handleUserAction(response: string, prompt: string): Promise<void> {
78
+ let { exec } = this.options
79
+ this.chatHistory.push({ role: 'assistant', content: response })
80
+
81
+ const generatedShell = extractMarkdown(response)
82
+ const generatedShellWithoutShebang = generatedShell.replace(/^#!.*?\s/, '')
83
+
84
+ if (exec) {
85
+ execSync(generatedShellWithoutShebang, { stdio: 'inherit' })
86
+ return
87
+ }
88
+
89
+ const action = await select({
90
+ message: 'What would you like to do?',
91
+ choices: [
92
+ { name: 'Execute', value: 'execute' },
93
+ { name: 'Revise', value: 'revise' },
94
+ { name: 'Explain', value: 'explain' },
95
+ { name: 'Copy to Clipboard', value: 'copy' },
96
+ { name: 'Cancel', value: 'cancel' },
97
+ ],
98
+ })
99
+
100
+ switch (action) {
101
+ case 'execute':
102
+ execSync(generatedShellWithoutShebang, { stdio: 'inherit' })
103
+ break
104
+ case 'revise':
105
+ const newPrompt = await input({
106
+ message: 'How would you like to modify the output:',
107
+ })
108
+ const newRawShellCommand = await this.generateShell(newPrompt)
109
+ this.displayGeneratedShell(newRawShellCommand)
110
+ await this.handleUserAction(newRawShellCommand, newPrompt)
111
+ break
112
+ case 'explain':
113
+ const explainPrompt = this.generateExplainShellPrompt(generatedShellWithoutShebang)
114
+ this.chatHistory.push({ role: 'user', content: explainPrompt })
115
+ const explainShellCommand = await this.gpt.generateText({
116
+ prompt: explainPrompt,
117
+ messages: this.chatHistory,
118
+ })
119
+ console.log(highlight(explainShellCommand, { language: 'markdown' }))
120
+ break
121
+ case 'copy':
122
+ ncp.copy(generatedShellWithoutShebang, (err) => {
123
+ if (err) {
124
+ console.error('Error: Unable to copy to clipboard.', err)
125
+ } else {
126
+ console.log('Script copied to clipboard.')
127
+ }
128
+ })
129
+ break
130
+ case 'cancel':
131
+ console.log('Operation cancelled.')
132
+ break
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Generates a shell script based on user input and handles subsequent user actions.
138
+ *
139
+ * This method is the main entry point for generating and interacting with shell scripts.
140
+ * It performs the following steps:
141
+ * 1. Obtains a user prompt (either from options or by asking the user).
142
+ * 2. Generates a shell script based on the prompt.
143
+ * 3. Displays the generated script with syntax highlighting.
144
+ * 4. Handles user actions (execute, revise, explain, copy, or cancel) for the generated script.
145
+ *
146
+ * @returns {Promise<void>} A promise that resolves when the generation and handling process is complete.
147
+ * @throws {Error} If there's an issue during the shell script generation process.
148
+ * @public
149
+ *
150
+ * @example
151
+ * const shellManager = new ShellManager(options);
152
+ * await shellManager.generateAndHandleShell();
153
+ */
154
+ public async generateAndHandleShell(): Promise<void> {
155
+ let { prompt: userPrompt } = this.options
156
+ try {
157
+ if (!userPrompt) {
158
+ userPrompt = await input({
159
+ message: 'What would you like to do: ',
160
+ })
161
+ }
162
+
163
+ const rawShellCommand = await this.generateShell(userPrompt)
164
+ this.displayGeneratedShell(rawShellCommand)
165
+ await this.handleUserAction(rawShellCommand, userPrompt)
166
+ } catch (error) {
167
+ console.error('Could not generate shell script', error)
168
+ }
169
+ }
170
+ }
171
+
172
+ export default ShellManager