@thegitai/cli 1.0.0-preview.6 → 1.0.0-preview.61

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.
Files changed (91) hide show
  1. package/README.md +232 -7
  2. package/dist/bin/ai.js +140 -111
  3. package/dist/bin/browser-host.js +284 -0
  4. package/dist/src/agent-mode.js +32 -7
  5. package/dist/src/api/auth.js +8 -2
  6. package/dist/src/api/browser-login.js +147 -35
  7. package/dist/src/api/chat.js +691 -166
  8. package/dist/src/api/contracts.js +55 -1
  9. package/dist/src/api/default-host.js +1 -0
  10. package/dist/src/api/http.js +139 -8
  11. package/dist/src/api/models.js +34 -9
  12. package/dist/src/api/startup-handshake.js +36 -0
  13. package/dist/src/api/turn-recovery.js +189 -0
  14. package/dist/src/background-jobs.js +8 -2
  15. package/dist/src/browser/bridge.js +268 -0
  16. package/dist/src/browser/chrome-profiles.js +73 -0
  17. package/dist/src/browser/framing.js +42 -0
  18. package/dist/src/browser/native-host.js +219 -0
  19. package/dist/src/browser/protocol.js +46 -0
  20. package/dist/src/browser/session-bridge.js +130 -0
  21. package/dist/src/cli-args.js +19 -5
  22. package/dist/src/client-environment.js +2 -0
  23. package/dist/src/core/clipboard.js +7 -13
  24. package/dist/src/core/image-limits.js +56 -0
  25. package/dist/src/core/image-path-extractor.js +70 -3
  26. package/dist/src/core/session-image-store.js +246 -0
  27. package/dist/src/edit-journal.js +33 -2
  28. package/dist/src/executor.js +25 -3
  29. package/dist/src/help-text.js +128 -22
  30. package/dist/src/job-follow-up.js +40 -0
  31. package/dist/src/mcp-client.js +335 -0
  32. package/dist/src/mcp-command.js +176 -0
  33. package/dist/src/mcp-config.js +123 -0
  34. package/dist/src/mcp-sdk.js +3 -0
  35. package/dist/src/mcp-types.js +26 -0
  36. package/dist/src/patcher.js +43 -4
  37. package/dist/src/permissions.js +301 -0
  38. package/dist/src/preferences.js +39 -0
  39. package/dist/src/project-key.js +11 -0
  40. package/dist/src/project-model-preferences.js +74 -0
  41. package/dist/src/quota-notice.js +35 -0
  42. package/dist/src/reasoning-effort.js +27 -0
  43. package/dist/src/session-safety.js +0 -12
  44. package/dist/src/session-store.js +123 -30
  45. package/dist/src/session.js +20 -4
  46. package/dist/src/signin.js +58 -0
  47. package/dist/src/tool-executor.js +26 -49
  48. package/dist/src/tools/browser.js +872 -0
  49. package/dist/src/tools/delete-file.js +20 -4
  50. package/dist/src/tools/index.js +32 -10
  51. package/dist/src/tools/patch-file.js +12 -26
  52. package/dist/src/tools/read-file.js +5 -0
  53. package/dist/src/tools/read-image-file.js +85 -0
  54. package/dist/src/tools/replace-document-text.js +28 -18
  55. package/dist/src/tools/restore-checkpoint.js +0 -1
  56. package/dist/src/tools/run-command.js +14 -71
  57. package/dist/src/tools/run-node-script.js +12 -81
  58. package/dist/src/tools/save-generated-image.js +120 -0
  59. package/dist/src/tools/str-replace.js +12 -26
  60. package/dist/src/tools/undo-edit.js +1 -6
  61. package/dist/src/tools/write-file.js +67 -11
  62. package/dist/src/ui/prompt-history-store.js +1 -1
  63. package/dist/src/ui/repl.js +1017 -299
  64. package/dist/src/ui/slash-commands.js +122 -0
  65. package/dist/src/ui/tui/attention.js +25 -0
  66. package/dist/src/ui/tui/bridge.js +38 -5
  67. package/dist/src/ui/tui/build-frame.js +807 -270
  68. package/dist/src/ui/tui/composer-layout.js +76 -0
  69. package/dist/src/ui/tui/desktop-notification.js +118 -0
  70. package/dist/src/ui/tui/markdown-render.js +21 -11
  71. package/dist/src/ui/tui/model-label.js +13 -0
  72. package/dist/src/ui/tui/shell-input.js +275 -73
  73. package/dist/src/ui/tui/shortcuts.js +61 -0
  74. package/dist/src/ui/tui/terminal-theme.js +28 -0
  75. package/dist/src/ui/tui/text.js +31 -6
  76. package/dist/src/ui/tui/user-input.js +593 -0
  77. package/dist/src/update-check.js +205 -0
  78. package/dist/src/usage-notice.js +52 -0
  79. package/dist/src/usage.js +5 -2
  80. package/dist/src/utils.js +13 -0
  81. package/dist/src/version.js +52 -2
  82. package/dist/vendor/mcp/LICENSES.txt +414 -0
  83. package/dist/vendor/mcp/client.cjs +82 -0
  84. package/package.json +22 -9
  85. package/dist/src/project-index.js +0 -233
  86. package/dist/src/tools/code-intel.js +0 -472
  87. package/dist/src/tools/find-symbol.js +0 -70
  88. package/dist/src/tools/hover-symbol.js +0 -95
  89. package/dist/src/tools/list-symbols.js +0 -55
  90. package/dist/src/tools/search-code.js +0 -37
  91. package/dist/src/tools/signature-help.js +0 -118
