forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAITerminalChatPlugin.swift
More file actions
129 lines (113 loc) · 4.68 KB
/
AITerminalChatPlugin.swift
File metadata and controls
129 lines (113 loc) · 4.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import Environment
import Foundation
import OpenAIService
import Terminal
public actor AITerminalChatPlugin: ChatPlugin {
public static var command: String { "airun" }
public nonisolated var name: String { "AI Terminal" }
let chatGPTService: any ChatGPTServiceType
var terminal: TerminalType = Terminal()
var isCancelled = false
weak var delegate: ChatPluginDelegate?
var isStarted = false
var command: String?
public init(inside chatGPTService: any ChatGPTServiceType, delegate: ChatPluginDelegate) {
self.chatGPTService = chatGPTService
self.delegate = delegate
}
public func send(content: String) async {
if !isStarted {
isStarted = true
delegate?.pluginDidStart(self)
}
do {
if let command {
await chatGPTService.mutateHistory { history in
history.append(.init(role: .user, content: content))
}
delegate?.pluginDidStartResponding(self)
if try await checkConfirmation(content: content) {
delegate?.pluginDidEndResponding(self)
delegate?.pluginDidEnd(self)
delegate?.shouldStartAnotherPlugin(
TerminalChatPlugin.self,
withContent: command
)
} else {
delegate?.pluginDidEndResponding(self)
delegate?.pluginDidEnd(self)
await chatGPTService.mutateHistory { history in
history.append(.init(role: .assistant, content: "Cancelled"))
}
}
} else {
await chatGPTService.mutateHistory { history in
history.append(.init(role: .user, content: "Run a command to \(content)"))
}
delegate?.pluginDidStartResponding(self)
let result = try await generateCommand(task: content)
command = result
await chatGPTService.mutateHistory { history in
history.append(.init(role: .assistant, content: """
Confirm to run?
```
\(result)
```
"""))
}
delegate?.pluginDidEndResponding(self)
}
} catch {
await chatGPTService.mutateHistory { history in
history.append(.init(role: .assistant, content: error.localizedDescription))
}
delegate?.pluginDidEndResponding(self)
delegate?.pluginDidEnd(self)
}
}
public func cancel() async {
isCancelled = true
}
public func stopResponding() async {}
func callAIFunction(
function: String,
args: [Any?],
description: String
) async throws -> String {
let args = args.map { arg -> String in
if let arg = arg {
return String(describing: arg)
} else {
return "None"
}
}
let argsString = args.joined(separator: ", ")
let service = ChatGPTService(
systemPrompt: "You are now the following python function: ```# \(description)\n\(function)```\n\nOnly respond with your `return` value."
)
return try await service.sendAndWait(content: argsString)
}
func generateCommand(task: String) async throws -> String {
let f = "def generate_terminal_command(task: str) -> string:"
let d = """
Available environment variables:
- $PROJECT_ROOT: the root path of the project
- $FILE_PATH: the currently editing file
Current directory path is the project root.
The return value should not be embedded in a markdown code block.
Generate a terminal command to solve the given task on macOS. If one command is not enough, you can use && to concatenate multiple commands.
"""
return try await callAIFunction(function: f, args: [task], description: d)
.replacingOccurrences(of: "`", with: "")
.replacingOccurrences(of: "\n", with: "")
}
func checkConfirmation(content: String) async throws -> Bool {
let f = "def check_confirmation(content: str) -> bool:"
let d = """
Check if the given content is a phrase or sentence that considered a confirmation to run a command.
For example: "Yes", "Confirm", "True", "Please run it". It can be in any language.
"""
let result = try await callAIFunction(function: f, args: [content], description: d)
return result.lowercased().contains("true")
}
}