@thegitai/cli 1.0.0-preview.6 → 1.0.0-preview.60
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.
- package/README.md +229 -7
- package/dist/bin/ai.js +140 -111
- package/dist/bin/browser-host.js +265 -0
- package/dist/src/agent-mode.js +32 -7
- package/dist/src/api/auth.js +8 -2
- package/dist/src/api/browser-login.js +147 -35
- package/dist/src/api/chat.js +691 -166
- package/dist/src/api/contracts.js +55 -1
- package/dist/src/api/default-host.js +1 -0
- package/dist/src/api/http.js +139 -8
- package/dist/src/api/models.js +34 -9
- package/dist/src/api/startup-handshake.js +36 -0
- package/dist/src/api/turn-recovery.js +189 -0
- package/dist/src/background-jobs.js +8 -2
- package/dist/src/browser/bridge.js +262 -0
- package/dist/src/browser/framing.js +42 -0
- package/dist/src/browser/native-host.js +219 -0
- package/dist/src/browser/protocol.js +46 -0
- package/dist/src/browser/session-bridge.js +130 -0
- package/dist/src/cli-args.js +19 -5
- package/dist/src/client-environment.js +2 -0
- package/dist/src/core/clipboard.js +7 -13
- package/dist/src/core/image-limits.js +56 -0
- package/dist/src/core/image-path-extractor.js +70 -3
- package/dist/src/core/session-image-store.js +246 -0
- package/dist/src/edit-journal.js +33 -2
- package/dist/src/executor.js +25 -3
- package/dist/src/help-text.js +128 -22
- package/dist/src/job-follow-up.js +40 -0
- package/dist/src/mcp-client.js +335 -0
- package/dist/src/mcp-command.js +176 -0
- package/dist/src/mcp-config.js +123 -0
- package/dist/src/mcp-sdk.js +3 -0
- package/dist/src/mcp-types.js +26 -0
- package/dist/src/patcher.js +43 -4
- package/dist/src/permissions.js +301 -0
- package/dist/src/preferences.js +39 -0
- package/dist/src/project-key.js +11 -0
- package/dist/src/project-model-preferences.js +74 -0
- package/dist/src/quota-notice.js +35 -0
- package/dist/src/reasoning-effort.js +27 -0
- package/dist/src/session-safety.js +0 -12
- package/dist/src/session-store.js +123 -30
- package/dist/src/session.js +20 -4
- package/dist/src/signin.js +58 -0
- package/dist/src/tool-executor.js +23 -49
- package/dist/src/tools/browser.js +641 -0
- package/dist/src/tools/delete-file.js +20 -4
- package/dist/src/tools/index.js +32 -10
- package/dist/src/tools/patch-file.js +12 -26
- package/dist/src/tools/read-file.js +5 -0
- package/dist/src/tools/read-image-file.js +85 -0
- package/dist/src/tools/replace-document-text.js +28 -18
- package/dist/src/tools/restore-checkpoint.js +0 -1
- package/dist/src/tools/run-command.js +14 -71
- package/dist/src/tools/run-node-script.js +12 -81
- package/dist/src/tools/save-generated-image.js +120 -0
- package/dist/src/tools/str-replace.js +12 -26
- package/dist/src/tools/undo-edit.js +1 -6
- package/dist/src/tools/write-file.js +67 -11
- package/dist/src/ui/prompt-history-store.js +1 -1
- package/dist/src/ui/repl.js +1017 -299
- package/dist/src/ui/slash-commands.js +122 -0
- package/dist/src/ui/tui/attention.js +25 -0
- package/dist/src/ui/tui/bridge.js +38 -5
- package/dist/src/ui/tui/build-frame.js +807 -270
- package/dist/src/ui/tui/composer-layout.js +76 -0
- package/dist/src/ui/tui/desktop-notification.js +118 -0
- package/dist/src/ui/tui/markdown-render.js +21 -11
- package/dist/src/ui/tui/model-label.js +13 -0
- package/dist/src/ui/tui/shell-input.js +275 -73
- package/dist/src/ui/tui/shortcuts.js +61 -0
- package/dist/src/ui/tui/terminal-theme.js +28 -0
- package/dist/src/ui/tui/text.js +31 -6
- package/dist/src/ui/tui/user-input.js +593 -0
- package/dist/src/update-check.js +205 -0
- package/dist/src/usage-notice.js +52 -0
- package/dist/src/usage.js +5 -2
- package/dist/src/utils.js +13 -0
- package/dist/src/version.js +52 -2
- package/dist/vendor/mcp/LICENSES.txt +414 -0
- package/dist/vendor/mcp/client.cjs +82 -0
- package/package.json +22 -9
- package/dist/src/project-index.js +0 -233
- package/dist/src/tools/code-intel.js +0 -472
- package/dist/src/tools/find-symbol.js +0 -70
- package/dist/src/tools/hover-symbol.js +0 -95
- package/dist/src/tools/list-symbols.js +0 -55
- package/dist/src/tools/search-code.js +0 -37
- package/dist/src/tools/signature-help.js +0 -118
package/dist/src/api/chat.js
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
|
+
import { sessionMcp } from '../mcp-client.js';
|
|
2
|
+
import { readProjectModelEfforts, projectModelEffort } from '../project-model-preferences.js';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
1
4
|
import { drainBackgroundJobNotifications } from '../background-jobs.js';
|
|
5
|
+
import { cancelActiveCommand } from '../executor.js';
|
|
2
6
|
import { createPromptCheckpoint, sanitizeSessionSafetyForServer, } from '../session-safety.js';
|
|
3
|
-
import { applySessionSnapshot, snapshotFromSession, } from '../session-store.js';
|
|
7
|
+
import { applySessionSnapshot, saveSessionState, snapshotFromSession, } from '../session-store.js';
|
|
4
8
|
import { executeLocalToolCall } from '../tool-executor.js';
|
|
5
|
-
import {
|
|
9
|
+
import { saveGeneratedImage } from '../tools/save-generated-image.js';
|
|
10
|
+
import { isUserInputQuestionArray } from './contracts.js';
|
|
11
|
+
import { createTraceContext, gatewayFailureCategory, normalizeServerUrl, QUOTA_EXCEEDED_CODE, readErrorResponse, ServerApiError, transportFailureDetail, } from './http.js';
|
|
12
|
+
import { createTurnRecovery, fetchTurnAttempt, interruptedStream, isRetryableTurnStatus, isTurnRecoveryExhausted, readTurnChunk, } from './turn-recovery.js';
|
|
6
13
|
import { collectClientEnvironment } from '../client-environment.js';
|
|
7
14
|
import { collectProjectOrientation } from '../project-orientation.js';
|
|
15
|
+
import { describeSessionImageStore } from '../core/session-image-store.js';
|
|
8
16
|
import { autoAttachImages } from '../core/image-path-extractor.js';
|
|
9
17
|
import { formatTurnFailureMarker } from '../turn-failure-marker.js';
|
|
18
|
+
import { browserExtensionSeen, releaseBrowserAfterTurn } from '../browser/session-bridge.js';
|
|
10
19
|
export class TurnCancelledError extends Error {
|
|
11
20
|
name = 'TurnCancelledError';
|
|
12
21
|
constructor(message = 'Turn cancelled.') {
|
|
@@ -18,11 +27,13 @@ export class ChatTurnFailedError extends Error {
|
|
|
18
27
|
category;
|
|
19
28
|
retryable;
|
|
20
29
|
traceId;
|
|
21
|
-
|
|
30
|
+
partialSnapshot;
|
|
31
|
+
constructor(message, category = 'unknown_error', retryable = false, traceId = '', partialSnapshot) {
|
|
22
32
|
super(traceId ? `${message}\nTrace ID: ${traceId}` : message);
|
|
23
33
|
this.category = category;
|
|
24
34
|
this.retryable = retryable;
|
|
25
35
|
this.traceId = traceId;
|
|
36
|
+
this.partialSnapshot = partialSnapshot;
|
|
26
37
|
}
|
|
27
38
|
}
|
|
28
39
|
export function isTurnCancelledError(error) {
|
|
@@ -32,8 +43,13 @@ export function isTurnCancelledError(error) {
|
|
|
32
43
|
}
|
|
33
44
|
function parseSseBlock(block) {
|
|
34
45
|
let event = 'message';
|
|
46
|
+
let id = '';
|
|
35
47
|
const dataLines = [];
|
|
36
48
|
for (const line of block.split(/\r?\n/)) {
|
|
49
|
+
if (line.startsWith('id:')) {
|
|
50
|
+
id = line.slice(3).trim();
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
37
53
|
if (line.startsWith('event:')) {
|
|
38
54
|
event = line.slice('event:'.length).trim() || event;
|
|
39
55
|
continue;
|
|
@@ -46,10 +62,10 @@ function parseSseBlock(block) {
|
|
|
46
62
|
return null;
|
|
47
63
|
const text = dataLines.join('\n');
|
|
48
64
|
try {
|
|
49
|
-
return { event, data: JSON.parse(text) };
|
|
65
|
+
return { id, event, data: JSON.parse(text) };
|
|
50
66
|
}
|
|
51
67
|
catch {
|
|
52
|
-
|
|
68
|
+
throw new Error('Server emitted invalid event JSON.');
|
|
53
69
|
}
|
|
54
70
|
}
|
|
55
71
|
let toolStateSeqCounter = 0;
|
|
@@ -86,7 +102,7 @@ export function preserveCancelledTurnInput(session, input) {
|
|
|
86
102
|
return;
|
|
87
103
|
for (let i = session.history.length - 1; i >= 0; i--) {
|
|
88
104
|
const entry = session.history[i];
|
|
89
|
-
if (!entry || entry.role !== 'user')
|
|
105
|
+
if (!entry || entry.role !== 'user' || entry.kind === 'userInterjection')
|
|
90
106
|
continue;
|
|
91
107
|
const prior = userHistoryText(entry);
|
|
92
108
|
if (!prior)
|
|
@@ -95,24 +111,46 @@ export function preserveCancelledTurnInput(session, input) {
|
|
|
95
111
|
return;
|
|
96
112
|
break;
|
|
97
113
|
}
|
|
98
|
-
session.history.push({
|
|
114
|
+
session.history.push({
|
|
115
|
+
role: 'user',
|
|
116
|
+
parts: [{ text }],
|
|
117
|
+
kind: 'turnStart',
|
|
118
|
+
userInput: text,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
function appendTurnFailureMarker(session, category) {
|
|
122
|
+
session.history.push({
|
|
123
|
+
role: 'model',
|
|
124
|
+
parts: [{ text: formatTurnFailureMarker(category) }],
|
|
125
|
+
});
|
|
99
126
|
}
|
|
100
127
|
function preserveFailedTurnInput(session, input, category) {
|
|
101
128
|
const text = input.trim();
|
|
102
129
|
if (!text)
|
|
103
130
|
return;
|
|
104
|
-
session.history.push({ role: 'user', parts: [{ text }], kind: 'turnStart' });
|
|
105
131
|
session.history.push({
|
|
106
|
-
role: '
|
|
107
|
-
parts: [{ text
|
|
132
|
+
role: 'user',
|
|
133
|
+
parts: [{ text }],
|
|
134
|
+
kind: 'turnStart',
|
|
135
|
+
userInput: text,
|
|
108
136
|
});
|
|
137
|
+
appendTurnFailureMarker(session, category);
|
|
109
138
|
}
|
|
110
|
-
function
|
|
111
|
-
return
|
|
139
|
+
function tagTurnPhase(phase, run) {
|
|
140
|
+
return run().catch((error) => {
|
|
141
|
+
if (error && typeof error === 'object' && !error.thegitaiPhase) {
|
|
142
|
+
error.thegitaiPhase = phase;
|
|
143
|
+
}
|
|
144
|
+
throw error;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function turnPhaseOf(error) {
|
|
148
|
+
const phase = error?.thegitaiPhase;
|
|
149
|
+
return typeof phase === 'string' ? phase : null;
|
|
112
150
|
}
|
|
113
151
|
function preserveCancelledTurnToolResult(session, input, event, result) {
|
|
114
152
|
const callId = String(event.call.id ?? '').trim();
|
|
115
|
-
if (!callId
|
|
153
|
+
if (!callId)
|
|
116
154
|
return;
|
|
117
155
|
preserveCancelledTurnInput(session, input);
|
|
118
156
|
session.history.push({
|
|
@@ -132,6 +170,22 @@ function preserveCancelledTurnToolResult(session, input, event, result) {
|
|
|
132
170
|
],
|
|
133
171
|
});
|
|
134
172
|
}
|
|
173
|
+
const turnInterjections = new Map();
|
|
174
|
+
function preserveTurnInterjection(session, input, sent) {
|
|
175
|
+
sent.delivered = true;
|
|
176
|
+
preserveCancelledTurnInput(session, input);
|
|
177
|
+
session.history.push({
|
|
178
|
+
role: 'user',
|
|
179
|
+
parts: [{ text: sent.text }],
|
|
180
|
+
kind: 'userInterjection',
|
|
181
|
+
userInput: sent.text,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
function preserveTurnAnswer(session, input, requestId, questions, result) {
|
|
185
|
+
preserveCancelledTurnInput(session, input);
|
|
186
|
+
session.history.push({ role: 'model', parts: [{ userInputRequest: { requestId, questions } }] });
|
|
187
|
+
session.history.push({ role: 'user', parts: [{ userInputResult: { requestId, result } }] });
|
|
188
|
+
}
|
|
135
189
|
function publicStatusMessage(data) {
|
|
136
190
|
if (!data || typeof data !== 'object')
|
|
137
191
|
return null;
|
|
@@ -145,11 +199,19 @@ function publicStatusMessage(data) {
|
|
|
145
199
|
? event.toolName
|
|
146
200
|
: 'tool';
|
|
147
201
|
if (event.phase === 'thinking')
|
|
148
|
-
return '
|
|
202
|
+
return 'Exploring options...';
|
|
203
|
+
if (event.phase === 'analyzing_image') {
|
|
204
|
+
return (event.imageCount ?? 1) > 1 ? 'Analyzing images...' : 'Analyzing image...';
|
|
205
|
+
}
|
|
206
|
+
if (event.phase === 'generating_image') {
|
|
207
|
+
return 'Generating image...';
|
|
208
|
+
}
|
|
149
209
|
if (event.phase === 'running_tool')
|
|
150
210
|
return `Running ${toolName}...`;
|
|
151
211
|
if (event.phase === 'waiting_for_tool')
|
|
152
212
|
return `Running ${toolName} locally...`;
|
|
213
|
+
if (event.phase === 'waiting_for_user_input')
|
|
214
|
+
return 'Waiting for your input...';
|
|
153
215
|
return null;
|
|
154
216
|
}
|
|
155
217
|
function normalizeShellJobToolCall(call) {
|
|
@@ -181,15 +243,33 @@ function normalizeShellJobToolCall(call) {
|
|
|
181
243
|
}
|
|
182
244
|
return changed ? { ...call, args } : call;
|
|
183
245
|
}
|
|
184
|
-
|
|
246
|
+
function createTurnRequester({ fetchImpl, recovery, signal, traceId, }) {
|
|
247
|
+
return (operation, url, init) => {
|
|
248
|
+
const caller = init.signal ? AbortSignal.any([signal, init.signal]) : signal;
|
|
249
|
+
return tagTurnPhase(operation, () => recovery.run(operation, async () => {
|
|
250
|
+
const response = await fetchTurnAttempt(fetchImpl, url, init, caller, {
|
|
251
|
+
readBody: true,
|
|
252
|
+
});
|
|
253
|
+
if (isRetryableTurnStatus(response.status)) {
|
|
254
|
+
throw await readErrorResponse(response, traceId);
|
|
255
|
+
}
|
|
256
|
+
return response;
|
|
257
|
+
}, caller));
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
function turnUrl(config, turnId, action) {
|
|
261
|
+
return `${normalizeServerUrl(config.serverUrl)}/v1/chat/turn/${encodeURIComponent(turnId)}/${action}`;
|
|
262
|
+
}
|
|
263
|
+
async function postToolResult({ config, turnId, event, result, session, request, traceId, delivery, }) {
|
|
185
264
|
const payload = {
|
|
265
|
+
executionId: event.executionId,
|
|
186
266
|
toolCallId: event.call.id,
|
|
187
267
|
result,
|
|
188
268
|
toolState: toolStateFromSession(session),
|
|
189
269
|
toolStateSeq: ++toolStateSeqCounter,
|
|
190
270
|
};
|
|
191
271
|
const trace = createTraceContext(traceId);
|
|
192
|
-
const response = await
|
|
272
|
+
const response = await request('posting a tool result', turnUrl(config, turnId, 'tool-result'), {
|
|
193
273
|
method: 'POST',
|
|
194
274
|
headers: {
|
|
195
275
|
authorization: `Bearer ${config.token}`,
|
|
@@ -197,13 +277,87 @@ async function postToolResult({ config, turnId, event, result, session, fetchImp
|
|
|
197
277
|
...trace.headers,
|
|
198
278
|
},
|
|
199
279
|
body: JSON.stringify(payload),
|
|
280
|
+
signal: delivery,
|
|
200
281
|
});
|
|
201
|
-
if (response.status === 410)
|
|
282
|
+
if (response.status === 410)
|
|
202
283
|
return;
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
async function postUserInputResult({ config, turnId, requestId, result, request, traceId, delivery, }) {
|
|
289
|
+
const payload = {
|
|
290
|
+
requestId,
|
|
291
|
+
result,
|
|
292
|
+
};
|
|
293
|
+
const trace = createTraceContext(traceId);
|
|
294
|
+
const response = await request('posting your answer', turnUrl(config, turnId, 'user-input-result'), {
|
|
295
|
+
method: 'POST',
|
|
296
|
+
headers: {
|
|
297
|
+
authorization: `Bearer ${config.token}`,
|
|
298
|
+
'content-type': 'application/json',
|
|
299
|
+
...trace.headers,
|
|
300
|
+
},
|
|
301
|
+
body: JSON.stringify(payload),
|
|
302
|
+
signal: delivery,
|
|
303
|
+
});
|
|
304
|
+
if (response.status === 410)
|
|
305
|
+
return;
|
|
306
|
+
if (!response.ok) {
|
|
307
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const activeTurnRequesters = new Map();
|
|
311
|
+
export async function postInterjection({ config, turnId, text, messageId, imageAttachments = [], fetchImpl = globalThis.fetch, traceId, }) {
|
|
312
|
+
const payload = {
|
|
313
|
+
text,
|
|
314
|
+
messageId,
|
|
315
|
+
...(imageAttachments.length > 0 ? { imageAttachments } : {}),
|
|
316
|
+
};
|
|
317
|
+
const trace = createTraceContext(traceId);
|
|
318
|
+
const url = turnUrl(config, turnId, 'interject');
|
|
319
|
+
const init = {
|
|
320
|
+
method: 'POST',
|
|
321
|
+
headers: {
|
|
322
|
+
authorization: `Bearer ${config.token}`,
|
|
323
|
+
'content-type': 'application/json',
|
|
324
|
+
...trace.headers,
|
|
325
|
+
},
|
|
326
|
+
body: JSON.stringify(payload),
|
|
327
|
+
};
|
|
328
|
+
const request = activeTurnRequesters.get(turnId);
|
|
329
|
+
const sent = turnInterjections.get(turnId);
|
|
330
|
+
const record = {
|
|
331
|
+
messageId,
|
|
332
|
+
text,
|
|
333
|
+
hasImages: imageAttachments.length > 0,
|
|
334
|
+
delivered: false,
|
|
335
|
+
};
|
|
336
|
+
sent?.push(record);
|
|
337
|
+
const forget = () => {
|
|
338
|
+
const index = sent?.indexOf(record) ?? -1;
|
|
339
|
+
if (index !== -1)
|
|
340
|
+
sent.splice(index, 1);
|
|
341
|
+
};
|
|
342
|
+
let response;
|
|
343
|
+
try {
|
|
344
|
+
response = request
|
|
345
|
+
? await request('posting a message into the turn', url, init)
|
|
346
|
+
: await fetchImpl(url, init);
|
|
347
|
+
}
|
|
348
|
+
catch (error) {
|
|
349
|
+
forget();
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
if (response.status === 410) {
|
|
353
|
+
forget();
|
|
354
|
+
return 'stale';
|
|
203
355
|
}
|
|
204
356
|
if (!response.ok) {
|
|
357
|
+
forget();
|
|
205
358
|
throw await readErrorResponse(response, trace.traceId);
|
|
206
359
|
}
|
|
360
|
+
return 'delivered';
|
|
207
361
|
}
|
|
208
362
|
const turnIdOverrides = new WeakMap();
|
|
209
363
|
function enterServerTurnId(session, serverSessionTurnId) {
|
|
@@ -228,14 +382,13 @@ function exitServerTurnId(session) {
|
|
|
228
382
|
turnIdOverrides.delete(session);
|
|
229
383
|
}
|
|
230
384
|
}
|
|
231
|
-
async function executeAndPostToolResult({ config,
|
|
385
|
+
async function executeAndPostToolResult({ config, session, event, input, request, signal, delivery, executed, traceId, }) {
|
|
232
386
|
const turnId = String(event?.turnId ?? '').trim();
|
|
233
|
-
if (!turnId || !event?.call?.id || !event.call.name) {
|
|
387
|
+
if (!turnId || !event?.executionId || !event?.call?.id || !event.call.name) {
|
|
234
388
|
throw new Error('Server emitted an invalid tool-call event.');
|
|
235
389
|
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
390
|
+
signal.throwIfAborted();
|
|
391
|
+
delivery.throwIfAborted();
|
|
239
392
|
const serverSessionTurnId = String(event.sessionTurnId ?? '').trim();
|
|
240
393
|
if (serverSessionTurnId) {
|
|
241
394
|
enterServerTurnId(session, serverSessionTurnId);
|
|
@@ -245,19 +398,28 @@ async function executeAndPostToolResult({ config, projectIndex, session, event,
|
|
|
245
398
|
}
|
|
246
399
|
try {
|
|
247
400
|
const call = normalizeShellJobToolCall(event.call);
|
|
248
|
-
const rawResult =
|
|
401
|
+
const rawResult = event.generatedImage
|
|
402
|
+
? saveGeneratedImage({
|
|
403
|
+
base64Data: event.generatedImage.base64Data,
|
|
404
|
+
mimeType: event.generatedImage.mimeType,
|
|
405
|
+
suggestedFilename: event.generatedImage.suggestedFilename ||
|
|
406
|
+
String(call.args?.filename ?? call.args?.file_name ?? ''),
|
|
407
|
+
})
|
|
408
|
+
: await executeLocalToolCall(session, call);
|
|
249
409
|
preserveCancelledTurnToolResult(session, input, { ...event, call }, rawResult);
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
410
|
+
executed();
|
|
411
|
+
signal.throwIfAborted();
|
|
412
|
+
if (delivery.aborted)
|
|
413
|
+
return;
|
|
253
414
|
await postToolResult({
|
|
254
415
|
config,
|
|
255
416
|
turnId,
|
|
256
417
|
event,
|
|
257
418
|
result: rawResult,
|
|
258
419
|
session,
|
|
259
|
-
|
|
420
|
+
request,
|
|
260
421
|
traceId,
|
|
422
|
+
delivery,
|
|
261
423
|
});
|
|
262
424
|
}
|
|
263
425
|
finally {
|
|
@@ -266,142 +428,316 @@ async function executeAndPostToolResult({ config, projectIndex, session, event,
|
|
|
266
428
|
}
|
|
267
429
|
}
|
|
268
430
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
431
|
+
function createTurnWork() {
|
|
432
|
+
const executions = new Map();
|
|
433
|
+
const inFlight = new Set();
|
|
434
|
+
const running = new Set();
|
|
435
|
+
let lastSerial = Promise.resolve();
|
|
436
|
+
let hasFailed = false;
|
|
437
|
+
let rejectFailed;
|
|
438
|
+
const failed = new Promise((_, reject) => {
|
|
439
|
+
rejectFailed = reject;
|
|
440
|
+
});
|
|
441
|
+
failed.catch(() => { });
|
|
442
|
+
function dispatch(key, parallel, run) {
|
|
443
|
+
if (executions.has(key))
|
|
444
|
+
return;
|
|
445
|
+
const prior = parallel ? lastSerial : Promise.all([lastSerial, ...inFlight]);
|
|
446
|
+
let executed;
|
|
447
|
+
const local = new Promise((resolve) => {
|
|
448
|
+
executed = resolve;
|
|
449
|
+
});
|
|
450
|
+
running.add(local);
|
|
451
|
+
void local.then(() => running.delete(local));
|
|
452
|
+
const execution = prior.then(() => run(executed));
|
|
453
|
+
execution.then(executed, executed);
|
|
454
|
+
executions.set(key, execution);
|
|
455
|
+
inFlight.add(execution);
|
|
456
|
+
if (!parallel)
|
|
457
|
+
lastSerial = execution;
|
|
458
|
+
execution.then(() => inFlight.delete(execution), (error) => {
|
|
459
|
+
inFlight.delete(execution);
|
|
460
|
+
hasFailed = true;
|
|
461
|
+
rejectFailed(error);
|
|
462
|
+
});
|
|
272
463
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
464
|
+
return {
|
|
465
|
+
dispatch,
|
|
466
|
+
failed,
|
|
467
|
+
get hasFailed() {
|
|
468
|
+
return hasFailed;
|
|
469
|
+
},
|
|
470
|
+
async executed() {
|
|
471
|
+
await Promise.all([...running]);
|
|
472
|
+
},
|
|
473
|
+
async settled() {
|
|
474
|
+
await Promise.allSettled([...inFlight]);
|
|
475
|
+
},
|
|
278
476
|
};
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
function recordParallelFailure(error) {
|
|
287
|
-
const failure = error ?? new Error('Local tool execution failed.');
|
|
288
|
-
if (firstParallelFailure == null) {
|
|
289
|
-
firstParallelFailure = failure;
|
|
290
|
-
rejectOnParallelFailure?.(failure);
|
|
291
|
-
}
|
|
292
|
-
return failure;
|
|
477
|
+
}
|
|
478
|
+
function terminalFailure(event, traceId) {
|
|
479
|
+
const data = (event.data ?? {});
|
|
480
|
+
const message = String(data.message ?? 'The turn failed before completion.');
|
|
481
|
+
const eventTraceId = typeof data.traceId === 'string' ? data.traceId : traceId;
|
|
482
|
+
if (event.event === 'cancelled') {
|
|
483
|
+
return new TurnCancelledError(message);
|
|
293
484
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
return;
|
|
297
|
-
const pending = pendingParallelTools.splice(0);
|
|
298
|
-
const outcomes = await Promise.all(pending);
|
|
299
|
-
for (const outcome of outcomes) {
|
|
300
|
-
if (outcome != null)
|
|
301
|
-
throw outcome;
|
|
302
|
-
}
|
|
485
|
+
if (data.code === QUOTA_EXCEEDED_CODE) {
|
|
486
|
+
return new ServerApiError(message, 429, eventTraceId, QUOTA_EXCEEDED_CODE, data.details ?? {});
|
|
303
487
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
488
|
+
return new ChatTurnFailedError(message, typeof data.category === 'string' ? data.category : 'unknown_error', Boolean(data.retryable), eventTraceId, data.snapshot);
|
|
489
|
+
}
|
|
490
|
+
const TURN_EVENT_ACK_INTERVAL_MS = 5_000;
|
|
491
|
+
const MAX_TURN_EVENT_BYTES = 64 * 1024 * 1024;
|
|
492
|
+
function createEventAcknowledger(send) {
|
|
493
|
+
let latest = '';
|
|
494
|
+
let confirmed = '';
|
|
495
|
+
let inFlight = false;
|
|
496
|
+
let stopped = false;
|
|
497
|
+
let timer = null;
|
|
498
|
+
const schedule = () => {
|
|
499
|
+
if (timer || stopped)
|
|
309
500
|
return;
|
|
310
|
-
|
|
311
|
-
|
|
501
|
+
timer = setTimeout(flush, TURN_EVENT_ACK_INTERVAL_MS);
|
|
502
|
+
timer.unref?.();
|
|
503
|
+
};
|
|
504
|
+
const flush = () => {
|
|
505
|
+
if (timer)
|
|
506
|
+
clearTimeout(timer);
|
|
507
|
+
timer = null;
|
|
508
|
+
if (stopped || inFlight || !latest || latest === confirmed)
|
|
312
509
|
return;
|
|
510
|
+
const eventId = latest;
|
|
511
|
+
inFlight = true;
|
|
512
|
+
send(eventId)
|
|
513
|
+
.then(() => {
|
|
514
|
+
confirmed = eventId;
|
|
515
|
+
}, () => { })
|
|
516
|
+
.finally(() => {
|
|
517
|
+
inFlight = false;
|
|
518
|
+
if (latest !== confirmed)
|
|
519
|
+
schedule();
|
|
520
|
+
});
|
|
521
|
+
};
|
|
522
|
+
return {
|
|
523
|
+
note(eventId) {
|
|
524
|
+
latest = eventId;
|
|
525
|
+
schedule();
|
|
526
|
+
},
|
|
527
|
+
flush,
|
|
528
|
+
stop() {
|
|
529
|
+
stopped = true;
|
|
530
|
+
if (timer)
|
|
531
|
+
clearTimeout(timer);
|
|
532
|
+
timer = null;
|
|
533
|
+
},
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
async function runTurnStream({ openStream, config, session, input, request, recovery, signal, traceId, acknowledge, stopLocalWork, interjections, onTurnStart, onInterjectionDelivered, }) {
|
|
537
|
+
const seen = new Set();
|
|
538
|
+
const work = createTurnWork();
|
|
539
|
+
const deliveries = new AbortController();
|
|
540
|
+
const delivery = AbortSignal.any([signal, deliveries.signal]);
|
|
541
|
+
const streamToken = {};
|
|
542
|
+
let lastEventId = '';
|
|
543
|
+
let registeredTurnId = '';
|
|
544
|
+
function handleEvent(event) {
|
|
545
|
+
if (!event.id) {
|
|
546
|
+
throw new Error('The server sent a turn event without an id.');
|
|
313
547
|
}
|
|
314
|
-
if (event.
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
548
|
+
if (seen.has(event.id))
|
|
549
|
+
return null;
|
|
550
|
+
seen.add(event.id);
|
|
551
|
+
lastEventId = event.id;
|
|
552
|
+
const data = event.data;
|
|
553
|
+
switch (event.event) {
|
|
554
|
+
case 'account-usage': {
|
|
555
|
+
session.onAccountUsage?.(data);
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
case 'turn-start': {
|
|
559
|
+
const turnId = String(data?.turnId ?? '').trim();
|
|
560
|
+
if (!turnId)
|
|
561
|
+
throw new Error('The server sent a turn without an id.');
|
|
562
|
+
registeredTurnId = turnId;
|
|
563
|
+
activeTurnRequesters.set(turnId, request);
|
|
564
|
+
turnInterjections.set(turnId, interjections);
|
|
565
|
+
onTurnStart?.(turnId);
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
case 'interjection-delivered': {
|
|
569
|
+
const delivered = data;
|
|
570
|
+
for (const messageId of delivered?.messageIds ?? []) {
|
|
571
|
+
const sent = interjections.find((item) => item.messageId === messageId);
|
|
572
|
+
if (sent && !sent.delivered)
|
|
573
|
+
preserveTurnInterjection(session, input, sent);
|
|
574
|
+
}
|
|
575
|
+
onInterjectionDelivered?.(delivered);
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
case 'status': {
|
|
579
|
+
const status = (data ?? {});
|
|
580
|
+
if (status.phase === 'analyzing_image') {
|
|
581
|
+
session.onImageAnalysis?.(Math.max(1, Number(status.imageCount ?? 1) || 1));
|
|
582
|
+
session.onImageGeneration?.(false);
|
|
583
|
+
}
|
|
584
|
+
else if (status.phase === 'generating_image') {
|
|
585
|
+
session.onImageGeneration?.(true);
|
|
586
|
+
session.onImageAnalysis?.(0);
|
|
587
|
+
}
|
|
588
|
+
else if (status.phase) {
|
|
589
|
+
session.onImageAnalysis?.(0);
|
|
590
|
+
session.onImageGeneration?.(false);
|
|
591
|
+
}
|
|
592
|
+
const message = publicStatusMessage(data);
|
|
593
|
+
if (message)
|
|
594
|
+
session.onStatus(message);
|
|
595
|
+
break;
|
|
596
|
+
}
|
|
597
|
+
case 'tool-call': {
|
|
598
|
+
const toolCall = data;
|
|
599
|
+
if (!toolCall?.executionId || !toolCall.call?.name) {
|
|
600
|
+
throw new Error('Server emitted an invalid tool-call event.');
|
|
601
|
+
}
|
|
602
|
+
work.dispatch(`tool:${toolCall.executionId}`, toolCall.parallelSafe === true, (executed) => executeAndPostToolResult({
|
|
318
603
|
config,
|
|
319
|
-
projectIndex,
|
|
320
604
|
session,
|
|
321
|
-
event:
|
|
605
|
+
event: toolCall,
|
|
322
606
|
input,
|
|
323
|
-
|
|
607
|
+
request,
|
|
324
608
|
signal,
|
|
609
|
+
delivery,
|
|
610
|
+
executed,
|
|
325
611
|
traceId,
|
|
326
|
-
})
|
|
327
|
-
|
|
612
|
+
}));
|
|
613
|
+
break;
|
|
328
614
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
input,
|
|
336
|
-
fetchImpl,
|
|
337
|
-
signal,
|
|
338
|
-
traceId,
|
|
339
|
-
});
|
|
340
|
-
return;
|
|
341
|
-
}
|
|
342
|
-
if (event.event === 'tool-result') {
|
|
343
|
-
const data = event.data;
|
|
344
|
-
if (data?.call?.name) {
|
|
345
|
-
session.onToolEvent?.({ call: data.call, result: data.result });
|
|
615
|
+
case 'tool-result': {
|
|
616
|
+
const toolResult = data;
|
|
617
|
+
if (toolResult?.call?.name) {
|
|
618
|
+
session.onToolEvent?.({ call: toolResult.call, result: toolResult.result });
|
|
619
|
+
}
|
|
620
|
+
break;
|
|
346
621
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
622
|
+
case 'user-input-request': {
|
|
623
|
+
const question = data;
|
|
624
|
+
const turnId = String(question?.turnId ?? '').trim();
|
|
625
|
+
const requestId = String(question?.requestId ?? '').trim();
|
|
626
|
+
if (!turnId || !requestId || !isUserInputQuestionArray(question?.questions)) {
|
|
627
|
+
throw new Error('Server emitted an invalid user-input request.');
|
|
628
|
+
}
|
|
629
|
+
work.dispatch(`question:${requestId}`, false, async (executed) => {
|
|
630
|
+
if (!session.requestUserInput) {
|
|
631
|
+
throw new Error('Interactive user input is unavailable in this client.');
|
|
632
|
+
}
|
|
633
|
+
const result = await session.requestUserInput({ questions: question.questions }, signal);
|
|
634
|
+
executed();
|
|
635
|
+
signal.throwIfAborted();
|
|
636
|
+
preserveTurnAnswer(session, input, requestId, question.questions, result);
|
|
637
|
+
if (delivery.aborted)
|
|
638
|
+
return;
|
|
639
|
+
await postUserInputResult({
|
|
640
|
+
config,
|
|
641
|
+
turnId,
|
|
642
|
+
requestId,
|
|
643
|
+
result,
|
|
644
|
+
request,
|
|
645
|
+
traceId,
|
|
646
|
+
delivery,
|
|
647
|
+
});
|
|
648
|
+
});
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
case 'result':
|
|
652
|
+
if (!data?.snapshot)
|
|
653
|
+
throw new Error('Server returned an invalid chat result.');
|
|
654
|
+
return { kind: 'result', result: data };
|
|
655
|
+
case 'error':
|
|
656
|
+
case 'cancelled':
|
|
657
|
+
return { kind: 'failed', error: terminalFailure(event, traceId) };
|
|
658
|
+
default:
|
|
659
|
+
break;
|
|
353
660
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
661
|
+
acknowledge.note(event.id);
|
|
662
|
+
return null;
|
|
663
|
+
}
|
|
664
|
+
async function readUntilOutcome(response) {
|
|
665
|
+
if (!response.body)
|
|
666
|
+
throw interruptedStream('The server returned an empty turn stream.');
|
|
667
|
+
const reader = response.body.getReader();
|
|
668
|
+
const decoder = new TextDecoder();
|
|
669
|
+
let buffer = '';
|
|
670
|
+
try {
|
|
671
|
+
for (;;) {
|
|
672
|
+
const read = await Promise.race([readTurnChunk(reader, signal), work.failed]);
|
|
673
|
+
if (read.done)
|
|
674
|
+
throw interruptedStream();
|
|
675
|
+
buffer += decoder.decode(read.value, { stream: true });
|
|
676
|
+
for (let match = /\r?\n\r?\n/.exec(buffer); match; match = /\r?\n\r?\n/.exec(buffer)) {
|
|
677
|
+
const block = buffer.slice(0, match.index);
|
|
678
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
679
|
+
signal.throwIfAborted();
|
|
680
|
+
const event = parseSseBlock(block);
|
|
681
|
+
if (!event)
|
|
682
|
+
continue;
|
|
683
|
+
recovery.restored(streamToken);
|
|
684
|
+
const outcome = handleEvent(event);
|
|
685
|
+
if (outcome)
|
|
686
|
+
return outcome;
|
|
687
|
+
}
|
|
688
|
+
if (buffer.length > MAX_TURN_EVENT_BYTES) {
|
|
689
|
+
throw new Error('The server sent a turn event larger than the protocol allows.');
|
|
690
|
+
}
|
|
359
691
|
}
|
|
360
|
-
|
|
692
|
+
}
|
|
693
|
+
finally {
|
|
694
|
+
await reader.cancel().catch(() => { });
|
|
361
695
|
}
|
|
362
696
|
}
|
|
363
697
|
try {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
698
|
+
for (;;) {
|
|
699
|
+
let outcome;
|
|
700
|
+
try {
|
|
701
|
+
signal.throwIfAborted();
|
|
702
|
+
const response = await openStream(lastEventId);
|
|
703
|
+
recovery.reconnected(streamToken);
|
|
704
|
+
outcome = await readUntilOutcome(response);
|
|
368
705
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
706
|
+
catch (error) {
|
|
707
|
+
signal.throwIfAborted();
|
|
708
|
+
if (work.hasFailed)
|
|
709
|
+
throw error;
|
|
710
|
+
await recovery.retryAfter(streamToken, lastEventId ? 'reading the turn stream' : 'opening the turn', error);
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
acknowledge.note(lastEventId);
|
|
714
|
+
acknowledge.flush();
|
|
715
|
+
if (outcome.kind === 'result') {
|
|
716
|
+
deliveries.abort(new Error('The turn already finished.'));
|
|
717
|
+
await work.executed();
|
|
718
|
+
signal.throwIfAborted();
|
|
381
719
|
}
|
|
720
|
+
else {
|
|
721
|
+
stopLocalWork();
|
|
722
|
+
await work.settled();
|
|
723
|
+
}
|
|
724
|
+
return outcome;
|
|
382
725
|
}
|
|
383
|
-
await drainParallelTools();
|
|
384
726
|
}
|
|
385
727
|
catch (error) {
|
|
386
|
-
|
|
387
|
-
|
|
728
|
+
const outcome = signal.aborted ? signal.reason : error;
|
|
729
|
+
stopLocalWork();
|
|
730
|
+
await work.settled();
|
|
731
|
+
throw outcome;
|
|
388
732
|
}
|
|
389
733
|
finally {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
if (tail) {
|
|
395
|
-
const event = parseSseBlock(tail);
|
|
396
|
-
if (event)
|
|
397
|
-
await handleEvent(event);
|
|
398
|
-
}
|
|
399
|
-
if (!finalResult.current?.snapshot) {
|
|
400
|
-
throw new Error('Server returned an invalid chat result.');
|
|
734
|
+
if (registeredTurnId) {
|
|
735
|
+
activeTurnRequesters.delete(registeredTurnId);
|
|
736
|
+
turnInterjections.delete(registeredTurnId);
|
|
737
|
+
}
|
|
401
738
|
}
|
|
402
|
-
return finalResult.current;
|
|
403
739
|
}
|
|
404
|
-
export async function sendServerUserMessage({ config,
|
|
740
|
+
export async function sendServerUserMessage({ config, session, input, jobFollowUp = false, imageAttachments = [], fetchImpl = globalThis.fetch, signal, onTurnStart, onInterjectionDelivered, recoverySleep, }) {
|
|
405
741
|
const autoAttach = autoAttachImages(input, session.rootDir, imageAttachments);
|
|
406
742
|
const requestImageAttachments = autoAttach.attachments.length > 0
|
|
407
743
|
? [...imageAttachments, ...autoAttach.attachments]
|
|
@@ -414,57 +750,104 @@ export async function sendServerUserMessage({ config, projectIndex, session, inp
|
|
|
414
750
|
session.onStatus(`Image: ${err}`);
|
|
415
751
|
}
|
|
416
752
|
const request = {
|
|
753
|
+
clientTurnId: randomUUID(),
|
|
754
|
+
mcpTools: await sessionMcp(session).discover(signal),
|
|
417
755
|
modelId: session.modelId,
|
|
756
|
+
reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, config.serverUrl, session.env), session.modelId),
|
|
418
757
|
session: snapshotForServer(session),
|
|
419
758
|
input: requestInputBase,
|
|
420
759
|
backgroundJobUpdate: backgroundJobUpdate || undefined,
|
|
760
|
+
supportsJobFollowUp: true,
|
|
761
|
+
...(jobFollowUp ? { jobFollowUp: true } : {}),
|
|
421
762
|
clientEnvironment: collectClientEnvironment({ env: session.env }),
|
|
422
763
|
projectOrientation: collectProjectOrientation(session.rootDir) ?? undefined,
|
|
764
|
+
sessionImageStore: describeSessionImageStore(session.env) ?? undefined,
|
|
423
765
|
imageAttachments: imageAttachmentsForServer(requestImageAttachments),
|
|
424
|
-
|
|
766
|
+
...(session.maxToolStepsWasExplicit || !browserExtensionSeen(session.env)
|
|
767
|
+
? { maxToolSteps: session.maxToolSteps }
|
|
768
|
+
: {}),
|
|
425
769
|
autoYes: session.autoYes,
|
|
426
770
|
agentMode: session.agentMode,
|
|
427
771
|
};
|
|
428
772
|
const trace = createTraceContext();
|
|
773
|
+
let completed = false;
|
|
774
|
+
let turnEnded = false;
|
|
775
|
+
const reportRecovery = (status) => {
|
|
776
|
+
if (!turnEnded)
|
|
777
|
+
session.onRecovery?.(status);
|
|
778
|
+
};
|
|
779
|
+
const startAttempt = (turnRequest, onStart) => startTurnAttempt({
|
|
780
|
+
config,
|
|
781
|
+
session,
|
|
782
|
+
turnRequest,
|
|
783
|
+
input: requestInputBase,
|
|
784
|
+
trace,
|
|
785
|
+
fetchImpl,
|
|
786
|
+
recoverySleep,
|
|
787
|
+
reportRecovery,
|
|
788
|
+
onTurnStart: onStart,
|
|
789
|
+
onInterjectionDelivered,
|
|
790
|
+
});
|
|
791
|
+
let attempt = startAttempt(request, onTurnStart);
|
|
792
|
+
const cancelTurn = () => attempt.cancel();
|
|
429
793
|
const preTurnHistoryLength = session.history.length;
|
|
430
794
|
const preserveOnAbort = () => preserveCancelledTurnInput(session, requestInputBase);
|
|
431
795
|
if (signal?.aborted) {
|
|
432
796
|
preserveOnAbort();
|
|
797
|
+
cancelTurn();
|
|
433
798
|
}
|
|
434
799
|
else {
|
|
435
800
|
signal?.addEventListener('abort', preserveOnAbort, { once: true });
|
|
801
|
+
signal?.addEventListener('abort', cancelTurn, { once: true });
|
|
436
802
|
}
|
|
437
803
|
try {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
accept: 'text/event-stream',
|
|
442
|
-
authorization: `Bearer ${config.token}`,
|
|
443
|
-
'content-type': 'application/json',
|
|
444
|
-
...trace.headers,
|
|
445
|
-
},
|
|
446
|
-
body: JSON.stringify(request),
|
|
447
|
-
signal,
|
|
448
|
-
});
|
|
449
|
-
if (!response.ok) {
|
|
450
|
-
throw await readErrorResponse(response, trace.traceId);
|
|
804
|
+
let outcome;
|
|
805
|
+
try {
|
|
806
|
+
outcome = await attempt.run();
|
|
451
807
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
808
|
+
catch (error) {
|
|
809
|
+
const sent = attempt.interjections;
|
|
810
|
+
if (!isTurnLostByServer(error) || sent.some((item) => item.hasImages))
|
|
811
|
+
throw error;
|
|
812
|
+
attempt.close(false);
|
|
813
|
+
if (signal?.aborted)
|
|
814
|
+
throw new TurnCancelledError();
|
|
815
|
+
const carried = sent.filter((item) => !item.delivered);
|
|
816
|
+
for (const item of carried)
|
|
817
|
+
preserveTurnInterjection(session, requestInputBase, item);
|
|
818
|
+
reportRecovery({ phase: 'continuing' });
|
|
819
|
+
attempt = startAttempt({
|
|
820
|
+
...request,
|
|
821
|
+
clientTurnId: randomUUID(),
|
|
822
|
+
session: snapshotForServer(session),
|
|
823
|
+
continuation: {
|
|
824
|
+
clientTurnId: request.clientTurnId,
|
|
825
|
+
historyIndex: preTurnHistoryLength,
|
|
826
|
+
},
|
|
827
|
+
}, (turnId) => {
|
|
828
|
+
reportRecovery({ phase: 'continued' });
|
|
829
|
+
onTurnStart?.(turnId);
|
|
830
|
+
if (carried.length > 0) {
|
|
831
|
+
onInterjectionDelivered?.({
|
|
832
|
+
turnId,
|
|
833
|
+
step: 0,
|
|
834
|
+
deliveredAt: 'tool_round_boundary',
|
|
835
|
+
messageIds: carried.map((item) => item.messageId),
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
outcome = await attempt.run();
|
|
840
|
+
}
|
|
841
|
+
if (outcome.kind === 'failed')
|
|
842
|
+
throw outcome.error;
|
|
843
|
+
applySessionSnapshot(session, outcome.result.snapshot, { preserveAgentMode: true });
|
|
844
|
+
completed = true;
|
|
463
845
|
return {
|
|
464
|
-
text: result.text,
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
846
|
+
text: outcome.result.text,
|
|
847
|
+
waitingForJobs: outcome.result.waitingForJobs,
|
|
848
|
+
waitingForApproval: outcome.result.waitingForApproval,
|
|
849
|
+
toolBudgetReached: outcome.result.toolBudgetReached,
|
|
850
|
+
usageSummary: outcome.result.usageSummary,
|
|
468
851
|
};
|
|
469
852
|
}
|
|
470
853
|
catch (error) {
|
|
@@ -474,11 +857,153 @@ export async function sendServerUserMessage({ config, projectIndex, session, inp
|
|
|
474
857
|
? error
|
|
475
858
|
: new TurnCancelledError();
|
|
476
859
|
}
|
|
477
|
-
|
|
478
|
-
|
|
860
|
+
const exhausted = isTurnRecoveryExhausted(error);
|
|
861
|
+
const carriesTrace = error instanceof ChatTurnFailedError || error instanceof ServerApiError;
|
|
862
|
+
const transportDetail = carriesTrace || exhausted ? null : transportFailureDetail(error);
|
|
863
|
+
if (transportDetail && error instanceof Error) {
|
|
864
|
+
const phase = turnPhaseOf(error) ?? 'reaching the server';
|
|
865
|
+
error.message = `connection lost while ${phase}: ${transportDetail} [trace ${trace.traceId}]`;
|
|
866
|
+
}
|
|
867
|
+
else if (!carriesTrace && error instanceof Error) {
|
|
868
|
+
error.message = `${error.message} [trace ${trace.traceId}]`;
|
|
869
|
+
}
|
|
870
|
+
const category = error instanceof ChatTurnFailedError
|
|
871
|
+
? error.category
|
|
872
|
+
: exhausted
|
|
873
|
+
? 'connection_error'
|
|
874
|
+
:
|
|
875
|
+
(gatewayFailureCategory(error) ?? 'unknown_error');
|
|
876
|
+
const partial = error instanceof ChatTurnFailedError ? error.partialSnapshot : undefined;
|
|
877
|
+
if (partial) {
|
|
878
|
+
applySessionSnapshot(session, partial, { preserveAgentMode: true });
|
|
879
|
+
}
|
|
880
|
+
else if (session.history.length === preTurnHistoryLength) {
|
|
881
|
+
preserveFailedTurnInput(session, requestInputBase, category);
|
|
882
|
+
}
|
|
883
|
+
else {
|
|
884
|
+
appendTurnFailureMarker(session, category);
|
|
885
|
+
}
|
|
886
|
+
try {
|
|
887
|
+
saveSessionState(session, session.env);
|
|
888
|
+
}
|
|
889
|
+
catch { }
|
|
479
890
|
throw error;
|
|
480
891
|
}
|
|
481
892
|
finally {
|
|
893
|
+
turnEnded = true;
|
|
482
894
|
signal?.removeEventListener('abort', preserveOnAbort);
|
|
895
|
+
signal?.removeEventListener('abort', cancelTurn);
|
|
896
|
+
attempt.close(completed);
|
|
897
|
+
releaseBrowserAfterTurn();
|
|
483
898
|
}
|
|
484
899
|
}
|
|
900
|
+
function isTurnLostByServer(error) {
|
|
901
|
+
return error instanceof ServerApiError && error.code === 'RECOVERY_UNAVAILABLE';
|
|
902
|
+
}
|
|
903
|
+
function startTurnAttempt({ config, session, turnRequest, input, trace, fetchImpl, recoverySleep, reportRecovery, onTurnStart, onInterjectionDelivered, }) {
|
|
904
|
+
const requestBody = JSON.stringify(turnRequest);
|
|
905
|
+
const interjections = [];
|
|
906
|
+
const turnController = new AbortController();
|
|
907
|
+
const turnSignal = turnController.signal;
|
|
908
|
+
session.turnAbortSignal = turnSignal;
|
|
909
|
+
let serverSettled = false;
|
|
910
|
+
let cancellationSent = false;
|
|
911
|
+
const sendCancellation = () => {
|
|
912
|
+
if (cancellationSent)
|
|
913
|
+
return;
|
|
914
|
+
cancellationSent = true;
|
|
915
|
+
const cancelController = new AbortController();
|
|
916
|
+
void fetchTurnAttempt(fetchImpl, turnUrl(config, turnRequest.clientTurnId, 'cancel'), {
|
|
917
|
+
method: 'POST',
|
|
918
|
+
headers: {
|
|
919
|
+
authorization: `Bearer ${config.token}`,
|
|
920
|
+
'content-type': 'application/json',
|
|
921
|
+
...trace.headers,
|
|
922
|
+
},
|
|
923
|
+
body: JSON.stringify({ sessionId: turnRequest.session.id }),
|
|
924
|
+
}, cancelController.signal, { readBody: true }).catch(() => { });
|
|
925
|
+
};
|
|
926
|
+
const stopLocalWork = () => {
|
|
927
|
+
turnController.abort(new TurnCancelledError());
|
|
928
|
+
cancelActiveCommand();
|
|
929
|
+
};
|
|
930
|
+
const recovery = createTurnRecovery({
|
|
931
|
+
signal: turnSignal,
|
|
932
|
+
sleep: recoverySleep,
|
|
933
|
+
onStatus: reportRecovery,
|
|
934
|
+
});
|
|
935
|
+
const requester = createTurnRequester({
|
|
936
|
+
fetchImpl,
|
|
937
|
+
recovery,
|
|
938
|
+
signal: turnSignal,
|
|
939
|
+
traceId: trace.traceId,
|
|
940
|
+
});
|
|
941
|
+
const acknowledge = createEventAcknowledger(async (eventId) => {
|
|
942
|
+
const response = await fetchTurnAttempt(fetchImpl, turnUrl(config, turnRequest.clientTurnId, 'ack'), {
|
|
943
|
+
method: 'POST',
|
|
944
|
+
headers: {
|
|
945
|
+
authorization: `Bearer ${config.token}`,
|
|
946
|
+
'content-type': 'application/json',
|
|
947
|
+
...trace.headers,
|
|
948
|
+
},
|
|
949
|
+
body: JSON.stringify({ eventId }),
|
|
950
|
+
}, new AbortController().signal, { readBody: true });
|
|
951
|
+
if (!response.ok)
|
|
952
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
953
|
+
});
|
|
954
|
+
const openStream = async (lastEventId) => {
|
|
955
|
+
const response = await fetchTurnAttempt(fetchImpl, `${normalizeServerUrl(config.serverUrl)}/v1/chat/turn`, {
|
|
956
|
+
method: 'POST',
|
|
957
|
+
headers: {
|
|
958
|
+
accept: 'text/event-stream',
|
|
959
|
+
authorization: `Bearer ${config.token}`,
|
|
960
|
+
'content-type': 'application/json',
|
|
961
|
+
...trace.headers,
|
|
962
|
+
...(lastEventId ? { 'last-event-id': lastEventId } : {}),
|
|
963
|
+
},
|
|
964
|
+
body: requestBody,
|
|
965
|
+
}, turnSignal);
|
|
966
|
+
if (!response.ok) {
|
|
967
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
968
|
+
}
|
|
969
|
+
return response;
|
|
970
|
+
};
|
|
971
|
+
return {
|
|
972
|
+
interjections,
|
|
973
|
+
cancel() {
|
|
974
|
+
stopLocalWork();
|
|
975
|
+
sendCancellation();
|
|
976
|
+
},
|
|
977
|
+
async run() {
|
|
978
|
+
const outcome = await runTurnStream({
|
|
979
|
+
openStream,
|
|
980
|
+
config,
|
|
981
|
+
session,
|
|
982
|
+
input,
|
|
983
|
+
request: requester,
|
|
984
|
+
recovery,
|
|
985
|
+
signal: turnSignal,
|
|
986
|
+
traceId: trace.traceId,
|
|
987
|
+
acknowledge,
|
|
988
|
+
stopLocalWork,
|
|
989
|
+
interjections,
|
|
990
|
+
onTurnStart,
|
|
991
|
+
onInterjectionDelivered,
|
|
992
|
+
});
|
|
993
|
+
serverSettled = true;
|
|
994
|
+
return outcome;
|
|
995
|
+
},
|
|
996
|
+
close(completed) {
|
|
997
|
+
acknowledge.stop();
|
|
998
|
+
if (!serverSettled)
|
|
999
|
+
sendCancellation();
|
|
1000
|
+
if (!completed)
|
|
1001
|
+
turnController.abort(new TurnCancelledError());
|
|
1002
|
+
if (session.turnAbortSignal === turnSignal)
|
|
1003
|
+
session.turnAbortSignal = undefined;
|
|
1004
|
+
},
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
export function isTurnOutcomeKnown(error) {
|
|
1008
|
+
return error instanceof ChatTurnFailedError;
|
|
1009
|
+
}
|