@thegitai/cli 1.0.0-preview.9 → 1.0.1

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 (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +139 -111
  4. package/dist/bin/browser-host.js +284 -0
  5. package/dist/src/agent-mode.js +33 -7
  6. package/dist/src/api/auth.js +8 -2
  7. package/dist/src/api/browser-login.js +77 -34
  8. package/dist/src/api/chat.js +702 -173
  9. package/dist/src/api/contracts.js +55 -1
  10. package/dist/src/api/default-host.js +1 -0
  11. package/dist/src/api/http.js +168 -8
  12. package/dist/src/api/models.js +75 -10
  13. package/dist/src/api/startup-handshake.js +36 -0
  14. package/dist/src/api/turn-recovery.js +189 -0
  15. package/dist/src/background-jobs.js +14 -4
  16. package/dist/src/browser/bridge.js +268 -0
  17. package/dist/src/browser/chrome-profiles.js +73 -0
  18. package/dist/src/browser/framing.js +42 -0
  19. package/dist/src/browser/native-host.js +219 -0
  20. package/dist/src/browser/protocol.js +46 -0
  21. package/dist/src/browser/session-bridge.js +130 -0
  22. package/dist/src/cli-args.js +19 -5
  23. package/dist/src/client-environment.js +2 -0
  24. package/dist/src/core/clipboard.js +8 -14
  25. package/dist/src/core/image-limits.js +56 -0
  26. package/dist/src/core/image-path-extractor.js +70 -3
  27. package/dist/src/core/session-image-store.js +271 -0
  28. package/dist/src/edit-journal.js +33 -2
  29. package/dist/src/executor.js +26 -4
  30. package/dist/src/help-text.js +152 -41
  31. package/dist/src/install-id.js +32 -0
  32. package/dist/src/job-follow-up.js +40 -0
  33. package/dist/src/mcp-client.js +335 -0
  34. package/dist/src/mcp-command.js +176 -0
  35. package/dist/src/mcp-config.js +123 -0
  36. package/dist/src/mcp-sdk.js +3 -0
  37. package/dist/src/mcp-types.js +26 -0
  38. package/dist/src/patcher.js +46 -4
  39. package/dist/src/permissions.js +301 -0
  40. package/dist/src/preferences.js +39 -0
  41. package/dist/src/project-key.js +11 -0
  42. package/dist/src/project-model-preferences.js +74 -0
  43. package/dist/src/quota-notice.js +62 -0
  44. package/dist/src/reasoning-effort.js +27 -0
  45. package/dist/src/scratch-dir.js +6 -2
  46. package/dist/src/session-context.js +11 -0
  47. package/dist/src/session-safety.js +0 -12
  48. package/dist/src/session-store.js +76 -10
  49. package/dist/src/session.js +14 -4
  50. package/dist/src/signin.js +58 -0
  51. package/dist/src/skills/discovery.js +280 -0
  52. package/dist/src/skills/frontmatter.js +192 -0
  53. package/dist/src/skills/install.js +394 -0
  54. package/dist/src/skills/types.js +43 -0
  55. package/dist/src/skills-command.js +71 -0
  56. package/dist/src/todo-list.js +16 -9
  57. package/dist/src/tool-executor.js +42 -51
  58. package/dist/src/tools/browser.js +928 -0
  59. package/dist/src/tools/delete-file.js +21 -5
  60. package/dist/src/tools/index.js +34 -10
  61. package/dist/src/tools/patch-file.js +14 -29
  62. package/dist/src/tools/read-file.js +7 -1
  63. package/dist/src/tools/read-image-file.js +85 -0
  64. package/dist/src/tools/replace-document-text.js +28 -18
  65. package/dist/src/tools/restore-checkpoint.js +1 -2
  66. package/dist/src/tools/run-command.js +14 -71
  67. package/dist/src/tools/run-node-script.js +13 -82
  68. package/dist/src/tools/save-generated-image.js +120 -0
  69. package/dist/src/tools/shell-diagnostics.js +248 -72
  70. package/dist/src/tools/str-replace.js +14 -29
  71. package/dist/src/tools/undo-edit.js +2 -7
  72. package/dist/src/tools/use-skill.js +38 -0
  73. package/dist/src/tools/write-file.js +69 -14
  74. package/dist/src/ui/repl.js +1141 -299
  75. package/dist/src/ui/slash-commands.js +140 -0
  76. package/dist/src/ui/tui/attention.js +25 -0
  77. package/dist/src/ui/tui/bridge.js +38 -5
  78. package/dist/src/ui/tui/build-frame.js +858 -303
  79. package/dist/src/ui/tui/composer-layout.js +76 -0
  80. package/dist/src/ui/tui/desktop-notification.js +118 -0
  81. package/dist/src/ui/tui/markdown-render.js +21 -11
  82. package/dist/src/ui/tui/model-label.js +13 -0
  83. package/dist/src/ui/tui/shell-input.js +266 -61
  84. package/dist/src/ui/tui/shortcuts.js +61 -0
  85. package/dist/src/ui/tui/terminal-theme.js +28 -0
  86. package/dist/src/ui/tui/text.js +31 -6
  87. package/dist/src/ui/tui/user-input.js +593 -0
  88. package/dist/src/update-check.js +205 -0
  89. package/dist/src/usage-notice.js +52 -0
  90. package/dist/src/usage.js +25 -2
  91. package/dist/src/utils.js +4 -0
  92. package/dist/src/version.js +52 -2
  93. package/dist/vendor/mcp/LICENSES.txt +414 -0
  94. package/dist/vendor/mcp/client.cjs +82 -0
  95. package/package.json +22 -9
  96. package/dist/src/project-index.js +0 -233
  97. package/dist/src/tools/code-intel.js +0 -472
  98. package/dist/src/tools/find-symbol.js +0 -70
  99. package/dist/src/tools/hover-symbol.js +0 -95
  100. package/dist/src/tools/list-symbols.js +0 -55
  101. package/dist/src/tools/search-code.js +0 -37
  102. 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,34 +1,48 @@
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
+ import { getInstallId } from '../install-id.js';
3
4
  export const TRACE_ID_HEADER = 'x-thegitai-trace-id';
4
5
  export const CLIENT_HEADER = 'x-thegitai-client';
5
6
  export const CLIENT_PLATFORM_HEADER = 'x-thegitai-client-platform';
7
+ export const INSTALL_ID_HEADER = 'x-thegitai-install-id';
6
8
  export class ServerApiError extends Error {
7
9
  status;
8
10
  traceId;
9
11
  code;
10
- constructor(message, status, traceId, code = '') {
12
+ details;
13
+ constructor(message, status, traceId, code = '', details = {}) {
11
14
  super(traceId ? `${message}\nTrace ID: ${traceId}` : message);
12
15
  this.name = 'ServerApiError';
13
16
  this.status = status;
14
17
  this.traceId = traceId;
15
18
  this.code = code;
19
+ this.details = details;
16
20
  }
17
21
  }
18
22
  export function createTraceId() {
19
23
  return `tr_${randomUUID().replace(/-/g, '')}`;
20
24
  }
21
25
  export function createTraceContext(traceId = createTraceId()) {
26
+ const installId = getInstallId();
22
27
  return {
23
28
  traceId,
24
29
  headers: {
25
30
  [TRACE_ID_HEADER]: traceId,
26
31
  [CLIENT_HEADER]: 'cli',
27
32
  [CLIENT_PLATFORM_HEADER]: `${process.platform}/${process.arch}`,
33
+ ...(installId ? { [INSTALL_ID_HEADER]: installId } : {}),
28
34
  },
29
35
  };
30
36
  }
31
37
  export const REQUEST_TIMEOUT_MS = 8000;
38
+ export const STARTUP_REQUEST_TIMEOUT_MS = 3000;
39
+ export const STARTUP_DEADLINE_MS = 10_000;
40
+ export const STARTUP_RETRY_BUDGET = {
41
+ retries: 3,
42
+ baseDelayMs: 200,
43
+ deadlineMs: STARTUP_DEADLINE_MS,
44
+ timeoutMs: STARTUP_REQUEST_TIMEOUT_MS,
45
+ };
32
46
  const TRANSIENT_NETWORK_CODES = new Set([
33
47
  'ECONNRESET',
34
48
  'ECONNREFUSED',
@@ -60,7 +74,9 @@ export function isTransientNetworkError(error) {
60
74
  }
61
75
  return false;
62
76
  }
63
- export async function retryTransient(run, { retries = 2, baseDelayMs = 400 } = {}) {
77
+ export async function retryTransient(run, { retries = 2, baseDelayMs = 400, deadlineMs, now = () => Date.now(), } = {}) {
78
+ const startedAt = now();
79
+ const remainingMs = () => deadlineMs == null ? Infinity : deadlineMs - (now() - startedAt);
64
80
  let attempt = 0;
65
81
  for (;;) {
66
82
  try {
@@ -70,13 +86,15 @@ export async function retryTransient(run, { retries = 2, baseDelayMs = 400 } = {
70
86
  if (attempt >= retries || !isTransientNetworkError(error))
71
87
  throw error;
72
88
  const delayMs = baseDelayMs * 2 ** attempt;
89
+ if (remainingMs() <= delayMs)
90
+ throw error;
73
91
  attempt += 1;
74
92
  await new Promise((resolve) => setTimeout(resolve, delayMs));
75
93
  }
76
94
  }
77
95
  }
78
96
  export function normalizeServerUrl(serverUrl) {
79
- const normalized = String(serverUrl || DEFAULT_SERVER_URL)
97
+ const normalized = String(serverUrl || DEFAULT_THEGITAI_HOST)
80
98
  .trim()
81
99
  .replace(/\/+$/, '');
82
100
  if (!/^https?:\/\//i.test(normalized)) {
@@ -84,6 +102,103 @@ export function normalizeServerUrl(serverUrl) {
84
102
  }
85
103
  return normalized;
86
104
  }
105
+ const MAX_NON_JSON_BODY_CHARS = 200;
106
+ const GATEWAY_STATUS_MESSAGES = {
107
+ 502: 'Could not reach the TheGitAI server (bad gateway).',
108
+ 503: 'The TheGitAI server is temporarily unavailable.',
109
+ 504: 'The TheGitAI server did not respond in time (gateway timeout).',
110
+ 520: 'The connection to the TheGitAI server failed (edge error 520).',
111
+ 521: 'The TheGitAI server is not accepting connections (edge error 521).',
112
+ 522: 'The connection to the TheGitAI server timed out (edge error 522).',
113
+ 523: 'The TheGitAI server is unreachable (edge error 523).',
114
+ 524: 'The TheGitAI server did not respond in time (edge error 524).',
115
+ };
116
+ function truncateByCodePoint(text, maxChars) {
117
+ if (text.length <= maxChars)
118
+ return text;
119
+ const points = Array.from(text);
120
+ if (points.length <= maxChars)
121
+ return text;
122
+ return `${points.slice(0, maxChars).join('').trimEnd()}…`;
123
+ }
124
+ export function nonJsonErrorMessage(body, status) {
125
+ const rayId = /Cloudflare Ray ID:\s*(?:<[^>]*>\s*)*([0-9a-f]{8,})/i.exec(body)?.[1];
126
+ const gateway = GATEWAY_STATUS_MESSAGES[status];
127
+ const summary = truncateByCodePoint(body
128
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
129
+ .replace(/<[^>]*>/g, ' ')
130
+ .replace(/\s+/g, ' ')
131
+ .trim(), MAX_NON_JSON_BODY_CHARS);
132
+ const base = gateway ?? (summary || `Request failed with ${status}`);
133
+ return rayId ? `${base} (Cloudflare Ray ID: ${rayId})` : base;
134
+ }
135
+ const TRANSPORT_CODES = new Set([
136
+ 'ECONNRESET',
137
+ 'ECONNREFUSED',
138
+ 'ECONNABORTED',
139
+ 'EPIPE',
140
+ 'ETIMEDOUT',
141
+ 'ENOTFOUND',
142
+ 'EAI_AGAIN',
143
+ 'EHOSTUNREACH',
144
+ 'ENETUNREACH',
145
+ 'EPROTO',
146
+ 'ERR_STREAM_PREMATURE_CLOSE',
147
+ ]);
148
+ const TRANSPORT_PHRASES = [
149
+ [/\bsocket hang up\b/i, 'socket hang up'],
150
+ [/\bother side closed\b/i, 'other side closed'],
151
+ [/\bpremature close\b/i, 'premature close'],
152
+ [/\bterminated\b/i, 'terminated'],
153
+ [/\bfetch failed\b/i, 'fetch failed'],
154
+ [/\bnetwork timeout\b/i, 'network timeout'],
155
+ [/\bnetwork error\b/i, 'network error'],
156
+ [/\bheaders timeout\b/i, 'headers timeout'],
157
+ [/\bbody timeout\b/i, 'body timeout'],
158
+ ];
159
+ export function transportFailureDetail(error) {
160
+ if (error instanceof ServerApiError)
161
+ return null;
162
+ const parts = [];
163
+ const seen = new Set();
164
+ const queue = [error];
165
+ while (queue.length && seen.size < 24) {
166
+ const current = queue.shift();
167
+ if (!current || typeof current !== 'object' || seen.has(current))
168
+ continue;
169
+ seen.add(current);
170
+ const code = String(current.code ?? '');
171
+ if (TRANSPORT_CODES.has(code) || /^UND_ERR_[A-Z_]+$/.test(code)) {
172
+ if (!parts.includes(code))
173
+ parts.push(code);
174
+ }
175
+ const message = String(current.message ?? '');
176
+ for (const [pattern, label] of TRANSPORT_PHRASES) {
177
+ if (pattern.test(message) && !parts.includes(label))
178
+ parts.push(label);
179
+ }
180
+ if (current.cause)
181
+ queue.push(current.cause);
182
+ const nested = current.errors;
183
+ if (Array.isArray(nested))
184
+ queue.push(...nested);
185
+ }
186
+ return parts.length ? parts.slice(0, 3).join(' <- ') : null;
187
+ }
188
+ function isTransportFailure(error) {
189
+ return transportFailureDetail(error) !== null;
190
+ }
191
+ export function gatewayFailureCategory(error) {
192
+ if (isTransportFailure(error))
193
+ return 'connection_error';
194
+ if (!(error instanceof ServerApiError))
195
+ return null;
196
+ if (isQuotaExceededError(error))
197
+ return 'quota_exceeded';
198
+ if (isPlanRequiredError(error))
199
+ return 'plan_required';
200
+ return error.status in GATEWAY_STATUS_MESSAGES ? 'gateway_error' : null;
201
+ }
87
202
  export async function readJsonResponse(response) {
88
203
  const text = await response.text();
89
204
  if (!text.trim())
@@ -92,7 +207,9 @@ export async function readJsonResponse(response) {
92
207
  return JSON.parse(text);
93
208
  }
94
209
  catch {
95
- return { error: { message: text } };
210
+ return {
211
+ error: { message: nonJsonErrorMessage(text, response.status) },
212
+ };
96
213
  }
97
214
  }
98
215
  export function failureMessage(data, status) {
@@ -101,17 +218,60 @@ export function failureMessage(data, status) {
101
218
  export function failureCode(data) {
102
219
  return typeof data?.error?.code === 'string' ? data.error.code : '';
103
220
  }
221
+ export function failureDetails(data) {
222
+ const error = data?.error;
223
+ if (!error || typeof error !== 'object')
224
+ return {};
225
+ return {
226
+ ...(typeof error.window === 'string' ? { window: error.window } : {}),
227
+ ...(typeof error.resetsAt === 'string' ? { resetsAt: error.resetsAt } : {}),
228
+ ...(typeof error.percentLeft === 'number'
229
+ ? { percentLeft: error.percentLeft }
230
+ : {}),
231
+ ...(error.autoAvailable === true ? { autoAvailable: true } : {}),
232
+ ...(isWebUrl(error.upgradeUrl) ? { upgradeUrl: error.upgradeUrl } : {}),
233
+ };
234
+ }
235
+ function isWebUrl(value) {
236
+ if (typeof value !== 'string')
237
+ return false;
238
+ try {
239
+ const url = new URL(value);
240
+ return url.protocol === 'https:' || url.protocol === 'http:';
241
+ }
242
+ catch {
243
+ return false;
244
+ }
245
+ }
246
+ export const QUOTA_EXCEEDED_CODE = 'QUOTA_EXCEEDED';
247
+ export function isQuotaExceededError(error) {
248
+ if (!(error instanceof ServerApiError))
249
+ return false;
250
+ if (error.code === QUOTA_EXCEEDED_CODE)
251
+ return true;
252
+ return error.status === 429 && !error.code;
253
+ }
254
+ export const PLAN_REQUIRED_CODE = 'PLAN_REQUIRED';
255
+ export function isPlanRequiredError(error) {
256
+ return error instanceof ServerApiError && error.code === PLAN_REQUIRED_CODE;
257
+ }
258
+ const ACCOUNT_REFUSAL_CODES = new Set(['ACCOUNT_ACTIVITY_REVIEW', 'PHONE_VERIFICATION_REQUIRED']);
259
+ export function isTurnRefusal(error) {
260
+ return (isPlanRequiredError(error) ||
261
+ isQuotaExceededError(error) ||
262
+ (error instanceof ServerApiError && ACCOUNT_REFUSAL_CODES.has(error.code)));
263
+ }
104
264
  export function isAuthenticationError(error) {
105
265
  return error instanceof ServerApiError && error.status === 401;
106
266
  }
107
267
  export function authenticationErrorMessage(error) {
108
268
  return error.code === 'AUTH_TOKEN_EXPIRED'
109
- ? 'Your login expired after 24 hours of inactivity. Run `ai login` and resume this saved session.'
269
+ ? 'Your login expired after 48 hours of inactivity. Run `ai login` and resume this saved session.'
110
270
  : 'Your login is no longer valid. Run `ai login` and resume this saved session.';
111
271
  }
112
272
  export async function readErrorResponse(response, traceId = response.headers.get(TRACE_ID_HEADER) ?? '') {
113
273
  const data = await readJsonResponse(response);
114
- return new ServerApiError(failureMessage(data, response.status), response.status, traceId, failureCode(data));
274
+ return new ServerApiError(failureMessage(data, response.status), response.status, traceId, failureCode(data), failureDetails(data));
115
275
  }
116
276
  export async function authorizedJson({ config, path, method = 'GET', body = null, headers = {}, fetchImpl = globalThis.fetch, timeoutMs = REQUEST_TIMEOUT_MS, }) {
117
277
  const trace = createTraceContext();
@@ -128,7 +288,7 @@ export async function authorizedJson({ config, path, method = 'GET', body = null
128
288
  });
129
289
  const data = await readJsonResponse(response);
130
290
  if (!response.ok) {
131
- throw new ServerApiError(failureMessage(data, response.status), response.status, trace.traceId, failureCode(data));
291
+ throw new ServerApiError(failureMessage(data, response.status), response.status, trace.traceId, failureCode(data), failureDetails(data));
132
292
  }
133
293
  return data;
134
294
  }
@@ -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,42 @@ 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
+ const locked = isModelLock(value.locked) ? value.locked : undefined;
18
+ const comparison = sanitizeComparison(value.comparison);
19
+ return {
20
+ id,
21
+ label,
22
+ costRating,
23
+ description,
24
+ ...(locked ? { locked } : {}),
25
+ ...(value.auto === true ? { auto: true } : {}),
26
+ ...(comparison ? { comparison } : {}),
27
+ };
28
+ }
29
+ function isModelLock(value) {
30
+ return value === 'plan' || value === 'auto-only';
31
+ }
32
+ function sanitizeComparison(raw) {
33
+ if (!raw || typeof raw !== 'object')
34
+ return undefined;
35
+ const value = raw;
36
+ if ((value.intelligenceScore !== null &&
37
+ (typeof value.intelligenceScore !== 'number' || !Number.isFinite(value.intelligenceScore) ||
38
+ value.intelligenceScore < 0 || value.intelligenceScore > 100)) ||
39
+ typeof value.responseTimeMs !== 'number' || !Number.isFinite(value.responseTimeMs) ||
40
+ value.responseTimeMs <= 0 || typeof value.benchmarkLabel !== 'string' ||
41
+ typeof value.benchmarkUrl !== 'string' || !/^https?:\/\//.test(value.benchmarkUrl) ||
42
+ (value.evaluationNote !== null && typeof value.evaluationNote !== 'string') ||
43
+ typeof value.updatedAt !== 'string' || !Number.isFinite(Date.parse(value.updatedAt)))
44
+ return undefined;
45
+ return {
46
+ intelligenceScore: value.intelligenceScore,
47
+ benchmarkLabel: value.benchmarkLabel,
48
+ benchmarkUrl: value.benchmarkUrl,
49
+ evaluationNote: value.evaluationNote,
50
+ responseTimeMs: value.responseTimeMs,
51
+ updatedAt: value.updatedAt,
52
+ };
18
53
  }
19
54
  function isCostRating(value) {
20
55
  return Number.isInteger(value) && value >= 1 && value <= 3;
@@ -58,12 +93,21 @@ export function selectCacheForServer(cached, serverUrl) {
58
93
  export function writeCachedServerModels(cache, env = process.env) {
59
94
  const filePath = getModelsCachePath(env);
60
95
  mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
61
- writeFileSync(filePath, `${JSON.stringify(cache, null, 2)}\n`, {
62
- encoding: 'utf8',
63
- mode: 0o600,
64
- });
96
+ const tempPath = `${filePath}.${process.pid}.tmp`;
97
+ try {
98
+ writeFileSync(tempPath, `${JSON.stringify(cache, null, 2)}\n`, {
99
+ encoding: 'utf8',
100
+ mode: 0o600,
101
+ });
102
+ renameSync(tempPath, filePath);
103
+ }
104
+ catch (error) {
105
+ rmSync(tempPath, { force: true });
106
+ throw error;
107
+ }
65
108
  }
66
- export async function fetchServerModels({ config, fetchImpl = globalThis.fetch, }) {
109
+ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch, budget = {}, }) {
110
+ const { timeoutMs = REQUEST_TIMEOUT_MS, ...ladder } = budget;
67
111
  return retryTransient(async () => {
68
112
  const trace = createTraceContext();
69
113
  const response = await fetchImpl(`${normalizeServerUrl(config.serverUrl)}/v1/models`, {
@@ -71,7 +115,7 @@ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch,
71
115
  authorization: `Bearer ${config.token}`,
72
116
  ...trace.headers,
73
117
  },
74
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
118
+ signal: AbortSignal.timeout(timeoutMs),
75
119
  });
76
120
  const data = (await readJsonResponse(response));
77
121
  if (!response.ok) {
@@ -83,8 +127,11 @@ export async function fetchServerModels({ config, fetchImpl = globalThis.fetch,
83
127
  if (models.length === 0) {
84
128
  throw new Error('Server returned an invalid model list.');
85
129
  }
86
- return { models };
87
- });
130
+ return { models: models.map((model) => {
131
+ const comparison = sanitizeComparison(data?.comparisons?.[model.id]);
132
+ return comparison ? { ...model, comparison } : model;
133
+ }) };
134
+ }, ladder);
88
135
  }
89
136
  export function selectServerModel({ requestedModelId, cached, serverModels, }) {
90
137
  const supportedIds = new Set(serverModels.models.map((model) => model.id));
@@ -95,6 +142,14 @@ export function selectServerModel({ requestedModelId, cached, serverModels, }) {
95
142
  }
96
143
  throw new Error(`Server does not support model "${requested}".`);
97
144
  }
145
+ const unlockedIds = new Set(serverModels.models.filter((model) => !model.locked).map((model) => model.id));
146
+ const firstUnlocked = serverModels.models.find((model) => !model.locked)?.id;
147
+ for (const candidate of [cached?.selectedModelId, serverModels.models[0]?.id, firstUnlocked]) {
148
+ const id = Number(candidate);
149
+ if (Number.isInteger(id) && unlockedIds.has(id)) {
150
+ return id;
151
+ }
152
+ }
98
153
  for (const candidate of [cached?.selectedModelId, serverModels.models[0]?.id]) {
99
154
  const id = Number(candidate);
100
155
  if (Number.isInteger(id) && supportedIds.has(id)) {
@@ -113,6 +168,16 @@ export function validateServerModel(modelId, serverModels) {
113
168
  }
114
169
  return requested;
115
170
  }
171
+ export function resolveResumedSessionModel(storedModelId, serverModels) {
172
+ if (serverModels.models.some((model) => model.id === storedModelId)) {
173
+ return { modelId: storedModelId, fellBack: false };
174
+ }
175
+ const fallbackId = serverModels.models[0]?.id;
176
+ return {
177
+ modelId: fallbackId ?? storedModelId,
178
+ fellBack: fallbackId != null,
179
+ };
180
+ }
116
181
  export function updateSelectedModelCache({ config, selectedModelId, serverModels, env = process.env, }) {
117
182
  writeCachedServerModels({
118
183
  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
+ }