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