@@ -1 +1,55 @@
1
- export {};
1
+ function nonEmptyString(value) {
2
+ return typeof value === 'string' && value.trim().length > 0;
3
+ }
4
+ const USER_INPUT_ID_PATTERN = /^[a-z][a-z0-9_]*$/;
5
+ export function isUserInputQuestionArray(value) {
6
+ if (!Array.isArray(value) || value.length < 1 || value.length > 4) {
7
+ return false;
8
+ }
9
+ const questionIds = new Set();
10
+ return value.every((question) => {
11
+ if (!question || typeof question !== 'object' || Array.isArray(question)) {
12
+ return false;
13
+ }
14
+ const candidate = question;
15
+ if (!nonEmptyString(candidate.id) ||
16
+ !USER_INPUT_ID_PATTERN.test(candidate.id) ||
17
+ questionIds.has(candidate.id) ||
18
+ !nonEmptyString(candidate.header) ||
19
+ Array.from(candidate.header).length > 12 ||
20
+ !nonEmptyString(candidate.question) ||
21
+ typeof candidate.multiSelect !== 'boolean' ||
22
+ !Array.isArray(candidate.options) ||
23
+ candidate.options.length < 2 ||
24
+ candidate.options.length > 4) {
25
+ return false;
26
+ }
27
+ questionIds.add(candidate.id);
28
+ const optionIds = new Set();
29
+ const optionsValid = candidate.options.every((option) => {
30
+ if (!option || typeof option !== 'object' || Array.isArray(option)) {
31
+ return false;
32
+ }
33
+ const item = option;
34
+ if (!nonEmptyString(item.id) ||
35
+ !USER_INPUT_ID_PATTERN.test(item.id) ||
36
+ optionIds.has(item.id) ||
37
+ !nonEmptyString(item.label) ||
38
+ !nonEmptyString(item.description)) {
39
+ return false;
40
+ }
41
+ optionIds.add(item.id);
42
+ return true;
43
+ });
44
+ if (!optionsValid) {
45
+ return false;
46
+ }
47
+ if (candidate.recommendedOptionId !== undefined &&
48
+ (!nonEmptyString(candidate.recommendedOptionId) ||
49
+ candidate.recommendedOptionId !==
50
+ candidate.options[0].id)) {
51
+ return false;
52
+ }
53
+ return true;
54
+ });
55
+ }
@@ -0,0 +1 @@
1
+ export const DEFAULT_THEGITAI_HOST = 'https://thegit.ai';
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- const DEFAULT_SERVER_URL = 'https://thegit.ai';
2
+ import { DEFAULT_THEGITAI_HOST } from './default-host.js';
3
3
  export const TRACE_ID_HEADER = 'x-thegitai-trace-id';
4
4
  export const CLIENT_HEADER = 'x-thegitai-client';
5
5
  export const CLIENT_PLATFORM_HEADER = 'x-thegitai-client-platform';
