@thegitai/cli 1.0.0-preview.9 → 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 +139 -111
- 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 +77 -34
- package/dist/src/api/chat.js +700 -173
- 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 +71 -10
- 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/repl.js +1141 -299
- 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 +858 -303
- 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 +4 -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,14 +201,19 @@ function publicStatusMessage(data) {
|
|
|
145
201
|
? event.toolName
|
|
146
202
|
: 'tool';
|
|
147
203
|
if (event.phase === 'thinking')
|
|
148
|
-
return '
|
|
204
|
+
return 'Exploring options...';
|
|
149
205
|
if (event.phase === 'analyzing_image') {
|
|
150
206
|
return (event.imageCount ?? 1) > 1 ? 'Analyzing images...' : 'Analyzing image...';
|
|
151
207
|
}
|
|
208
|
+
if (event.phase === 'generating_image') {
|
|
209
|
+
return 'Generating image...';
|
|
210
|
+
}
|
|
152
211
|
if (event.phase === 'running_tool')
|
|
153
212
|
return `Running ${toolName}...`;
|
|
154
213
|
if (event.phase === 'waiting_for_tool')
|
|
155
214
|
return `Running ${toolName} locally...`;
|
|
215
|
+
if (event.phase === 'waiting_for_user_input')
|
|
216
|
+
return 'Waiting for your input...';
|
|
156
217
|
return null;
|
|
157
218
|
}
|
|
158
219
|
function normalizeShellJobToolCall(call) {
|
|
@@ -184,15 +245,33 @@ function normalizeShellJobToolCall(call) {
|
|
|
184
245
|
}
|
|
185
246
|
return changed ? { ...call, args } : call;
|
|
186
247
|
}
|
|
187
|
-
|
|
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, }) {
|
|
188
266
|
const payload = {
|
|
267
|
+
executionId: event.executionId,
|
|
189
268
|
toolCallId: event.call.id,
|
|
190
269
|
result,
|
|
191
270
|
toolState: toolStateFromSession(session),
|
|
192
271
|
toolStateSeq: ++toolStateSeqCounter,
|
|
193
272
|
};
|
|
194
273
|
const trace = createTraceContext(traceId);
|
|
195
|
-
const response = await
|
|
274
|
+
const response = await request('posting a tool result', turnUrl(config, turnId, 'tool-result'), {
|
|
196
275
|
method: 'POST',
|
|
197
276
|
headers: {
|
|
198
277
|
authorization: `Bearer ${config.token}`,
|
|
@@ -200,14 +279,88 @@ async function postToolResult({ config, turnId, event, result, session, fetchImp
|
|
|
200
279
|
...trace.headers,
|
|
201
280
|
},
|
|
202
281
|
body: JSON.stringify(payload),
|
|
282
|
+
signal: delivery,
|
|
203
283
|
});
|
|
204
|
-
if (response.status === 410)
|
|
284
|
+
if (response.status === 410)
|
|
205
285
|
return;
|
|
286
|
+
if (!response.ok) {
|
|
287
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
206
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;
|
|
207
308
|
if (!response.ok) {
|
|
208
309
|
throw await readErrorResponse(response, trace.traceId);
|
|
209
310
|
}
|
|
210
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';
|
|
357
|
+
}
|
|
358
|
+
if (!response.ok) {
|
|
359
|
+
forget();
|
|
360
|
+
throw await readErrorResponse(response, trace.traceId);
|
|
361
|
+
}
|
|
362
|
+
return 'delivered';
|
|
363
|
+
}
|
|
211
364
|
const turnIdOverrides = new WeakMap();
|
|
212
365
|
function enterServerTurnId(session, serverSessionTurnId) {
|
|
213
366
|
const active = turnIdOverrides.get(session);
|
|
@@ -231,14 +384,13 @@ function exitServerTurnId(session) {
|
|
|
231
384
|
turnIdOverrides.delete(session);
|
|
232
385
|
}
|
|
233
386
|
}
|
|
234
|
-
async function executeAndPostToolResult({ config,
|
|
387
|
+
async function executeAndPostToolResult({ config, session, event, input, request, signal, delivery, executed, traceId, }) {
|
|
235
388
|
const turnId = String(event?.turnId ?? '').trim();
|
|
236
|
-
if (!turnId || !event?.call?.id || !event.call.name) {
|
|
389
|
+
if (!turnId || !event?.executionId || !event?.call?.id || !event.call.name) {
|
|
237
390
|
throw new Error('Server emitted an invalid tool-call event.');
|
|
238
391
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
392
|
+
signal.throwIfAborted();
|
|
393
|
+
delivery.throwIfAborted();
|
|
242
394
|
const serverSessionTurnId = String(event.sessionTurnId ?? '').trim();
|
|
243
395
|
if (serverSessionTurnId) {
|
|
244
396
|
enterServerTurnId(session, serverSessionTurnId);
|
|
@@ -248,19 +400,28 @@ async function executeAndPostToolResult({ config, projectIndex, session, event,
|
|
|
248
400
|
}
|
|
249
401
|
try {
|
|
250
402
|
const call = normalizeShellJobToolCall(event.call);
|
|
251
|
-
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));
|
|
252
411
|
preserveCancelledTurnToolResult(session, input, { ...event, call }, rawResult);
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
412
|
+
executed();
|
|
413
|
+
signal.throwIfAborted();
|
|
414
|
+
if (delivery.aborted)
|
|
415
|
+
return;
|
|
256
416
|
await postToolResult({
|
|
257
417
|
config,
|
|
258
418
|
turnId,
|
|
259
419
|
event,
|
|
260
420
|
result: rawResult,
|
|
261
421
|
session,
|
|
262
|
-
|
|
422
|
+
request,
|
|
263
423
|
traceId,
|
|
424
|
+
delivery,
|
|
264
425
|
});
|
|
265
426
|
}
|
|
266
427
|
finally {
|
|
@@ -269,149 +430,319 @@ async function executeAndPostToolResult({ config, projectIndex, session, event,
|
|
|
269
430
|
}
|
|
270
431
|
}
|
|
271
432
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
+
});
|
|
275
465
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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
|
+
},
|
|
281
478
|
};
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
function recordParallelFailure(error) {
|
|
290
|
-
const failure = error ?? new Error('Local tool execution failed.');
|
|
291
|
-
if (firstParallelFailure == null) {
|
|
292
|
-
firstParallelFailure = failure;
|
|
293
|
-
rejectOnParallelFailure?.(failure);
|
|
294
|
-
}
|
|
295
|
-
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);
|
|
296
486
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
return;
|
|
300
|
-
const pending = pendingParallelTools.splice(0);
|
|
301
|
-
const outcomes = await Promise.all(pending);
|
|
302
|
-
for (const outcome of outcomes) {
|
|
303
|
-
if (outcome != null)
|
|
304
|
-
throw outcome;
|
|
305
|
-
}
|
|
487
|
+
if (data.code === QUOTA_EXCEEDED_CODE) {
|
|
488
|
+
return new ServerApiError(message, 429, eventTraceId, QUOTA_EXCEEDED_CODE, failureDetails({ error: data.details }));
|
|
306
489
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
490
|
+
if (data.code === PLAN_REQUIRED_CODE) {
|
|
491
|
+
return new ServerApiError(message, 402, eventTraceId, PLAN_REQUIRED_CODE, failureDetails({ error: data.details }));
|
|
492
|
+
}
|
|
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)
|
|
319
505
|
return;
|
|
320
|
-
|
|
321
|
-
|
|
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)
|
|
322
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.');
|
|
323
552
|
}
|
|
324
|
-
if (event.
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
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({
|
|
328
608
|
config,
|
|
329
|
-
projectIndex,
|
|
330
609
|
session,
|
|
331
|
-
event:
|
|
610
|
+
event: toolCall,
|
|
332
611
|
input,
|
|
333
|
-
|
|
612
|
+
request,
|
|
334
613
|
signal,
|
|
614
|
+
delivery,
|
|
615
|
+
executed,
|
|
335
616
|
traceId,
|
|
336
|
-
})
|
|
337
|
-
|
|
617
|
+
}));
|
|
618
|
+
break;
|
|
338
619
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
input,
|
|
346
|
-
fetchImpl,
|
|
347
|
-
signal,
|
|
348
|
-
traceId,
|
|
349
|
-
});
|
|
350
|
-
return;
|
|
351
|
-
}
|
|
352
|
-
if (event.event === 'tool-result') {
|
|
353
|
-
const data = event.data;
|
|
354
|
-
if (data?.call?.name) {
|
|
355
|
-
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;
|
|
356
626
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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;
|
|
363
665
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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
|
+
}
|
|
369
696
|
}
|
|
370
|
-
|
|
697
|
+
}
|
|
698
|
+
finally {
|
|
699
|
+
await reader.cancel().catch(() => { });
|
|
371
700
|
}
|
|
372
701
|
}
|
|
373
702
|
try {
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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);
|
|
378
710
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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();
|
|
391
728
|
}
|
|
729
|
+
return outcome;
|
|
392
730
|
}
|
|
393
|
-
await drainParallelTools();
|
|
394
731
|
}
|
|
395
732
|
catch (error) {
|
|
396
|
-
|
|
397
|
-
|
|
733
|
+
const outcome = signal.aborted ? signal.reason : error;
|
|
734
|
+
stopLocalWork();
|
|
735
|
+
await work.settled();
|
|
736
|
+
throw outcome;
|
|
398
737
|
}
|
|
399
738
|
finally {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
if (tail) {
|
|
405
|
-
const event = parseSseBlock(tail);
|
|
406
|
-
if (event)
|
|
407
|
-
await handleEvent(event);
|
|
408
|
-
}
|
|
409
|
-
if (!finalResult.current?.snapshot) {
|
|
410
|
-
throw new Error('Server returned an invalid chat result.');
|
|
739
|
+
if (registeredTurnId) {
|
|
740
|
+
activeTurnRequesters.delete(registeredTurnId);
|
|
741
|
+
turnInterjections.delete(registeredTurnId);
|
|
742
|
+
}
|
|
411
743
|
}
|
|
412
|
-
return finalResult.current;
|
|
413
744
|
}
|
|
414
|
-
export async function sendServerUserMessage({ config,
|
|
745
|
+
export async function sendServerUserMessage({ config, session, input, jobFollowUp = false, imageAttachments = [], fetchImpl = globalThis.fetch, signal, onTurnStart, onInterjectionDelivered, recoverySleep, }) {
|
|
415
746
|
const autoAttach = autoAttachImages(input, session.rootDir, imageAttachments);
|
|
416
747
|
const requestImageAttachments = autoAttach.attachments.length > 0
|
|
417
748
|
? [...imageAttachments, ...autoAttach.attachments]
|
|
@@ -424,57 +755,105 @@ export async function sendServerUserMessage({ config, projectIndex, session, inp
|
|
|
424
755
|
session.onStatus(`Image: ${err}`);
|
|
425
756
|
}
|
|
426
757
|
const request = {
|
|
758
|
+
clientTurnId: randomUUID(),
|
|
759
|
+
mcpTools: await sessionMcp(session).discover(signal),
|
|
760
|
+
...collectSkillRequest(session.rootDir, session.env, jobFollowUp ? '' : requestInputBase),
|
|
427
761
|
modelId: session.modelId,
|
|
762
|
+
reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, config.serverUrl, session.env), session.modelId),
|
|
428
763
|
session: snapshotForServer(session),
|
|
429
764
|
input: requestInputBase,
|
|
430
765
|
backgroundJobUpdate: backgroundJobUpdate || undefined,
|
|
766
|
+
supportsJobFollowUp: true,
|
|
767
|
+
...(jobFollowUp ? { jobFollowUp: true } : {}),
|
|
431
768
|
clientEnvironment: collectClientEnvironment({ env: session.env }),
|
|
432
769
|
projectOrientation: collectProjectOrientation(session.rootDir) ?? undefined,
|
|
770
|
+
sessionImageStore: describeSessionImageStore(session.env) ?? undefined,
|
|
433
771
|
imageAttachments: imageAttachmentsForServer(requestImageAttachments),
|
|
434
|
-
|
|
772
|
+
...(session.maxToolStepsWasExplicit || !browserExtensionSeen(session.env)
|
|
773
|
+
? { maxToolSteps: session.maxToolSteps }
|
|
774
|
+
: {}),
|
|
435
775
|
autoYes: session.autoYes,
|
|
436
776
|
agentMode: session.agentMode,
|
|
437
777
|
};
|
|
438
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();
|
|
439
799
|
const preTurnHistoryLength = session.history.length;
|
|
440
800
|
const preserveOnAbort = () => preserveCancelledTurnInput(session, requestInputBase);
|
|
441
801
|
if (signal?.aborted) {
|
|
442
802
|
preserveOnAbort();
|
|
803
|
+
cancelTurn();
|
|
443
804
|
}
|
|
444
805
|
else {
|
|
445
806
|
signal?.addEventListener('abort', preserveOnAbort, { once: true });
|
|
807
|
+
signal?.addEventListener('abort', cancelTurn, { once: true });
|
|
446
808
|
}
|
|
447
809
|
try {
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
accept: 'text/event-stream',
|
|
452
|
-
authorization: `Bearer ${config.token}`,
|
|
453
|
-
'content-type': 'application/json',
|
|
454
|
-
...trace.headers,
|
|
455
|
-
},
|
|
456
|
-
body: JSON.stringify(request),
|
|
457
|
-
signal,
|
|
458
|
-
});
|
|
459
|
-
if (!response.ok) {
|
|
460
|
-
throw await readErrorResponse(response, trace.traceId);
|
|
810
|
+
let outcome;
|
|
811
|
+
try {
|
|
812
|
+
outcome = await attempt.run();
|
|
461
813
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
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;
|
|
473
851
|
return {
|
|
474
|
-
text: result.text,
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
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,
|
|
478
857
|
};
|
|
479
858
|
}
|
|
480
859
|
catch (error) {
|
|
@@ -484,11 +863,159 @@ export async function sendServerUserMessage({ config, projectIndex, session, inp
|
|
|
484
863
|
? error
|
|
485
864
|
: new TurnCancelledError();
|
|
486
865
|
}
|
|
487
|
-
|
|
488
|
-
|
|
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 { }
|
|
489
899
|
throw error;
|
|
490
900
|
}
|
|
491
901
|
finally {
|
|
902
|
+
turnEnded = true;
|
|
492
903
|
signal?.removeEventListener('abort', preserveOnAbort);
|
|
904
|
+
signal?.removeEventListener('abort', cancelTurn);
|
|
905
|
+
attempt.close(completed);
|
|
906
|
+
releaseBrowserAfterTurn();
|
|
493
907
|
}
|
|
494
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
|
+
}
|