-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessageEnhancer.ts
More file actions
144 lines (130 loc) · 4.59 KB
/
Copy pathmessageEnhancer.ts
File metadata and controls
144 lines (130 loc) · 4.59 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import { ProviderSettings, ShoferMessage, GlobalState, TelemetryEventName } from "@shofer/types"
import { TelemetryService } from "@shofer/telemetry"
import { supportPrompt } from "@shofer/types"
import { singleCompletionHandler } from "../../utils/single-completion-handler"
import { ProviderSettingsManager } from "../config/ProviderSettingsManager"
import { ShoferProvider } from "./ShoferProvider"
import { webviewLog } from "@shofer/core"
export interface MessageEnhancerOptions {
text: string
apiConfiguration: ProviderSettings
customSupportPrompts?: Record<string, any>
listApiConfigMeta: Array<{ id: string; name?: string }>
enhancementApiConfigId?: string
includeTaskHistoryInEnhance?: boolean
currentShoferMessages?: ShoferMessage[]
providerSettingsManager: ProviderSettingsManager
}
export interface MessageEnhancerResult {
success: boolean
enhancedText?: string
error?: string
}
/**
* Enhances a message prompt using AI, optionally including task history for context
*/
export class MessageEnhancer {
/**
* Enhances a message prompt using the configured AI provider
* @param options Configuration options for message enhancement
* @returns Enhanced message result with success status
*/
static async enhanceMessage(options: MessageEnhancerOptions): Promise<MessageEnhancerResult> {
try {
const {
text,
apiConfiguration,
customSupportPrompts,
listApiConfigMeta,
enhancementApiConfigId,
includeTaskHistoryInEnhance,
currentShoferMessages,
providerSettingsManager,
} = options
// Determine which API configuration to use
let configToUse: ProviderSettings = apiConfiguration
// Try to get enhancement config first, fall back to current config
if (enhancementApiConfigId && listApiConfigMeta.find(({ id }) => id === enhancementApiConfigId)) {
const { name: _, ...providerSettings } = await providerSettingsManager.getProfile({
id: enhancementApiConfigId,
})
if (providerSettings.apiProvider) {
configToUse = providerSettings
}
}
// Prepare the prompt to enhance
let promptToEnhance = text
// Include task history if enabled and available
if (includeTaskHistoryInEnhance && currentShoferMessages && currentShoferMessages.length > 0) {
const taskHistory = this.extractTaskHistory(currentShoferMessages)
if (taskHistory) {
promptToEnhance = `${text}\n\nUse the following previous conversation context as needed:\n${taskHistory}`
}
}
// Create the enhancement prompt using the support prompt system
const enhancementPrompt = supportPrompt.create(
"ENHANCE",
{ userInput: promptToEnhance },
customSupportPrompts,
)
// Call the single completion handler to get the enhanced prompt
const enhancedText = await singleCompletionHandler(configToUse, enhancementPrompt)
return {
success: true,
enhancedText,
}
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
}
}
}
/**
* Extracts relevant task history from Shofer messages for context
* @param messages Array of Shofer messages
* @returns Formatted task history string
*/
private static extractTaskHistory(messages: ShoferMessage[]): string {
try {
const relevantMessages = messages
.filter((msg) => {
// Include user messages (type: "ask" with text) and assistant messages (type: "say" with say: "text")
if (msg.type === "ask" && msg.text) {
return true
}
if (msg.type === "say" && msg.say === "text" && msg.text) {
return true
}
return false
})
.slice(-10) // Limit to last 10 messages to avoid context explosion
return relevantMessages
.map((msg) => {
const role = msg.type === "ask" ? "User" : "Assistant"
const content = msg.text || ""
// Truncate long messages
return `${role}: ${content.slice(0, 500)}${content.length > 500 ? "..." : ""}`
})
.join("\n")
} catch (error) {
// Log error but don't fail the enhancement
webviewLog.error("Failed to extract task history:", error)
return ""
}
}
/**
* Captures telemetry for prompt enhancement
* @param taskId Optional task ID for telemetry tracking
* @param includeTaskHistory Whether task history was included in the enhancement
*/
static captureTelemetry(taskId?: string, includeTaskHistory?: boolean): void {
if (TelemetryService.hasInstance()) {
// Use captureEvent directly to include the includeTaskHistory property
TelemetryService.instance.captureEvent(TelemetryEventName.PROMPT_ENHANCED, {
...(taskId && { taskId }),
includeTaskHistory: includeTaskHistory ?? false,
})
}
}
}