@@ -7,12 +7,14 @@ export class ServerApiError extends Error {
7
7
  status;
8
8
  traceId;
9
9
  code;
10
- constructor(message, status, traceId, code = '') {
10
+ details;
11
+ constructor(message, status, traceId, code = '', details = {}) {
11
12
  super(traceId ? `${message}\nTrace ID: ${traceId}` : message);
12
13
  this.name = 'ServerApiError';
13
14
  this.status = status;
14
15
  this.traceId = traceId;
15
16
  this.code = code;
17
+ this.details = details;
16
18
  }
17
19
  }
18
20
  export function createTraceId() {
@@ -29,6 +31,14 @@ export function createTraceContext(traceId = createTraceId()) {
29
31
  };
30
32
  }
31
33
  export const REQUEST_TIMEOUT_MS = 8000;
34
+ export const STARTUP_REQUEST_TIMEOUT_MS = 3000;
35
+ export const STARTUP_DEADLINE_MS = 10_000;
36
+ export const STARTUP_RETRY_BUDGET = {
37
+ retries: 3,
38
+ baseDelayMs: 200,
39
+ deadlineMs: STARTUP_DEADLINE_MS,
40
+ timeoutMs: STARTUP_REQUEST_TIMEOUT_MS,
41
+ };
32
42
  const TRANSIENT_NETWORK_CODES = new Set([
33
43
  'ECONNRESET',
34
44
  'ECONNREFUSED',
@@ -60,7 +70,9 @@ export function isTransientNetworkError(error) {
60
70
  }
61
71
  return false;
62
72
  }
63
- export async function retryTransient(run, { retries = 2, baseDelayMs = 400 } = {}) {
73
+ export async function retryTransient(run, { retries = 2, baseDelayMs = 400, deadlineMs, now = () => Date.now(), } = {}) {
74
+ const startedAt = now();
75
+ const remainingMs = () => deadlineMs == null ? Infinity : deadlineMs - (now() - startedAt);
64
76
  let attempt = 0;
65
77
  for (;;) {
66
78
  try {
@@ -70,13 +82,15 @@ export async function retryTransient(run, { retries = 2, baseDelayMs = 400 } = {
70
82
  if (attempt >= retries || !isTransientNetworkError(error))
71
83
  throw error;
72
84
  const delayMs = baseDelayMs * 2 ** attempt;
85
+ if (remainingMs() <= delayMs)
86
+ throw error;
73
87
  attempt += 1;
74
88
  await new Promise((resolve) => setTimeout(resolve, delayMs));
75
89
  }
76
90
  }
77
91
  }
78
92
  export function normalizeServerUrl(serverUrl) {
79
- const normalized = String(serverUrl || DEFAULT_SERVER_URL)
93
+ const normalized = String(serverUrl || DEFAULT_THEGITAI_HOST)
80
94
  .trim()
81
95
  .replace(/\/+$/, '');
82
96
  if (!/^https?:\/\//i.test(normalized)) {
@@ -84,6 +98,101 @@ export function normalizeServerUrl(serverUrl) {
84
98
  }
85
99
  return normalized;
86
100
  }
101
+ const MAX_NON_JSON_BODY_CHARS = 200;
102
+ const GATEWAY_STATUS_MESSAGES = {
103
+ 502: 'Could not reach the TheGitAI server (bad gateway).',
104
+ 503: 'The TheGitAI server is temporarily unavailable.',
105
+ 504: 'The TheGitAI server did not respond in time (gateway timeout).',
106
+ 520: 'The connection to the TheGitAI server failed (edge error 520).',
107
+ 521: 'The TheGitAI server is not accepting connections (edge error 521).',
108
+ 522: 'The connection to the TheGitAI server timed out (edge error 522).',
109
+ 523: 'The TheGitAI server is unreachable (edge error 523).',
110
+ 524: 'The TheGitAI server did not respond in time (edge error 524).',
111
+ };
112
+ function truncateByCodePoint(text, maxChars) {
113
+ if (text.length <= maxChars)
114
+ return text;
115
+ const points = Array.from(text);
116
+ if (points.length <= maxChars)
117
+ return text;
118
+ return `${points.slice(0, maxChars).join('').trimEnd()}…`;
119
+ }
120
+ export function nonJsonErrorMessage(body, status) {
121
+ const rayId = /Cloudflare Ray ID:\s*(?:<[^>]*>\s*)*([0-9a-f]{8,})/i.exec(body)?.[1];
122
+ const gateway = GATEWAY_STATUS_MESSAGES[status];
123
+ const summary = truncateByCodePoint(body
124
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
125
+ .replace(/<[^>]*>/g, ' ')
126
+ .replace(/\s+/g, ' ')
127
+ .trim(), MAX_NON_JSON_BODY_CHARS);
128
+ const base = gateway ?? (summary || `Request failed with ${status}`);
129
+ return rayId ? `${base} (Cloudflare Ray ID: ${rayId})` : base;
130
+ }
131
+ const TRANSPORT_CODES = new Set([
132
+ 'ECONNRESET',
133
+ 'ECONNREFUSED',
134
+ 'ECONNABORTED',
135
+ 'EPIPE',
136
+ 'ETIMEDOUT',
137
+ 'ENOTFOUND',
138
+ 'EAI_AGAIN',
139
+ 'EHOSTUNREACH',
140
+ 'ENETUNREACH',
141
+ 'EPROTO',
142
+ 'ERR_STREAM_PREMATURE_CLOSE',
143
+ ]);
144
+ const TRANSPORT_PHRASES = [
145
+ [/\bsocket hang up\b/i, 'socket hang up'],
146
+ [/\bother side closed\b/i, 'other side closed'],
147
+ [/\bpremature close\b/i, 'premature close'],
148
+ [/\bterminated\b/i, 'terminated'],
149
+ [/\bfetch failed\b/i, 'fetch failed'],
150
+ [/\bnetwork timeout\b/i, 'network timeout'],
151
+ [/\bnetwork error\b/i, 'network error'],
152
+ [/\bheaders timeout\b/i, 'headers timeout'],
153
+ [/\bbody timeout\b/i, 'body timeout'],
154
+ ];
155
+ export function transportFailureDetail(error) {
156
+ if (error instanceof ServerApiError)
157
+ return null;
158
+ const parts = [];
159
+ const seen = new Set();
160
+ const queue = [error];
161
+ while (queue.length && seen.size < 24) {
162
+ const current = queue.shift();
163
+ if (!current || typeof current !== 'object' || seen.has(current))
164
+ continue;
165
+ seen.add(current);
166
+ const code = String(current.code ?? '');
167
+ if (TRANSPORT_CODES.has(code) || /^UND_ERR_[A-Z_]+$/.test(code)) {
168
+ if (!parts.includes(code))
169
+ parts.push(code);
170
+ }
171
+ const message = String(current.message ?? '');
172
+ for (const [pattern, label] of TRANSPORT_PHRASES) {
173
+ if (pattern.test(message) && !parts.includes(label))
174
+ parts.push(label);
175
+ }
176
+ if (current.cause)
177
+ queue.push(current.cause);
178
+ const nested = current.errors;
179
+ if (Array.isArray(nested))
180
+ queue.push(...nested);
181
+ }
182
+ return parts.length ? parts.slice(0, 3).join(' <- ') : null;
183
+ }
184
+ function isTransportFailure(error) {
185
+ return transportFailureDetail(error) !== null;
186
+ }
187
+ export function gatewayFailureCategory(error) {
188
+ if (isTransportFailure(error))
189
+ return 'connection_error';
190
+ if (!(error instanceof ServerApiError))
191
+ return null;
192
+ if (isQuotaExceededError(error))
193
+ return 'quota_exceeded';
194
+ return error.status in GATEWAY_STATUS_MESSAGES ? 'gateway_error' : null;
195
+ }
87
196
  export async function readJsonResponse(response) {
88
197
  const text = await response.text();
89
198
  if (!text.trim())
@@ -92,7 +201,9 @@ export async function readJsonResponse(response) {
92
201
  return JSON.parse(text);
93
202
  }
94
203
  catch {
95
- return { error: { message: text } };
204
+ return {
205
+ error: { message: nonJsonErrorMessage(text, response.status) },
206
+ };
96
207
  }
97
208
  }
98
209
  export function failureMessage(data, status) {
@@ -101,17 +212,37 @@ export function failureMessage(data, status) {
101
212
  export function failureCode(data) {
102
213
  return typeof data?.error?.code === 'string' ? data.error.code : '';
103
214
  }
215
+ export function failureDetails(data) {
216
+ const error = data?.error;
217
+ if (!error || typeof error !== 'object')
218
+ return {};
219
+ return {
220
+ ...(typeof error.window === 'string' ? { window: error.window } : {}),
221
+ ...(typeof error.resetsAt === 'string' ? { resetsAt: error.resetsAt } : {}),
222
+ ...(typeof error.percentLeft === 'number'
223
+ ? { percentLeft: error.percentLeft }
224
+ : {}),
225
+ };
226
+ }
227
+ export const QUOTA_EXCEEDED_CODE = 'QUOTA_EXCEEDED';
228
+ export function isQuotaExceededError(error) {
229
+ if (!(error instanceof ServerApiError))
230
+ return false;
231
+ if (error.code === QUOTA_EXCEEDED_CODE)
232
+ return true;
233
+ return error.status === 429 && !error.code;
234
+ }
104
235
  export function isAuthenticationError(error) {
105
236
  return error instanceof ServerApiError && error.status === 401;
106
237
  }
107
238
  export function authenticationErrorMessage(error) {
108
239
  return error.code === 'AUTH_TOKEN_EXPIRED'
109
- ? 'Your login expired after 24 hours of inactivity. Run `ai login` and resume this saved session.'
240
+ ? 'Your login expired after 48 hours of inactivity. Run `ai login` and resume this saved session.'
110
241
  : 'Your login is no longer valid. Run `ai login` and resume this saved session.';
111
242
  }
112
243
  export async function readErrorResponse(response, traceId = response.headers.get(TRACE_ID_HEADER) ?? '') {
113
244
  const data = await readJsonResponse(response);
114
- return new ServerApiError(failureMessage(data, response.status), response.status, traceId, failureCode(data));
245
+ return new ServerApiError(failureMessage(data, response.status), response.status, traceId, failureCode(data), failureDetails(data));
115
246
  }
116
247
  export async function authorizedJson({ config, path, method = 'GET', body = null, headers = {}, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS, }) {
117
248
  const trace = createTraceContext();
@@ -128,7 +259,7 @@ export async function authorizedJson({ config, path, method = 'GET', body = null
128
259
  });
129
260
  const data = await readJsonResponse(response);
130
261
  if (!response.ok) {
131
- throw new ServerApiError(failureMessage(data, response.status), response.status, trace.traceId, failureCode(data));
262
+ throw new ServerApiError(failureMessage(data, response.status), response.status, trace.traceId, failureCode(data), failureDetails(data));
132
263
  }
133
264
  return data;
134
265
  }
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync, } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { getClientStateDir } from '../client-state.js';
4
4
  import { REQUEST_TIMEOUT_MS, ServerApiError, createTraceContext, failureCode, failureMessage, normalizeServerUrl, readJsonResponse, retryTransient, } from './http.js';
@@ -14,7 +14,13 @@ function sanitizeModelInfo(raw) {
14
14
  if (!Number.isInteger(id) || id <= 0 || !label || !isCostRating(costRating)) {
15
15
  return null;
16
16
  }
17
- return { id, label, costRating, description };
17
+ return {
18
+ id,
19
+ label,
20
+ costRating,
21
+ description,
22
+ ...(value.auto === true ? { auto: true } : {}),
23
+ };
18
24
  }
19
25
  function isCostRating(value) {
20
26
  return Number.isInteger(value) && value >= 1 && value <= 3;
@@ -58,12 +64,21 @@ export function selectCacheForServer(cached, serverUrl) {
58
64
  export function writeCachedServerModels(cache, env = process.env) {
59
65
  const filePath = getModelsCachePath(env);
60
66
  mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
61
- writeFileSync(filePath, `${JSON.stringify(cache, null, 2)}\n`, {
62
- encoding: 'utf8',
63
- mode: 0o600,
64
- });
67
+ const tempPath = `${filePath}.${process.pid}.tmp`;
68
+ try {
69
+ writeFileSync(tempPath, `${JSON.stringify(cache, null, 2)}\n`, {
70
+ encoding: 'utf8',
71
+ mode: 0o600,
72
+ });
73
+ renameSync(tempPath, filePath);
74
+ }
75
+ catch (error) {
76
+ rmSync(tempPath, { force: true });
77
+ throw error;
78
+ }
65
79
  }
66
- export async function fetchServerModels({ config, fetchImpl = globalThis.fetch, }) {
80
+ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch, budget = {}, }) {
81
+ const { timeoutMs = REQUEST_TIMEOUT_MS, ...ladder } = budget;
67
82
  return retryTransient(async () => {
68
83
  const trace = createTraceContext();
69
84
  const response = await fetchImpl(`${normalizeServerUrl(config.serverUrl)}/v1/models`, {
@@ -71,7 +86,7 @@ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch,
71
86
  authorization: `Bearer ${config.token}`,
72
87
  ...trace.headers,
73
88
  },
74
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
89
+ signal: AbortSignal.timeout(timeoutMs),
75
90
  });
76
91
  const data = (await readJsonResponse(response));
77
92
  if (!response.ok) {
@@ -84,7 +99,7 @@ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch,
84
99
  throw new Error('Server returned an invalid model list.');
85
100
  }
86
101
  return { models };
87
- });
102
+ }, ladder);
88
103
  }
89
104
  export function selectServerModel({ requestedModelId, cached, serverModels, }) {
90
105
  const supportedIds = new Set(serverModels.models.map((model) => model.id));
@@ -113,6 +128,16 @@ export function validateServerModel(modelId, serverModels) {
113
128
  }
114
129
  return requested;
115
130
  }
131
+ export function resolveResumedSessionModel(storedModelId, serverModels) {
132
+ if (serverModels.models.some((model) => model.id === storedModelId)) {
133
+ return { modelId: storedModelId, fellBack: false };
134
+ }
135
+ const fallbackId = serverModels.models[0]?.id;
136
+ return {
137
+ modelId: fallbackId ?? storedModelId,
138
+ fellBack: fallbackId != null,
139
+ };
140
+ }
116
141
  export function updateSelectedModelCache({ config, selectedModelId, serverModels, env = process.env, }) {
117
142
  writeCachedServerModels({
118
143
  serverUrl: normalizeServerUrl(config.serverUrl),
@@ -0,0 +1,36 @@
1
+ import { fetchWhoamiResponse } from './auth.js';
2
+ import { STARTUP_RETRY_BUDGET, isTransientNetworkError, } from './http.js';
3
+ import { fetchServerModels } from './models.js';
4
+ import { abortableDelay, createTurnRecovery, isRetryableTurnFailure, isTurnRecoveryExhausted, } from './turn-recovery.js';
5
+ export async function loadStartupHandshake({ config, canStartOffline, fetchImpl, budget = STARTUP_RETRY_BUDGET, sleep = abortableDelay, onStatus = () => { }, }) {
6
+ let lastFailure;
7
+ const recovery = createTurnRecovery({
8
+ signal: new AbortController().signal,
9
+ sleep,
10
+ onStatus: (status) => onStatus(status, lastFailure),
11
+ });
12
+ const attempt = async () => {
13
+ const [models, whoami] = await Promise.allSettled([
14
+ fetchServerModels({ config, fetchImpl, budget }),
15
+ fetchWhoamiResponse({ config, fetchImpl, budget }),
16
+ ]);
17
+ const unreachable = models.status === 'rejected' &&
18
+ isRetryableTurnFailure(models.reason) &&
19
+ !(canStartOffline && isTransientNetworkError(models.reason));
20
+ if (unreachable) {
21
+ lastFailure = models.reason;
22
+ throw models.reason;
23
+ }
24
+ return { models, whoami };
25
+ };
26
+ try {
27
+ return await recovery.run('loading your models', attempt);
28
+ }
29
+ catch (error) {
30
+ const reason = isTurnRecoveryExhausted(error) ? error.cause : error;
31
+ return {
32
+ models: { status: 'rejected', reason },
33
+ whoami: { status: 'rejected', reason },
34
+ };
35
+ }
36
+ }
@@ -0,0 +1,189 @@
1
+ import { isTransientNetworkError, ServerApiError, transportFailureDetail, } from './http.js';
2
+ export const TURN_RECOVERY_DELAY_MS = 10_000;
3
+ export const TURN_RECOVERY_RETRIES = 3;
4
+ export const TURN_REQUEST_TIMEOUT_MS = 30_000;
5
+ export const TURN_STREAM_IDLE_TIMEOUT_MS = 60_000;
6
+ const RETRYABLE_TURN_STATUSES = new Set([408, 500, 502, 503, 504, 520, 521, 522, 523, 524]);
7
+ export function isRetryableTurnStatus(status) {
8
+ return RETRYABLE_TURN_STATUSES.has(status);
9
+ }
10
+ export function isRetryableTurnFailure(error) {
11
+ if (error instanceof ServerApiError)
12
+ return isRetryableTurnStatus(error.status);
13
+ return isTransientNetworkError(error);
14
+ }
15
+ export function interruptedStream(message = 'The turn stream ended before the turn finished.') {
16
+ return Object.assign(new Error(message), { code: 'ECONNRESET' });
17
+ }
18
+ export function formatTurnRecoveryStatus(status) {
19
+ if (status.phase === 'waiting') {
20
+ return `Connection interrupted · retrying in ${TURN_RECOVERY_DELAY_MS / 1000}s · retry ${status.retry}/${TURN_RECOVERY_RETRIES}`;
21
+ }
22
+ if (status.phase === 'reconnecting') {
23
+ return `Reconnecting · retry ${status.retry}/${TURN_RECOVERY_RETRIES}`;
24
+ }
25
+ if (status.phase === 'reconnected')
26
+ return 'Reconnected';
27
+ if (status.phase === 'continuing')
28
+ return 'Server restarted · continuing from the finished steps';
29
+ if (status.phase === 'continued')
30
+ return 'Server restarted · continued from the finished steps';
31
+ return 'Connection restored · continued the same turn';
32
+ }
33
+ export const TURN_RECOVERY_EXHAUSTED = 'TURN_RECOVERY_EXHAUSTED';
34
+ export function isTurnRecoveryExhausted(error) {
35
+ return error?.code === TURN_RECOVERY_EXHAUSTED;
36
+ }
37
+ function recoveryExhausted(operation, cause) {
38
+ const detail = transportFailureDetail(cause);
39
+ const reason = detail ?? (cause instanceof ServerApiError ? `HTTP ${cause.status}` : 'no response');
40
+ return Object.assign(new Error(`Connection lost while ${operation} (${reason}). Reconnecting failed after ${TURN_RECOVERY_RETRIES} retries. Some actions in this turn may already have completed.`, { cause }), { code: TURN_RECOVERY_EXHAUSTED });
41
+ }
42
+ export function abortableDelay(ms, signal) {
43
+ return new Promise((resolve, reject) => {
44
+ if (signal.aborted) {
45
+ reject(signal.reason);
46
+ return;
47
+ }
48
+ const onAbort = () => {
49
+ clearTimeout(timer);
50
+ reject(signal.reason);
51
+ };
52
+ const timer = setTimeout(() => {
53
+ signal.removeEventListener('abort', onAbort);
54
+ resolve();
55
+ }, ms);
56
+ signal.addEventListener('abort', onAbort, { once: true });
57
+ });
58
+ }
59
+ function untilAborted(promise, signal) {
60
+ if (signal.aborted)
61
+ return Promise.reject(signal.reason);
62
+ return new Promise((resolve, reject) => {
63
+ const onAbort = () => reject(signal.reason);
64
+ signal.addEventListener('abort', onAbort, { once: true });
65
+ promise
66
+ .then(resolve, reject)
67
+ .finally(() => signal.removeEventListener('abort', onAbort));
68
+ });
69
+ }
70
+ export function createTurnRecovery({ signal, onStatus = () => { }, sleep = abortableDelay, }) {
71
+ const affected = new Set();
72
+ let retry = 0;
73
+ let gate = null;
74
+ let exhausted = null;
75
+ async function retryAfter(token, operation, error, caller = signal) {
76
+ signal.throwIfAborted();
77
+ withdrawIfAborted(token, caller);
78
+ if (exhausted)
79
+ throw exhausted;
80
+ if (!isRetryableTurnFailure(error))
81
+ throw error;
82
+ affected.add(token);
83
+ if (!gate) {
84
+ if (retry === TURN_RECOVERY_RETRIES) {
85
+ exhausted = recoveryExhausted(operation, error);
86
+ throw exhausted;
87
+ }
88
+ retry += 1;
89
+ const current = retry;
90
+ onStatus({ phase: 'waiting', retry: current });
91
+ gate = sleep(TURN_RECOVERY_DELAY_MS, signal)
92
+ .then(() => {
93
+ signal.throwIfAborted();
94
+ onStatus({ phase: 'reconnecting', retry: current });
95
+ })
96
+ .finally(() => {
97
+ gate = null;
98
+ });
99
+ }
100
+ if (caller === signal) {
101
+ await gate;
102
+ return;
103
+ }
104
+ await untilAborted(gate, caller).catch((reason) => {
105
+ withdrawIfAborted(token, caller);
106
+ throw reason;
107
+ });
108
+ }
109
+ function withdrawIfAborted(token, caller) {
110
+ if (!caller.aborted)
111
+ return;
112
+ affected.delete(token);
113
+ throw caller.reason;
114
+ }
115
+ function reconnected(token) {
116
+ if (!affected.has(token) || gate || exhausted)
117
+ return;
118
+ onStatus({ phase: 'reconnected' });
119
+ }
120
+ function restored(token) {
121
+ if (!affected.delete(token))
122
+ return;
123
+ if (affected.size > 0 || gate || exhausted)
124
+ return;
125
+ retry = 0;
126
+ onStatus({ phase: 'restored' });
127
+ }
128
+ async function run(operation, attempt, caller = signal) {
129
+ const token = {};
130
+ for (;;) {
131
+ signal.throwIfAborted();
132
+ withdrawIfAborted(token, caller);
133
+ if (exhausted)
134
+ throw exhausted;
135
+ try {
136
+ const value = await attempt();
137
+ restored(token);
138
+ return value;
139
+ }
140
+ catch (error) {
141
+ await retryAfter(token, operation, error, caller);
142
+ }
143
+ }
144
+ }
145
+ return { run, retryAfter, reconnected, restored };
146
+ }
147
+ export async function fetchTurnAttempt(fetchImpl, url, init, signal, { readBody = false } = {}) {
148
+ const controller = new AbortController();
149
+ const onAbort = () => controller.abort(signal.reason);
150
+ signal.addEventListener('abort', onAbort, { once: true });
151
+ if (signal.aborted)
152
+ onAbort();
153
+ const timer = setTimeout(() => controller.abort(new DOMException('The request did not get a response in time.', 'TimeoutError')), TURN_REQUEST_TIMEOUT_MS);
154
+ try {
155
+ const response = await fetchImpl(url, { ...init, signal: controller.signal });
156
+ if (!readBody && response.ok)
157
+ return response;
158
+ return new Response(await response.arrayBuffer(), {
159
+ status: response.status,
160
+ headers: response.headers,
161
+ });
162
+ }
163
+ finally {
164
+ clearTimeout(timer);
165
+ signal.removeEventListener('abort', onAbort);
166
+ }
167
+ }
168
+ export async function readTurnChunk(reader, signal) {
169
+ let timer;
170
+ let onAbort;
171
+ try {
172
+ return await Promise.race([
173
+ reader.read(),
174
+ new Promise((_, reject) => {
175
+ timer = setTimeout(() => reject(interruptedStream(`The turn stream sent nothing for ${TURN_STREAM_IDLE_TIMEOUT_MS / 1000} seconds.`)), TURN_STREAM_IDLE_TIMEOUT_MS);
176
+ onAbort = () => reject(signal.reason);
177
+ signal.addEventListener('abort', onAbort, { once: true });
178
+ if (signal.aborted)
179
+ onAbort();
180
+ }),
181
+ ]);
182
+ }
183
+ finally {
184
+ if (timer)
185
+ clearTimeout(timer);
186
+ if (onAbort)
187
+ signal.removeEventListener('abort', onAbort);
188
+ }
189
+ }
@@ -1,6 +1,6 @@
1
1
  import chalk from './colors.js';
2
2
  import { spawn } from 'child_process';
3
- import { buildCommandEnv, commandUsesSudo, sanitizeCommandText, terminateChild, } from './executor.js';
3
+ import { buildCommandEnv, commandUsesSudo, resolveCommandShell, sanitizeCommandText, terminateChild, } from './executor.js';
4
4
  import { isTuiMode } from './runtime-mode.js';
5
5
  import { redactConnectionStringCredentials } from './secret-preview.js';
6
6
  const MAX_RUNNING_JOBS = 8;
@@ -196,7 +196,7 @@ export async function startBackgroundJob(command, cwd, { startupWaitMs, sessionI
196
196
  const id = `bg_${++jobCounter}`;
197
197
  const child = spawn(command, {
198
198
  cwd,
199
- shell: true,
199
+ shell: resolveCommandShell(),
200
200
  detached: process.platform !== 'win32',
201
201
  stdio: ['pipe', 'pipe', 'pipe'],
202
202
  env: buildCommandEnv(cwd),
@@ -265,6 +265,7 @@ export function getJobOutputTail(id, maxLines) {
265
265
  if (!record || !belongsToSession(record) || maxLines <= 0)
266
266
  return [];
267
267
  const lines = sanitizeJobText(record, record.buffer)
268
+ .replace(/\r\n?/g, '\n')
268
269
  .split('\n')
269
270
  .filter((line) => line.trim().length > 0);
270
271
  return lines.slice(-maxLines);
@@ -277,6 +278,7 @@ export function getJobOutputPreview(id, maxTailLines) {
277
278
  ? sanitizeJobText(record, record.firstOutputLine).trim()
278
279
  : '';
279
280
  return {
281
+ droppedChars: Math.max(record.totalCaptured - record.buffer.length, 0),
280
282
  firstLine,
281
283
  tailLines: getJobOutputTail(id, maxTailLines),
282
284
  };
@@ -401,6 +403,10 @@ export function drainBackgroundJobNotifications({ sessionId } = {}) {
401
403
  const hasReadableFinalOutput = pending.some((snapshot) => snapshot.status !== 'killed');
402
404
  return `${lines.join(' ')}${hasReadableFinalOutput ? ' Use shell_job_output to read any final output.' : ''}`;
403
405
  }
406
+ export function hasUnreportedBackgroundJobUpdate(id, { sessionId } = {}) {
407
+ const filter = sessionFilter(sessionId);
408
+ return pendingModelNotifications.some((snapshot) => snapshot.id === id && (!filter || snapshot.sessionId === filter));
409
+ }
404
410
  function unknownJobError(id) {
405
411
  const known = listBackgroundJobs().map((job) => job.id);
406
412
  const hint = known.length