-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-executor.ts
More file actions
285 lines (266 loc) · 9.49 KB
/
Copy pathruntime-executor.ts
File metadata and controls
285 lines (266 loc) · 9.49 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import {
type AgentEvent,
type Effort,
type Mode,
type ReviewFinding,
type RuntimeHost,
type SessionManager,
type StoredMessage,
} from '@deepcode/core';
import { EFFORT_PARAMS } from '@deepcode/core/dist/providers/deepseek.js';
import type { CompletedItem, ThreadSnapshot } from '@deepcode/protocol';
import type { TurnExecutionArgs, TurnExecutionItem, TurnExecutor } from './server.js';
export interface RuntimeHostExecutorOptions {
createHost: (
cwd: string,
mode: Mode,
context: RuntimeHostCreationContext,
) => Promise<RuntimeHost | RuntimeHostLease> | RuntimeHost | RuntimeHostLease;
systemPrompt?: string;
model?: string;
sessionManager?: SessionManager;
}
export interface RuntimeHostCreationContext {
modeExplicit: boolean;
signal: AbortSignal;
requestApproval: (toolName: string, reason: string) => Promise<'allow' | 'deny' | 'always'>;
reviewAction: { kind: 'apply' | 'revert' } | null;
}
export interface RuntimeHostLease {
host: RuntimeHost;
systemPrompt?: string;
model?: string;
effort?: Effort;
diagnostics?: Array<{
source: string;
code: string;
severity: 'warning' | 'error';
message: string;
}>;
prepareUserMessage?: (text: string) => Promise<{
text: string;
diagnostics: Array<{
source: string;
code: string;
severity: 'warning' | 'error';
message: string;
}>;
}>;
close?: () => Promise<void> | void;
}
const DEFAULT_SYSTEM_PROMPT =
'You are DeepCode, an AI coding assistant powered by DeepSeek. Be concise and accurate.';
export class RuntimeHostExecutor implements TurnExecutor {
constructor(private readonly options: RuntimeHostExecutorOptions) {}
async execute(args: TurnExecutionArgs) {
const requestedMode = args.input.mode;
const modeExplicit = isMode(requestedMode);
const mode: Mode = modeExplicit ? requestedMode : 'default';
const reviewAction = readReviewAction(args.input.reviewAction);
const interactionItems: TurnExecutionItem[] = [];
const requestApproval = async (toolName: string, reason: string) => {
const decision = await args.requestApproval(toolName, reason);
interactionItems.push({
type: 'approval',
payload: { toolName, decision, reason },
});
return decision;
};
const created = await this.options.createHost(args.thread.cwd, mode, {
modeExplicit,
signal: args.signal,
requestApproval,
reviewAction,
});
const lease: RuntimeHostLease = 'host' in created ? created : { host: created };
try {
const history = historyFromThread(args.thread);
const baselineLength = history.length;
let text = typeof args.input.text === 'string' ? args.input.text : JSON.stringify(args.input);
for (const diagnostic of lease.diagnostics ?? []) {
interactionItems.push({ type: 'error', payload: diagnostic });
}
if (lease.prepareUserMessage) {
const prepared = await lease.prepareUserMessage(text);
text = prepared.text;
for (const diagnostic of prepared.diagnostics) {
interactionItems.push({ type: 'error', payload: diagnostic });
}
}
const streamingItemId = `${args.turn.id}-assistant`;
const events: AgentEvent[] = [];
const effort = parseEffort(args.input.effort ?? lease.effort);
const effortParams = EFFORT_PARAMS[effort];
const result = await lease.host.run({
cwd: args.thread.cwd,
systemPrompt: lease.systemPrompt ?? this.options.systemPrompt ?? DEFAULT_SYSTEM_PROMPT,
userMessage: text,
history,
model:
typeof args.input.model === 'string'
? args.input.model
: (lease.model ?? this.options.model ?? 'deepseek-chat'),
maxTokens: effortParams.maxTokens,
temperature: effortParams.temperature,
...(reviewAction?.kind === 'revert' ? { allowedTools: ['RestoreReviewAction'] } : {}),
signal: args.signal,
session: this.options.sessionManager
? { manager: this.options.sessionManager, id: args.thread.id, turnId: args.turn.id }
: undefined,
persistSessionMessages: false,
systemReminders: false,
approval: async (toolName, _input, verdict) => {
const decision = await requestApproval(
toolName,
verdict.reason ?? `Approve ${toolName}?`,
);
return decision === 'always' ? 'always' : decision === 'allow';
},
askUser: async (request) => {
const answer = await args.requestUserInput(request);
interactionItems.push({ type: 'ask_user', payload: { ...request, answer } });
return answer;
},
onEvent: (event) => {
events.push(event);
switch (event.type) {
case 'text_delta':
args.publishDelta(streamingItemId, event.text);
break;
case 'tool_use':
args.publishToolStarted(event.id, event.name, event.input);
break;
case 'tool_result':
args.publishToolCompleted(event.id, event.result);
break;
case 'usage':
args.publishUsage({
inputTokens: event.inputTokens,
outputTokens: event.outputTokens,
reasoningTokens: event.reasoningTokens,
cacheReadTokens: event.cacheReadTokens,
});
break;
}
},
});
const newMessages = result.history.slice(baselineLength);
const items = [
...interactionItems,
...reviewFindingsFromEvents(events),
...completedItemsFromMessages(newMessages, text),
];
if (result.stopReason === 'error') {
const error = [...events].reverse().find((event) => event.type === 'error');
if (error?.type === 'error') {
items.push({ type: 'error', payload: { message: error.error } });
}
}
return {
items,
status: result.stopReason === 'error' ? ('failed' as const) : ('completed' as const),
};
} finally {
await lease.close?.();
}
}
}
function readReviewAction(value: unknown): { kind: 'apply' | 'revert' } | null {
if (!value || typeof value !== 'object') return null;
const kind = (value as { kind?: unknown }).kind;
return kind === 'apply' || kind === 'revert' ? { kind } : null;
}
export function reviewFindingsFromEvents(events: AgentEvent[]): TurnExecutionItem[] {
const calls = new Map<string, Record<string, unknown>>();
const items: TurnExecutionItem[] = [];
for (const event of events) {
if (event.type === 'tool_use' && event.name === 'SubmitReviewFinding') {
calls.set(event.id, event.input);
} else if (event.type === 'tool_result' && calls.has(event.id) && !event.result.isError) {
const finding = event.result.data?.finding;
if (isReviewFinding(finding)) {
items.push({
type: 'review_finding',
payload: { findingId: event.id, ...finding },
});
}
calls.delete(event.id);
}
}
return items;
}
function isReviewFinding(value: unknown): value is ReviewFinding {
if (!value || typeof value !== 'object') return false;
const finding = value as Partial<ReviewFinding>;
return (
typeof finding.title === 'string' &&
typeof finding.body === 'string' &&
typeof finding.path === 'string' &&
Number.isInteger(finding.startLine) &&
Number.isInteger(finding.endLine) &&
Number.isInteger(finding.priority)
);
}
const MODES = new Set<Mode>([
'default',
'acceptEdits',
'plan',
'auto',
'dontAsk',
'bypassPermissions',
]);
const EFFORTS = new Set<Effort>(['low', 'medium', 'high', 'xhigh', 'max']);
function isMode(value: unknown): value is Mode {
return typeof value === 'string' && MODES.has(value as Mode);
}
function parseEffort(value: unknown): Effort {
return typeof value === 'string' && EFFORTS.has(value as Effort) ? (value as Effort) : 'high';
}
export function historyFromThread(thread: ThreadSnapshot): StoredMessage[] {
const history: StoredMessage[] = [];
for (const turn of thread.turns) {
for (const item of turn.items) {
const message = messageFromItem(item);
if (message) history.push(message);
}
}
return history;
}
function messageFromItem(item: CompletedItem): StoredMessage | null {
if (item.type === 'user_message' && typeof item.payload.text === 'string') {
return { role: 'user', content: [{ type: 'text', text: item.payload.text }] };
}
const message = item.payload.message;
if (!isStoredMessage(message)) return null;
return message;
}
function completedItemsFromMessages(
messages: StoredMessage[],
inputText: string,
): TurnExecutionItem[] {
const items: TurnExecutionItem[] = [];
for (const [index, message] of messages.entries()) {
if (index === 0 && isMatchingInputMessage(message, inputText)) continue;
items.push({
type: message.role === 'assistant' ? 'assistant_message' : 'tool_result',
payload: { message },
});
}
return items;
}
function isMatchingInputMessage(message: StoredMessage, text: string): boolean {
return (
message.role === 'user' &&
message.content.length === 1 &&
message.content[0]?.type === 'text' &&
message.content[0].text === text
);
}
function isStoredMessage(value: unknown): value is StoredMessage {
if (typeof value !== 'object' || value === null) return false;
const candidate = value as Partial<StoredMessage>;
return (
(candidate.role === 'user' || candidate.role === 'assistant') &&
Array.isArray(candidate.content)
);
}