@tolmete/cli 0.2.9 → 0.2.11

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.
@@ -0,0 +1,1868 @@
1
+ #!/usr/bin/env node
2
+ if(+process.versions.node.split(".")[0]<22)process.exit(64);
3
+
4
+ // src/cli.ts
5
+ import { existsSync } from "node:fs";
6
+ import { dirname as dirname4, join as join7 } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ // src/util.ts
10
+ import { createHash } from "node:crypto";
11
+ import { homedir } from "node:os";
12
+ var SECOND_MS = 1e3;
13
+ var MINUTE_MS = 60 * SECOND_MS;
14
+ var HOUR_MS = 60 * MINUTE_MS;
15
+ var DAY_MS = 24 * HOUR_MS;
16
+ var sha256 = (value) => createHash("sha256").update(value).digest("hex");
17
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
18
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19
+ var errCode = (error) => isRecord(error) && typeof error.code === "string" ? error.code : void 0;
20
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
21
+ var neutralSpawn = () => ({
22
+ cwd: homedir(),
23
+ env: { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" }
24
+ });
25
+
26
+ // src/api.ts
27
+ var TIMEOUT_MS = 15 * SECOND_MS;
28
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
29
+ var ORGANIZATION_HEADER = "x-tolmete-organization-id";
30
+ var USER_HEADER = "x-tolmete-user-id";
31
+ var assertApiUrl = (value) => {
32
+ const url = new URL(value);
33
+ const secure = url.protocol === "https:";
34
+ const local = url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);
35
+ if (!secure && !local) throw new Error("The API URL must be https.");
36
+ if (url.username || url.password || url.search || url.hash) throw new Error("Invalid API URL.");
37
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
38
+ };
39
+ var endpoints = (apiUrl) => ({
40
+ register: `${apiUrl}/oauth/register`,
41
+ authorize: `${apiUrl}/oauth/authorize`,
42
+ token: `${apiUrl}/oauth/token`,
43
+ revoke: `${apiUrl}/oauth/revoke`,
44
+ events: `${apiUrl}/api/ai-usage/events`,
45
+ repositories: `${apiUrl}/api/ai-usage/repositories`,
46
+ /** The OAuth resource the usage tokens are bound to. */
47
+ resource: `${apiUrl}/api/ai-usage`
48
+ });
49
+ var request = async (url, input = {}, timeoutMs = TIMEOUT_MS) => {
50
+ try {
51
+ const res = await fetch(url, {
52
+ ...input,
53
+ signal: AbortSignal.timeout(timeoutMs),
54
+ redirect: "error"
55
+ });
56
+ const text = await res.text();
57
+ let json = null;
58
+ try {
59
+ json = JSON.parse(text);
60
+ } catch {
61
+ }
62
+ return { status: res.status, headers: res.headers, json };
63
+ } catch {
64
+ return { status: 0, headers: new Headers(), json: null };
65
+ }
66
+ };
67
+ var formBody = (fields) => ({
68
+ method: "POST",
69
+ headers: { "content-type": "application/x-www-form-urlencoded" },
70
+ body: new URLSearchParams(fields).toString()
71
+ });
72
+ var jsonBody = (value) => ({
73
+ method: "POST",
74
+ headers: { "content-type": "application/json" },
75
+ body: JSON.stringify(value)
76
+ });
77
+ var oauthError = (res) => isRecord(res.json) && typeof res.json.error === "string" ? res.json.error : null;
78
+ var retryAfterMs = (res) => {
79
+ const seconds = Number(res.headers.get("retry-after"));
80
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * SECOND_MS : null;
81
+ };
82
+ var REVOKE_TIMEOUT_MS = 5 * SECOND_MS;
83
+ var revokeToken = async (apiUrl, clientId, token) => {
84
+ const res = await request(
85
+ endpoints(apiUrl).revoke,
86
+ formBody({ token, client_id: clientId }),
87
+ REVOKE_TIMEOUT_MS
88
+ );
89
+ return res.status === 200;
90
+ };
91
+
92
+ // src/files.ts
93
+ import { randomBytes } from "node:crypto";
94
+ import { chmod, mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises";
95
+ import { dirname, join } from "node:path";
96
+ var TRANSIENT_RENAME_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
97
+ var RENAME_ATTEMPTS = 10;
98
+ var MISSING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
99
+ var ensureDir = async (dir) => {
100
+ await mkdir(dir, { recursive: true, mode: 448 });
101
+ if (process.platform !== "win32") await chmod(dir, 448).catch(() => void 0);
102
+ };
103
+ var readJson = async (file, guard) => {
104
+ let text;
105
+ try {
106
+ text = await readFile(file, "utf8");
107
+ } catch (error) {
108
+ if (MISSING_CODES.has(errCode(error) ?? "")) return null;
109
+ throw error;
110
+ }
111
+ try {
112
+ const value = JSON.parse(text);
113
+ return guard(value) ? value : null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ };
118
+ var readJsonLoose = async (file, guard) => readJson(file, guard).catch(() => null);
119
+ var removeStaleTemps = async (dir, now, prefix = "") => {
120
+ const names = await readdir(dir).catch(() => []);
121
+ for (const name of names) {
122
+ if (!name.endsWith(".tmp") || !name.startsWith(prefix)) continue;
123
+ const path = join(dir, name);
124
+ const modified = await stat(path).then(
125
+ (s) => s.mtimeMs,
126
+ () => now
127
+ );
128
+ if (now - modified > HOUR_MS) await rm(path, { force: true });
129
+ }
130
+ };
131
+ var renameWithRetry = async (from, to) => {
132
+ for (let attempt = 1; ; attempt++) {
133
+ try {
134
+ await rename(from, to);
135
+ return;
136
+ } catch (error) {
137
+ const retry = attempt < RENAME_ATTEMPTS && TRANSIENT_RENAME_CODES.has(errCode(error) ?? "");
138
+ if (!retry) {
139
+ await rm(from, { force: true });
140
+ throw error;
141
+ }
142
+ await sleep(20 * attempt);
143
+ }
144
+ }
145
+ };
146
+ var writeFileAtomic = async (file, data) => {
147
+ await ensureDir(dirname(file));
148
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
149
+ const handle = await open(temp, "w", 384);
150
+ try {
151
+ await handle.writeFile(data);
152
+ await handle.sync();
153
+ } finally {
154
+ await handle.close();
155
+ }
156
+ await renameWithRetry(temp, file);
157
+ };
158
+ var writeJsonAtomic = (file, value) => writeFileAtomic(file, JSON.stringify(value));
159
+ var removeQuiet = (path) => rm(path, { recursive: true, force: true });
160
+
161
+ // src/lock.ts
162
+ import { randomBytes as randomBytes2 } from "node:crypto";
163
+ import { open as open2, rm as rm2, stat as stat2 } from "node:fs/promises";
164
+ import { dirname as dirname2 } from "node:path";
165
+ var isLockInfo = (value) => isRecord(value) && isFiniteNumber(value.pid) && typeof value.token === "string" && isFiniteNumber(value.at);
166
+ var BUSY_CODES = /* @__PURE__ */ new Set(["EEXIST", "EPERM", "EACCES", "EBUSY"]);
167
+ var POLL_MS = 50;
168
+ var isAlive = (pid) => {
169
+ try {
170
+ process.kill(pid, 0);
171
+ return true;
172
+ } catch (error) {
173
+ return errCode(error) !== "ESRCH";
174
+ }
175
+ };
176
+ var tryCreate = async (file, token) => {
177
+ await ensureDir(dirname2(file));
178
+ let handle;
179
+ try {
180
+ handle = await open2(file, "wx", 384);
181
+ } catch (error) {
182
+ if (BUSY_CODES.has(errCode(error) ?? "")) return false;
183
+ throw error;
184
+ }
185
+ try {
186
+ const info = { pid: process.pid, token, at: Date.now() };
187
+ await handle.writeFile(JSON.stringify(info));
188
+ } finally {
189
+ await handle.close();
190
+ }
191
+ return true;
192
+ };
193
+ var steal = async (file, observedToken) => {
194
+ const stealFile = `${file}.steal`;
195
+ let handle;
196
+ try {
197
+ handle = await open2(stealFile, "wx", 384);
198
+ } catch {
199
+ const age = await stat2(stealFile).then(
200
+ (s) => Date.now() - s.mtimeMs,
201
+ () => 0
202
+ );
203
+ if (age > HOUR_MS) await rm2(stealFile, { force: true });
204
+ return false;
205
+ }
206
+ await handle.close();
207
+ try {
208
+ const current = await readJsonLoose(file, isLockInfo);
209
+ if ((current?.token ?? null) === observedToken) await rm2(file, { force: true });
210
+ } finally {
211
+ await rm2(stealFile, { force: true });
212
+ }
213
+ return true;
214
+ };
215
+ var removeIfStale = async (file, staleMs) => {
216
+ const info = await readJsonLoose(file, isLockInfo);
217
+ const modified = await stat2(file).then(
218
+ (s) => s.mtimeMs,
219
+ () => null
220
+ );
221
+ if (modified === null) return true;
222
+ const stale = info !== null && !isAlive(info.pid) || Date.now() - (info?.at ?? modified) > staleMs;
223
+ return stale ? steal(file, info?.token ?? null) : false;
224
+ };
225
+ var release = async (file, token) => {
226
+ const info = await readJsonLoose(file, isLockInfo);
227
+ if (info?.token === token) await rm2(file, { force: true });
228
+ };
229
+ var withLock = async (file, options, work) => {
230
+ const token = randomBytes2(8).toString("hex");
231
+ const deadline = Date.now() + options.waitMs;
232
+ let quickRetries = 3;
233
+ while (!await tryCreate(file, token)) {
234
+ if (await removeIfStale(file, options.staleMs) && quickRetries-- > 0) continue;
235
+ if (Date.now() >= deadline) return "busy";
236
+ await sleep(POLL_MS + Math.random() * POLL_MS);
237
+ }
238
+ try {
239
+ return await work();
240
+ } finally {
241
+ await release(file, token);
242
+ }
243
+ };
244
+
245
+ // src/paths.ts
246
+ import { homedir as homedir2 } from "node:os";
247
+ import { join as join2 } from "node:path";
248
+ var DEFAULT_API_URL = "https://api.app.tolmete.com";
249
+ var defaultHome = () => join2(homedir2(), ".tolmete");
250
+ var paths = {
251
+ credentials: (home) => join2(home, "credentials.json"),
252
+ clients: (home) => join2(home, "clients.json"),
253
+ autoLogin: (home) => join2(home, "auto-login"),
254
+ autoLoginHint: (home) => join2(home, "auto-login-hint"),
255
+ /** Set once the Codex CLI hook has offered the sign-in; a sign-out sets it too. */
256
+ codexHint: (home) => join2(home, "codex-hint"),
257
+ /** The link of a sign-in that is waiting for the browser. */
258
+ pendingLogin: (home) => join2(home, "login-pending"),
259
+ /** Hash of a working directory -> its canonical remotes, for folders that are gone later. */
260
+ cwdRemotes: (home) => join2(home, "cwd-remotes.json"),
261
+ notifiedDir: (home) => join2(home, "notified"),
262
+ notified: (home, sessionId) => join2(home, "notified", sha256(sessionId)),
263
+ promptsDir: (home) => join2(home, "prompts"),
264
+ prompt: (home, promptId) => join2(home, "prompts", promptId),
265
+ offsets: (home) => join2(home, "offsets.json"),
266
+ queueRoot: (home) => join2(home, "queue"),
267
+ partitionDir: (home, partition) => join2(home, "queue", partition),
268
+ state: (home, partition) => join2(home, "queue", partition, "state.json"),
269
+ repositories: (home, partition) => join2(home, "queue", partition, "repositories.json"),
270
+ /** Per tool, when its last event was queued. */
271
+ lastRecorded: (home, partition) => join2(home, "queue", partition, "last-recorded.json"),
272
+ /** Codex hook records waiting for the worker. The queue's own file listing ignores a folder. */
273
+ codexSpool: (home, partition) => join2(home, "queue", partition, "codex"),
274
+ /** The same for Cursor. A logout deletes the whole partition, both folders with it. */
275
+ cursorSpool: (home, partition) => join2(home, "queue", partition, "cursor"),
276
+ lock: (home, name) => join2(home, "locks", `${name}.lock`)
277
+ };
278
+
279
+ // src/credentials.ts
280
+ var isCredentials = (value) => isRecord(value) && typeof value.apiUrl === "string" && typeof value.clientId === "string" && typeof value.accessToken === "string" && isFiniteNumber(value.expiresAt) && typeof value.refreshToken === "string" && typeof value.organizationId === "string" && typeof value.userId === "string" && isFiniteNumber(value.loginAt) && (value.status === "active" || value.status === "needs_login");
281
+ var readCredentials = (home) => readJson(paths.credentials(home), isCredentials);
282
+ var writeCredentials = (home, credentials) => writeJsonAtomic(paths.credentials(home), credentials);
283
+ var partitionOf = (c) => sha256(`${c.apiUrl}|${c.organizationId}|${c.userId}`).slice(0, 32);
284
+ var isClients = (value) => isRecord(value) && Object.values(value).every((v) => typeof v === "string");
285
+ var readClients = async (home) => await readJson(paths.clients(home), isClients) ?? {};
286
+ var saveClient = async (home, apiUrl, clientId) => writeJsonAtomic(paths.clients(home), { ...await readClients(home), [apiUrl]: clientId });
287
+ var forgetClient = async (home, apiUrl) => {
288
+ const clients = await readClients(home);
289
+ delete clients[apiUrl];
290
+ await writeJsonAtomic(paths.clients(home), clients);
291
+ };
292
+ var CREDENTIALS_LOCK = { waitMs: 30 * SECOND_MS, staleMs: 10 * MINUTE_MS };
293
+ var withCredentialsLock = (home, work) => withLock(paths.lock(home, "credentials"), CREDENTIALS_LOCK, work);
294
+ var EXPIRY_MARGIN_MS = MINUTE_MS;
295
+ var parseTokens = (res, now) => {
296
+ const body = res.json;
297
+ if (!isRecord(body) || typeof body.access_token !== "string" || typeof body.refresh_token !== "string" || !isFiniteNumber(body.expires_in) || body.expires_in <= 0) {
298
+ return null;
299
+ }
300
+ return {
301
+ accessToken: body.access_token,
302
+ refreshToken: body.refresh_token,
303
+ expiresAt: now + body.expires_in * SECOND_MS
304
+ };
305
+ };
306
+ var refreshLocked = async (home, failedToken, now) => {
307
+ const credentials = await readCredentials(home);
308
+ if (!credentials) return { ok: false, reason: "no_credentials" };
309
+ if (credentials.status !== "active") return { ok: false, reason: "needs_login" };
310
+ const partition = partitionOf(credentials);
311
+ const fresh = credentials.expiresAt - now > EXPIRY_MARGIN_MS;
312
+ if (fresh && credentials.accessToken !== failedToken) {
313
+ return { ok: true, token: credentials.accessToken, partition };
314
+ }
315
+ const res = await request(
316
+ endpoints(credentials.apiUrl).token,
317
+ formBody({
318
+ grant_type: "refresh_token",
319
+ refresh_token: credentials.refreshToken,
320
+ client_id: credentials.clientId,
321
+ resource: endpoints(credentials.apiUrl).resource
322
+ })
323
+ );
324
+ const stillHere = async () => (await readCredentials(home))?.refreshToken === credentials.refreshToken;
325
+ if (res.status === 200) {
326
+ const tokens = parseTokens(res, now);
327
+ if (!tokens) return { ok: false, reason: "unavailable" };
328
+ if (!await stillHere()) return { ok: false, reason: "no_credentials" };
329
+ await writeCredentials(home, { ...credentials, ...tokens });
330
+ return { ok: true, token: tokens.accessToken, partition };
331
+ }
332
+ const error = oauthError(res);
333
+ const grantGone = res.status === 400 && error === "invalid_grant";
334
+ const clientGone = (res.status === 400 || res.status === 401) && error === "invalid_client";
335
+ if (grantGone || clientGone) {
336
+ if (clientGone) await forgetClient(home, credentials.apiUrl);
337
+ if (!await stillHere()) return { ok: false, reason: "no_credentials" };
338
+ await writeCredentials(home, { ...credentials, status: "needs_login" });
339
+ return { ok: false, reason: "needs_login" };
340
+ }
341
+ return { ok: false, reason: "unavailable" };
342
+ };
343
+ var getAccessToken = async (home, options = {}) => {
344
+ const result = await withCredentialsLock(
345
+ home,
346
+ () => refreshLocked(home, options.failedToken, options.now ?? Date.now())
347
+ );
348
+ return result === "busy" ? { ok: false, reason: "unavailable" } : result;
349
+ };
350
+ var withBearer = (input, token) => ({
351
+ ...input,
352
+ headers: { ...input.headers, authorization: `Bearer ${token}` }
353
+ });
354
+ var authedFetch = async (home, url, input = {}, partition) => {
355
+ const first = await getAccessToken(home);
356
+ if (!first.ok) return { kind: "auth", reason: first.reason };
357
+ if (partition !== void 0 && first.partition !== partition) {
358
+ return { kind: "auth", reason: "identity_changed" };
359
+ }
360
+ let res = await request(url, withBearer(input, first.token));
361
+ if (res.status === 401) {
362
+ const second = await getAccessToken(home, { failedToken: first.token });
363
+ if (!second.ok) return { kind: "auth", reason: second.reason };
364
+ if (partition !== void 0 && second.partition !== partition) {
365
+ return { kind: "auth", reason: "identity_changed" };
366
+ }
367
+ res = await request(url, withBearer(input, second.token));
368
+ }
369
+ return { kind: "response", res };
370
+ };
371
+ var removeCredentials = (home) => removeQuiet(paths.credentials(home));
372
+
373
+ // src/account.ts
374
+ import { readdir as readdir3 } from "node:fs/promises";
375
+ import { join as join5 } from "node:path";
376
+
377
+ // src/canonical-remote.ts
378
+ var GITHUB_HOST = "github.com";
379
+ var GITLAB_HOST = "gitlab.com";
380
+ var BITBUCKET_HOST = "bitbucket.org";
381
+ var REMOTE_MAX_LENGTH = 512;
382
+ var PATH_SEGMENTS_MIN = 2;
383
+ var GITLAB_PATH_SEGMENTS_MAX = 20;
384
+ var GIT_HOSTS = /* @__PURE__ */ new Set([GITHUB_HOST, GITLAB_HOST, BITBUCKET_HOST]);
385
+ var HOST_ALIASES = /* @__PURE__ */ new Map([
386
+ ["ssh.github.com", GITHUB_HOST],
387
+ ["altssh.gitlab.com", GITLAB_HOST],
388
+ ["altssh.bitbucket.org", BITBUCKET_HOST]
389
+ ]);
390
+ var URL_REMOTE_PATTERN = /^(?:https?|ssh|git|git\+ssh|ssh\+git):\/\/(?:[^/?#\\]*@)?([^/:@?#[\]\\]+)(?::\d+)?\/([^?#]+)$/i;
391
+ var SCP_REMOTE_PATTERN = /^(?:[^@/:]+@)?([^/:@?#[\]\\]+):(?!\/\/)([^?#]+)$/;
392
+ var PATH_SEGMENT_PATTERN = /^[a-z0-9._-]+$/;
393
+ var UNSAFE_REMOTE_CHARACTERS = /[\s\p{Cc}]/u;
394
+ var splitRemote = (remote) => {
395
+ if (remote.length > REMOTE_MAX_LENGTH || UNSAFE_REMOTE_CHARACTERS.test(remote)) return null;
396
+ const match = URL_REMOTE_PATTERN.exec(remote) ?? SCP_REMOTE_PATTERN.exec(remote);
397
+ const [, host, path] = match ?? [];
398
+ return host && path ? { host, path } : null;
399
+ };
400
+ var canonicalizeGitRemote = (remote) => {
401
+ const parts = splitRemote(remote);
402
+ if (!parts) return null;
403
+ const lowerHost = parts.host.toLowerCase();
404
+ const host = HOST_ALIASES.get(lowerHost) ?? lowerHost;
405
+ if (!GIT_HOSTS.has(host)) return null;
406
+ const segments = parts.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").toLowerCase().split("/");
407
+ const maxSegments = host === GITLAB_HOST ? GITLAB_PATH_SEGMENTS_MAX : PATH_SEGMENTS_MIN;
408
+ const isValid = segments.length >= PATH_SEGMENTS_MIN && segments.length <= maxSegments && segments.every(
409
+ (segment) => PATH_SEGMENT_PATTERN.test(segment) && segment !== "." && segment !== ".."
410
+ );
411
+ return isValid ? `${host}/${segments.join("/")}` : null;
412
+ };
413
+ var remoteHash = (canonical) => sha256(canonical);
414
+ var remoteUrlHash = (remote) => remoteHash(remote.replace(/^https:\/\//, ""));
415
+ var isGitHost = (host) => {
416
+ const lower = host.toLowerCase();
417
+ return GIT_HOSTS.has(HOST_ALIASES.get(lower) ?? lower);
418
+ };
419
+
420
+ // src/event.ts
421
+ var TOOL_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
422
+ var MODEL_PATTERN = /^[\x21-\x7E]{1,128}$/;
423
+ var BRANCH_MAX_LENGTH = 255;
424
+ var BRANCH_PATTERN = /^[^\p{Cc}\p{Cs}\s~^:?*\x5B\\]+$/u;
425
+ var INT4_MAX = 2147483647;
426
+ var cleanCount = (value) => Number.isInteger(value) && value !== null && value >= 0 && value <= INT4_MAX ? value : null;
427
+ var cleanBranch = (branch) => branch !== null && branch !== "HEAD" && branch.length <= BRANCH_MAX_LENGTH && BRANCH_PATTERN.test(branch) ? branch : null;
428
+ var buildEvent = (tool, provider, draft, canonicalRemote) => {
429
+ if (!TOOL_ID_PATTERN.test(draft.sessionId) || !TOOL_ID_PATTERN.test(draft.toolEventId)) {
430
+ return null;
431
+ }
432
+ const time2 = Date.parse(draft.occurredAt);
433
+ if (Number.isNaN(time2)) return null;
434
+ return {
435
+ provider,
436
+ tool,
437
+ model: draft.model !== null && MODEL_PATTERN.test(draft.model) ? draft.model : null,
438
+ inputTokens: cleanCount(draft.inputTokens),
439
+ outputTokens: cleanCount(draft.outputTokens),
440
+ cacheReadTokens: cleanCount(draft.cacheReadTokens),
441
+ cacheWriteTokens: cleanCount(draft.cacheWriteTokens),
442
+ interactions: draft.interactions,
443
+ sessionId: draft.sessionId,
444
+ toolEventId: draft.toolEventId,
445
+ branch: cleanBranch(draft.branch),
446
+ occurredAt: new Date(time2).toISOString(),
447
+ remote: `https://${canonicalRemote}`
448
+ };
449
+ };
450
+ var isNullableCount = (value) => value === null || typeof value === "number";
451
+ var isStoredEvent = (value) => {
452
+ if (!isRecord(value)) return false;
453
+ const e = value;
454
+ return typeof e.toolEventId === "string" && typeof e.occurredAt === "string" && typeof e.remote === "string" && typeof e.sessionId === "string" && typeof e.provider === "string" && typeof e.tool === "string" && (e.interactions === 0 || e.interactions === 1) && isNullableCount(e.inputTokens) && isNullableCount(e.outputTokens) && isNullableCount(e.cacheReadTokens) && isNullableCount(e.cacheWriteTokens);
455
+ };
456
+
457
+ // src/git-branch.ts
458
+ import { readFileSync, statSync } from "node:fs";
459
+ import { dirname as dirname3, join as join3, resolve } from "node:path";
460
+ var HEAD_REF = /^ref: refs\/heads\/(.+)$/;
461
+ var readBranch = (cwd) => {
462
+ let dir = cwd;
463
+ for (let depth = 0; depth < 32; depth++) {
464
+ try {
465
+ const dot = join3(dir, ".git");
466
+ const gitDir = statSync(dot).isDirectory() ? dot : resolve(dir, /^gitdir: (.+)$/m.exec(readFileSync(dot, "utf8"))?.[1]?.trim() ?? "");
467
+ const ref = HEAD_REF.exec(readFileSync(join3(gitDir, "HEAD"), "utf8").trim())?.[1] ?? null;
468
+ return ref === ".invalid" ? null : ref;
469
+ } catch {
470
+ }
471
+ const parent = dirname3(dir);
472
+ if (parent === dir) break;
473
+ dir = parent;
474
+ }
475
+ return null;
476
+ };
477
+
478
+ // src/repositories.ts
479
+ var REFRESH_MS = HOUR_MS;
480
+ var RETRY_MS = 5 * MINUTE_MS;
481
+ var MATCH_MEMORY_MS = 30 * DAY_MS;
482
+ var empty = () => ({ hashes: null, fetchedAt: 0, triedAt: 0, matched: {} });
483
+ var isCache = (value) => isRecord(value) && (value.hashes === null || Array.isArray(value.hashes)) && isFiniteNumber(value.fetchedAt) && isFiniteNumber(value.triedAt) && isRecord(value.matched);
484
+ var readRepositories = async (home, partition) => await readJson(paths.repositories(home, partition), isCache) ?? empty();
485
+ var writeRepositories = (home, partition, cache, now) => {
486
+ const matched = Object.fromEntries(
487
+ Object.entries(cache.matched).filter(([, at]) => now - at < MATCH_MEMORY_MS)
488
+ );
489
+ return writeJsonAtomic(paths.repositories(home, partition), { ...cache, matched });
490
+ };
491
+ var saveRepositories = async (home, partition, mine, now) => {
492
+ const latest2 = await readRepositories(home, partition);
493
+ const base = mine.hashes !== null && mine.fetchedAt >= latest2.fetchedAt ? mine : latest2;
494
+ const matched = { ...latest2.matched };
495
+ for (const [hash, at] of Object.entries(mine.matched)) {
496
+ matched[hash] = Math.max(matched[hash] ?? 0, at);
497
+ }
498
+ const next = {
499
+ ...base,
500
+ triedAt: Math.max(mine.triedAt, latest2.triedAt),
501
+ matched: Object.fromEntries(
502
+ Object.entries(matched).filter(([, at]) => now - at < MATCH_MEMORY_MS)
503
+ )
504
+ };
505
+ if (JSON.stringify(next) !== JSON.stringify(latest2)) {
506
+ await writeJsonAtomic(paths.repositories(home, partition), next);
507
+ }
508
+ };
509
+ var noteMatch = (cache, hash, now) => {
510
+ if (now - (cache.matched[hash] ?? 0) <= DAY_MS) return false;
511
+ cache.matched[hash] = now;
512
+ return true;
513
+ };
514
+ var parseHashes = (json) => isRecord(json) && Array.isArray(json.hashes) && json.hashes.every((h) => typeof h === "string") ? json.hashes : null;
515
+ var refreshRepositories = async (home, credentials, now) => {
516
+ const partition = partitionOf(credentials);
517
+ const cache = await readRepositories(home, partition);
518
+ const stale = cache.hashes === null || cache.fetchedAt > now || now - cache.fetchedAt >= REFRESH_MS;
519
+ const due = stale ? cache.triedAt > now || now - cache.triedAt >= RETRY_MS : false;
520
+ if (!due) return cache;
521
+ const result = await authedFetch(home, endpoints(credentials.apiUrl).repositories, {}, partition);
522
+ const hashes = result.kind === "response" && result.res.status === 200 ? parseHashes(result.res.json) : null;
523
+ return hashes ? { ...cache, hashes, fetchedAt: now, triedAt: now } : { ...cache, triedAt: now };
524
+ };
525
+
526
+ // src/convert.ts
527
+ var COLLECT_LOCK = { waitMs: 10 * SECOND_MS, staleMs: 2 * MINUTE_MS };
528
+ var MEMORY_MS = 30 * DAY_MS;
529
+ var isCwdMemory = (value) => isRecord(value) && Object.values(value).every(
530
+ (v) => isRecord(v) && isFiniteNumber(v.seenAt) && Array.isArray(v.remotes) && v.remotes.every((r) => typeof r === "string")
531
+ );
532
+ var loadCwdMemory = async (home, now) => {
533
+ const remembered = await readJson(paths.cwdRemotes(home), isCwdMemory) ?? {};
534
+ let changed = false;
535
+ const memory = {
536
+ get: (cwd) => remembered[sha256(cwd)]?.remotes,
537
+ set: (cwd, remotes) => {
538
+ const key = sha256(cwd);
539
+ const before = remembered[key];
540
+ if (before && now - before.seenAt < DAY_MS && before.remotes.join() === remotes.join())
541
+ return;
542
+ remembered[key] = { remotes, seenAt: now };
543
+ changed = true;
544
+ }
545
+ };
546
+ const save2 = async () => {
547
+ if (!changed) return;
548
+ const fresh = Object.entries(remembered).filter(([, v]) => now - v.seenAt < MEMORY_MS);
549
+ await writeJsonAtomic(paths.cwdRemotes(home), Object.fromEntries(fresh));
550
+ };
551
+ return { memory, save: save2 };
552
+ };
553
+ var chooseRemote = (remotes, listed, cache, now) => {
554
+ if (listed === null) {
555
+ const first = remotes[0];
556
+ return first ? { canonical: first, matchedNow: false } : null;
557
+ }
558
+ const connected = remotes.find((r) => listed.has(remoteHash(r)));
559
+ if (connected) return { canonical: connected, matchedNow: true };
560
+ const remembered = remotes.find(
561
+ (r) => now - (cache.matched[remoteHash(r)] ?? 0) < MATCH_MEMORY_MS
562
+ );
563
+ return remembered ? { canonical: remembered, matchedNow: false } : null;
564
+ };
565
+ var MAX_TOUCHED_DIRS = 20;
566
+ var repositoryOfTouched = async (dirs, resolve2, listed, cache, now) => {
567
+ if (dirs.length === 0 || dirs.length > MAX_TOUCHED_DIRS) return null;
568
+ let found = null;
569
+ for (const dir of dirs) {
570
+ const remotes = await resolve2(dir);
571
+ if (remotes.length === 0) continue;
572
+ const chosen = chooseRemote(remotes, listed, cache, now);
573
+ if (!chosen || found && found.canonical !== chosen.canonical) return null;
574
+ found ??= { canonical: chosen.canonical, dir };
575
+ }
576
+ return found;
577
+ };
578
+ var toEvents = async (tool, drafts, resolve2, cache, now) => {
579
+ const listed = cache.hashes === null ? null : new Set(cache.hashes);
580
+ const results = [];
581
+ for (const { draft, provider } of drafts) {
582
+ let remotes;
583
+ let touched = null;
584
+ try {
585
+ remotes = await resolve2(draft.cwd);
586
+ if (remotes.length === 0 && draft.touchedDirs) {
587
+ touched = await repositoryOfTouched(draft.touchedDirs, resolve2, listed, cache, now);
588
+ }
589
+ } catch {
590
+ results.push({ event: null, connected: false, unresolved: true });
591
+ continue;
592
+ }
593
+ if (touched) {
594
+ const moved = { ...draft, branch: readBranch(touched.dir) };
595
+ const matchedNow = listed?.has(remoteHash(touched.canonical)) ?? false;
596
+ if (matchedNow) noteMatch(cache, remoteHash(touched.canonical), now);
597
+ results.push({
598
+ event: buildEvent(tool, provider, moved, touched.canonical),
599
+ connected: matchedNow,
600
+ unresolved: false
601
+ });
602
+ continue;
603
+ }
604
+ const chosen = chooseRemote(remotes, listed, cache, now);
605
+ if (chosen?.matchedNow) noteMatch(cache, remoteHash(chosen.canonical), now);
606
+ const named = chosen && draft.branch === "HEAD" ? { ...draft, branch: readBranch(draft.cwd) } : draft;
607
+ results.push({
608
+ event: chosen ? buildEvent(tool, provider, named, chosen.canonical) : null,
609
+ connected: chosen?.matchedNow ?? false,
610
+ unresolved: false
611
+ });
612
+ }
613
+ return results;
614
+ };
615
+ var withPrefetched = async (deps, collect2) => {
616
+ const credentials = await readCredentials(deps.home);
617
+ if (credentials?.status !== "active") return;
618
+ const prefetched = {
619
+ partition: partitionOf(credentials),
620
+ cache: await refreshRepositories(deps.home, credentials, (deps.now ?? Date.now)())
621
+ };
622
+ await withLock(paths.lock(deps.home, "collect"), COLLECT_LOCK, () => collect2(prefetched));
623
+ };
624
+ var isLastRecorded = (value) => isRecord(value) && Object.values(value).every(isFiniteNumber);
625
+ var readLastRecorded = async (home, partition) => await readJson(paths.lastRecorded(home, partition), isLastRecorded) ?? {};
626
+ var noteRecorded = async (home, partition, tool, events) => {
627
+ const times = events.map((e) => Date.parse(e.occurredAt)).filter((t) => !Number.isNaN(t));
628
+ if (times.length === 0) return;
629
+ const known = await readLastRecorded(home, partition);
630
+ const latest2 = Math.max(known[tool] ?? 0, ...times);
631
+ if (latest2 !== known[tool]) {
632
+ await writeJsonAtomic(paths.lastRecorded(home, partition), { ...known, [tool]: latest2 });
633
+ }
634
+ };
635
+
636
+ // src/queue.ts
637
+ import { randomBytes as randomBytes3 } from "node:crypto";
638
+ import { readdir as readdir2, readFile as readFile2, rm as rm3, stat as stat3 } from "node:fs/promises";
639
+ import { join as join4 } from "node:path";
640
+ var BATCH_MAX_EVENTS = 500;
641
+ var BATCH_MAX_BYTES = 9e5;
642
+ var FILE_MAX_BYTES = 512 * 1024;
643
+ var QUEUE_MAX_BYTES = 20 * 1024 * 1024;
644
+ var MAX_AGE_MS = 30 * DAY_MS;
645
+ var FILE_PATTERN = /^(\d{13})-(\d{1,16})-[0-9a-f]+\.json$/;
646
+ var EMPTY_STATE = {
647
+ failures: 0,
648
+ nextAttemptAt: 0,
649
+ lastSuccessAt: null,
650
+ lastError: null
651
+ };
652
+ var isState = (value) => isRecord(value) && isFiniteNumber(value.failures) && isFiniteNumber(value.nextAttemptAt) && (value.lastSuccessAt === null || isFiniteNumber(value.lastSuccessAt)) && (value.lastError === null || typeof value.lastError === "string");
653
+ var readState = async (home, partition) => await readJson(paths.state(home, partition), isState) ?? EMPTY_STATE;
654
+ var updateState = async (home, partition, patch) => {
655
+ const next = { ...await readState(home, partition), ...patch };
656
+ await writeJsonAtomic(paths.state(home, partition), next);
657
+ return next;
658
+ };
659
+ var listFiles = async (home, partition) => {
660
+ let names;
661
+ try {
662
+ names = await readdir2(paths.partitionDir(home, partition));
663
+ } catch {
664
+ return [];
665
+ }
666
+ const files = [];
667
+ for (const name of names) {
668
+ const match = FILE_PATTERN.exec(name);
669
+ if (match) files.push({ name, notBefore: Number(match[1]), seenAt: Number(match[2]) });
670
+ }
671
+ return files.sort((a, b) => a.name.localeCompare(b.name));
672
+ };
673
+ var readEvents = async (path) => {
674
+ let text;
675
+ try {
676
+ text = await readFile2(path, "utf8");
677
+ } catch {
678
+ return null;
679
+ }
680
+ try {
681
+ const value = JSON.parse(text);
682
+ return Array.isArray(value) ? value.filter(isStoredEvent) : [];
683
+ } catch {
684
+ return [];
685
+ }
686
+ };
687
+ var fileName = (notBefore, now) => `${String(notBefore).padStart(13, "0")}-${now}-${randomBytes3(4).toString("hex")}.json`;
688
+ var enqueue = async (home, partition, events, now, notBefore = 0) => {
689
+ let chunk = [];
690
+ let bytes = 2;
691
+ const flush = async () => {
692
+ if (chunk.length === 0) return;
693
+ const path = join4(paths.partitionDir(home, partition), fileName(notBefore, now));
694
+ await writeFileAtomic(path, `[${chunk.join(",")}]`);
695
+ chunk = [];
696
+ bytes = 2;
697
+ };
698
+ for (const event of events) {
699
+ const json = JSON.stringify(event);
700
+ const size = Buffer.byteLength(json) + 1;
701
+ if (chunk.length >= BATCH_MAX_EVENTS || bytes + size > FILE_MAX_BYTES) await flush();
702
+ chunk.push(json);
703
+ bytes += size;
704
+ }
705
+ await flush();
706
+ };
707
+ var takeBatch = async (home, partition, now) => {
708
+ const events = [];
709
+ const files = [];
710
+ const ids = /* @__PURE__ */ new Set();
711
+ let bytes = 0;
712
+ for (const file of await listFiles(home, partition)) {
713
+ if (file.notBefore > now) continue;
714
+ const path = join4(paths.partitionDir(home, partition), file.name);
715
+ const stored = await readEvents(path);
716
+ if (stored === null) continue;
717
+ const fileEvents = stored.filter((e) => !ids.has(e.toolEventId));
718
+ const fileBytes = fileEvents.reduce((sum, e) => sum + JSON.stringify(e).length + 1, 0);
719
+ if (files.length > 0 && (events.length + fileEvents.length > BATCH_MAX_EVENTS || bytes + fileBytes > BATCH_MAX_BYTES)) {
720
+ break;
721
+ }
722
+ for (const e of fileEvents) ids.add(e.toolEventId);
723
+ events.push(...fileEvents);
724
+ bytes += fileBytes;
725
+ files.push(path);
726
+ }
727
+ return files.length > 0 ? { events, files } : null;
728
+ };
729
+ var removeFiles = async (files) => {
730
+ await Promise.all(files.map((file) => rm3(file, { force: true })));
731
+ };
732
+ var enforceLimit = async (home, partition) => {
733
+ const files = await listFiles(home, partition);
734
+ const sized = await Promise.all(
735
+ files.map(async (file) => {
736
+ const path = join4(paths.partitionDir(home, partition), file.name);
737
+ return {
738
+ path,
739
+ seenAt: file.seenAt,
740
+ size: await stat3(path).then(
741
+ (s) => s.size,
742
+ () => 0
743
+ )
744
+ };
745
+ })
746
+ );
747
+ let total = sized.reduce((sum, f) => sum + f.size, 0);
748
+ let dropped = 0;
749
+ for (const file of sized.sort((a, b) => a.seenAt - b.seenAt)) {
750
+ if (total <= QUEUE_MAX_BYTES) break;
751
+ await rm3(file.path, { force: true });
752
+ total -= file.size;
753
+ dropped++;
754
+ }
755
+ return dropped;
756
+ };
757
+ var queueSize = async (home, partition) => {
758
+ let count2 = 0;
759
+ for (const file of await listFiles(home, partition)) {
760
+ count2 += (await readEvents(join4(paths.partitionDir(home, partition), file.name)))?.length ?? 0;
761
+ }
762
+ return count2;
763
+ };
764
+ var pruneOld = async (home, now) => {
765
+ let partitions;
766
+ try {
767
+ partitions = await readdir2(paths.queueRoot(home));
768
+ } catch {
769
+ return;
770
+ }
771
+ for (const partition of partitions) {
772
+ const dir = paths.partitionDir(home, partition);
773
+ await removeStaleTemps(dir, now);
774
+ for (const file of await listFiles(home, partition)) {
775
+ if (now - file.seenAt > MAX_AGE_MS) await rm3(join4(dir, file.name), { force: true });
776
+ }
777
+ for (const spool of [paths.codexSpool(home, partition), paths.cursorSpool(home, partition)]) {
778
+ await removeStaleTemps(spool, now);
779
+ for (const name of await readdir2(spool).catch(() => [])) {
780
+ const path = join4(spool, name);
781
+ const modified = await stat3(path).then(
782
+ (s) => s.mtimeMs,
783
+ () => now
784
+ );
785
+ if (name.endsWith(".json") && now - modified > MAX_AGE_MS) await rm3(path, { force: true });
786
+ }
787
+ }
788
+ if ((await listFiles(home, partition)).length > 0) continue;
789
+ const names = await readdir2(dir).catch(() => []);
790
+ const times = await Promise.all(
791
+ names.map(
792
+ (name) => stat3(join4(dir, name)).then(
793
+ (s) => s.mtimeMs,
794
+ () => now
795
+ )
796
+ )
797
+ );
798
+ if (times.every((time2) => now - time2 > MAX_AGE_MS)) await removeQuiet(dir);
799
+ }
800
+ };
801
+
802
+ // src/account.ts
803
+ var time = (ms) => ms ? new Date(ms).toISOString() : "never";
804
+ var TOOLS = [
805
+ ["ClaudeCode", "Claude Code"],
806
+ ["CodexCli", "Codex CLI"],
807
+ ["Cursor", "Cursor"]
808
+ ];
809
+ var statusLines = async (home, signIn2, notes = []) => {
810
+ const credentials = await readCredentials(home);
811
+ if (!credentials) return [`Not signed in. ${signIn2 ?? "Run /tolmete:login in Claude Code."}`];
812
+ const partition = partitionOf(credentials);
813
+ const state = await readState(home, partition);
814
+ const last = await readLastRecorded(home, partition);
815
+ return [
816
+ credentials.status === "active" ? "Signed in: yes" : `Signed in: no, the sign-in expired. ${signIn2 ?? "Run /tolmete:login."}`,
817
+ `API: ${credentials.apiUrl}`,
818
+ `Organization: ${credentials.organizationId}`,
819
+ `Queued events: ${await queueSize(home, partition)}`,
820
+ `Last successful send: ${state.lastSuccessAt ? new Date(state.lastSuccessAt).toISOString() : "never"}`,
821
+ `Last error: ${state.lastError ?? "none"}`,
822
+ ...TOOLS.map(([tool, name]) => `Last event, ${name}: ${time(last[tool])}`),
823
+ ...notes
824
+ ];
825
+ };
826
+ var deleteLocalData = async (home) => {
827
+ await Promise.all(
828
+ [
829
+ paths.queueRoot(home),
830
+ paths.promptsDir(home),
831
+ paths.offsets(home),
832
+ paths.notifiedDir(home),
833
+ paths.clients(home),
834
+ paths.cwdRemotes(home),
835
+ paths.pendingLogin(home)
836
+ ].map(removeQuiet)
837
+ );
838
+ const names = await readdir3(home).catch(() => []);
839
+ await Promise.all(
840
+ names.filter((name) => name.startsWith("credentials.json.") && name.endsWith(".tmp")).map((name) => removeQuiet(join5(home, name)))
841
+ );
842
+ };
843
+ var logout = async (home) => {
844
+ const takeCredentials = async () => {
845
+ const credentials2 = await readCredentials(home);
846
+ await removeCredentials(home);
847
+ return credentials2;
848
+ };
849
+ const locked = await withCredentialsLock(home, takeCredentials);
850
+ const credentials = locked === "busy" ? await takeCredentials() : locked;
851
+ if (credentials) {
852
+ await writeFileAtomic(paths.autoLogin(home), "");
853
+ await writeFileAtomic(paths.codexHint(home), "");
854
+ }
855
+ const revoked = credentials ? await revokeToken(credentials.apiUrl, credentials.clientId, credentials.refreshToken) : false;
856
+ const wipe = async () => {
857
+ const collecting = await withLock(
858
+ paths.lock(home, "collect"),
859
+ { waitMs: 10 * SECOND_MS, staleMs: 2 * MINUTE_MS },
860
+ () => deleteLocalData(home)
861
+ );
862
+ if (collecting === "busy") await deleteLocalData(home);
863
+ };
864
+ const sending = await withLock(
865
+ paths.lock(home, "send"),
866
+ { waitMs: 20 * SECOND_MS, staleMs: 10 * MINUTE_MS },
867
+ wipe
868
+ );
869
+ if (sending === "busy") await wipe();
870
+ if (!credentials) return "Not signed in. Local data removed.";
871
+ return revoked ? "Signed out. The connection is revoked and the local data is deleted." : "Signed out here and the local data is deleted, but Tolmete could not be reached to revoke the connection. Remove it in Tolmete under Settings, Connectors.";
872
+ };
873
+
874
+ // src/login.ts
875
+ import { spawn } from "node:child_process";
876
+ import { createHash as createHash2, randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
877
+ import { createServer } from "node:http";
878
+ import { join as join6 } from "node:path";
879
+ import { readFile as readFile3 } from "node:fs/promises";
880
+ var LOGIN_LOCK = { waitMs: 0, staleMs: 6 * MINUTE_MS };
881
+ var CALLBACK_TIMEOUT_MS = 5 * MINUTE_MS;
882
+ var SCOPE = "ai_usage offline_access";
883
+ var CLIENT_NAME = "Tolmete";
884
+ var REPOSITORIES_TRIES = 3;
885
+ var FIRST_LINE_TIMEOUT_MS = 10 * SECOND_MS;
886
+ var fail = (message) => ({ ok: false, message });
887
+ var base64Url = (bytes) => bytes.toString("base64url");
888
+ var safeEqual = (a, b) => {
889
+ const left = Buffer.from(a);
890
+ const right = Buffer.from(b);
891
+ return left.length === right.length && timingSafeEqual(left, right);
892
+ };
893
+ var openBrowser = (url) => {
894
+ const [file, args] = process.platform === "win32" ? [
895
+ join6(process.env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"),
896
+ ["url.dll,FileProtocolHandler", url]
897
+ ] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
898
+ try {
899
+ spawn(file, args, { stdio: "ignore", detached: true, windowsHide: true, ...neutralSpawn() }).on("error", () => void 0).unref();
900
+ } catch {
901
+ }
902
+ };
903
+ var register = async (apiUrl) => {
904
+ const res = await request(
905
+ endpoints(apiUrl).register,
906
+ jsonBody({
907
+ client_name: CLIENT_NAME,
908
+ token_endpoint_auth_method: "none",
909
+ redirect_uris: ["http://127.0.0.1/callback"],
910
+ grant_types: ["authorization_code", "refresh_token"],
911
+ response_types: ["code"],
912
+ scope: SCOPE
913
+ })
914
+ );
915
+ return isRecord(res.json) && typeof res.json.client_id === "string" ? res.json.client_id : null;
916
+ };
917
+ var sendPage = (res, status, text) => {
918
+ res.writeHead(status, {
919
+ "content-type": "text/html; charset=utf-8",
920
+ "cache-control": "no-store",
921
+ connection: "close"
922
+ });
923
+ res.end(`<!doctype html><meta charset="utf-8"><title>Tolmete</title><p>${text}</p>`);
924
+ };
925
+ var listenForCallback = async (state, apiUrl, timeoutMs) => {
926
+ let settle = () => void 0;
927
+ const result = new Promise((resolve2) => {
928
+ settle = resolve2;
929
+ });
930
+ let used = false;
931
+ const server = createServer((req, res) => {
932
+ const url = URL.canParse(req.url ?? "/", "http://127.0.0.1") ? new URL(req.url ?? "/", "http://127.0.0.1") : null;
933
+ if (req.method !== "GET" || url?.pathname !== "/callback") {
934
+ res.writeHead(404).end();
935
+ return;
936
+ }
937
+ if (used || !safeEqual(url.searchParams.get("state") ?? "", state)) {
938
+ sendPage(res, 400, "This sign-in link is not valid. Go back to the terminal.");
939
+ return;
940
+ }
941
+ used = true;
942
+ const issuer = url.searchParams.get("iss");
943
+ const code = url.searchParams.get("code");
944
+ if (issuer !== null && issuer.replace(/\/+$/, "") !== apiUrl) {
945
+ sendPage(res, 400, "The sign-in came from an unexpected server.");
946
+ settle({ ok: false, message: "The sign-in answer came from an unexpected server." });
947
+ } else if (url.searchParams.has("error") || !code) {
948
+ sendPage(res, 400, "Sign-in was not completed. You can close this tab.");
949
+ settle({ ok: false, message: "Sign-in was cancelled or refused." });
950
+ } else {
951
+ sendPage(res, 200, "Signed in. You can close this tab.");
952
+ settle({ ok: true, code });
953
+ }
954
+ });
955
+ await new Promise((resolve2, reject) => {
956
+ server.once("error", reject);
957
+ server.listen(0, "127.0.0.1", resolve2);
958
+ });
959
+ const timer = setTimeout(
960
+ () => settle({ ok: false, message: "Timed out waiting for the sign-in." }),
961
+ timeoutMs
962
+ );
963
+ return {
964
+ port: server.address().port,
965
+ result,
966
+ close: () => {
967
+ clearTimeout(timer);
968
+ server.close();
969
+ server.closeIdleConnections();
970
+ }
971
+ };
972
+ };
973
+ var exchangeCode = async (home, apiUrl, form, now) => {
974
+ const res = await request(endpoints(apiUrl).token, formBody(form));
975
+ const tokens = res.status === 200 ? parseTokens(res, now) : null;
976
+ if (tokens) return tokens;
977
+ const error = oauthError(res);
978
+ if (error === "invalid_client") await forgetClient(home, apiUrl);
979
+ return `Tolmete refused the sign-in${error ? ` (${error})` : ""}.`;
980
+ };
981
+ var fetchIdentity = async (apiUrl, accessToken) => {
982
+ for (let attempt = 1; attempt <= REPOSITORIES_TRIES; attempt++) {
983
+ const res = await request(endpoints(apiUrl).repositories, {
984
+ headers: { authorization: `Bearer ${accessToken}` }
985
+ });
986
+ const hashes = res.status === 200 ? parseHashes(res.json) : null;
987
+ const organizationId = res.headers.get(ORGANIZATION_HEADER);
988
+ const userId = res.headers.get(USER_HEADER);
989
+ if (hashes && organizationId && userId) return { hashes, organizationId, userId };
990
+ if (attempt < REPOSITORIES_TRIES) await sleep(SECOND_MS);
991
+ }
992
+ return null;
993
+ };
994
+ var signIn = async (options, now) => {
995
+ const { home, apiUrl, print } = options;
996
+ const endpoint = endpoints(apiUrl);
997
+ const clientId = (await readClients(home))[apiUrl] ?? await register(apiUrl);
998
+ if (!clientId) return fail("Could not register with Tolmete. Check the connection and retry.");
999
+ const verifier = base64Url(randomBytes4(32));
1000
+ const challenge = base64Url(createHash2("sha256").update(verifier).digest());
1001
+ const state = base64Url(randomBytes4(32));
1002
+ const listener = await listenForCallback(state, apiUrl, options.timeoutMs ?? CALLBACK_TIMEOUT_MS);
1003
+ try {
1004
+ const redirectUri = `http://127.0.0.1:${listener.port}/callback`;
1005
+ const url = `${endpoint.authorize}?${new URLSearchParams({
1006
+ response_type: "code",
1007
+ client_id: clientId,
1008
+ redirect_uri: redirectUri,
1009
+ state,
1010
+ code_challenge: challenge,
1011
+ code_challenge_method: "S256",
1012
+ scope: SCOPE,
1013
+ resource: endpoint.resource
1014
+ }).toString()}`;
1015
+ await writeFileAtomic(paths.pendingLogin(home), url);
1016
+ print(`Sign in to Tolmete: ${url}`);
1017
+ options.open(url);
1018
+ const callback = await listener.result;
1019
+ if (!callback.ok) return fail(callback.message);
1020
+ const tokens = await exchangeCode(
1021
+ home,
1022
+ apiUrl,
1023
+ {
1024
+ grant_type: "authorization_code",
1025
+ code: callback.code,
1026
+ redirect_uri: redirectUri,
1027
+ client_id: clientId,
1028
+ code_verifier: verifier,
1029
+ resource: endpoint.resource
1030
+ },
1031
+ now()
1032
+ );
1033
+ if (typeof tokens === "string") return fail(tokens);
1034
+ const identity = await fetchIdentity(apiUrl, tokens.accessToken);
1035
+ if (!identity) {
1036
+ await revokeToken(apiUrl, clientId, tokens.refreshToken);
1037
+ return fail("Signed in, but Tolmete could not be asked for the repositories. Try again.");
1038
+ }
1039
+ const credentials = {
1040
+ apiUrl,
1041
+ clientId,
1042
+ ...tokens,
1043
+ organizationId: identity.organizationId,
1044
+ userId: identity.userId,
1045
+ loginAt: now(),
1046
+ status: "active"
1047
+ };
1048
+ const previous = await save(home, credentials, identity.hashes, now());
1049
+ if (previous === "busy") {
1050
+ await revokeToken(apiUrl, clientId, tokens.refreshToken);
1051
+ return fail("Another process holds the credentials. Try again.");
1052
+ }
1053
+ if (previous) await revokeToken(previous.apiUrl, previous.clientId, previous.refreshToken);
1054
+ return { ok: true, organizationId: credentials.organizationId };
1055
+ } finally {
1056
+ listener.close();
1057
+ await removeQuiet(paths.pendingLogin(home));
1058
+ }
1059
+ };
1060
+ var save = (home, next, hashes, now) => withCredentialsLock(home, async () => {
1061
+ const previous = await readCredentials(home);
1062
+ const sameIdentity = previous?.status === "active" && partitionOf(previous) === partitionOf(next);
1063
+ const credentials = sameIdentity ? { ...next, loginAt: Math.min(previous.loginAt, now) } : next;
1064
+ await writeCredentials(home, credentials);
1065
+ await saveClient(home, next.apiUrl, next.clientId);
1066
+ const partition = partitionOf(next);
1067
+ const known = await readRepositories(home, partition);
1068
+ await writeRepositories(
1069
+ home,
1070
+ partition,
1071
+ { hashes, fetchedAt: now, triedAt: now, matched: known.matched },
1072
+ now
1073
+ );
1074
+ await removeQuiet(paths.notifiedDir(home));
1075
+ return previous;
1076
+ });
1077
+ var login = async (options) => {
1078
+ const now = options.now ?? Date.now;
1079
+ const result = await withLock(
1080
+ paths.lock(options.home, "login"),
1081
+ LOGIN_LOCK,
1082
+ () => signIn(options, now)
1083
+ );
1084
+ if (result !== "busy") return result;
1085
+ const pending = await readFile3(paths.pendingLogin(options.home), "utf8").catch(() => "");
1086
+ if (URL.canParse(pending)) {
1087
+ options.print(`Sign in to Tolmete: ${pending}`);
1088
+ options.open(pending);
1089
+ }
1090
+ return fail("A sign-in is already in progress. Finish it in the browser, or wait and retry.");
1091
+ };
1092
+ var loginDetached = (print, apiUrl) => new Promise((resolve2) => {
1093
+ const args = [process.argv[1] ?? "", "login", ...apiUrl ? ["--api-url", apiUrl] : []];
1094
+ const child = spawn(process.execPath, args, {
1095
+ detached: true,
1096
+ stdio: ["ignore", "pipe", "ignore"],
1097
+ windowsHide: true,
1098
+ ...neutralSpawn()
1099
+ });
1100
+ let seen = "";
1101
+ let done = false;
1102
+ const finish = (text) => {
1103
+ if (done) return;
1104
+ done = true;
1105
+ clearTimeout(timer);
1106
+ child.stdout.destroy();
1107
+ child.unref();
1108
+ print(text);
1109
+ resolve2();
1110
+ };
1111
+ const timer = setTimeout(
1112
+ () => finish("Could not start the sign-in. Run /tolmete:login again."),
1113
+ FIRST_LINE_TIMEOUT_MS
1114
+ );
1115
+ child.on("error", () => finish("Could not start the sign-in."));
1116
+ child.stdout.on("data", (chunk) => {
1117
+ seen += chunk.toString("utf8");
1118
+ const end = seen.indexOf("\n");
1119
+ if (end !== -1) {
1120
+ finish(
1121
+ `${seen.slice(0, end).trim()}
1122
+ Open the link above if the browser did not open. Then run /tolmete:status.`
1123
+ );
1124
+ }
1125
+ });
1126
+ child.on("close", () => finish(seen.trim() || "The sign-in could not start."));
1127
+ });
1128
+
1129
+ // src/output.ts
1130
+ var out = (text) => {
1131
+ try {
1132
+ process.stdout.write(`${text}
1133
+ `);
1134
+ } catch {
1135
+ }
1136
+ };
1137
+ var ignoreBrokenStdout = () => {
1138
+ process.stdout.on("error", () => void 0);
1139
+ };
1140
+
1141
+ // src/cli.ts
1142
+ var terminalCommand = (name) => {
1143
+ const runtime = dirname4(fileURLToPath(import.meta.url));
1144
+ return process.platform === "win32" ? `powershell -NoProfile -ExecutionPolicy Bypass -File "${join7(runtime, "tolmete.ps1")}" ${name}` : `sh "${join7(runtime, "tolmete.sh")}" ${name}`;
1145
+ };
1146
+ var STDIN_LIMIT_BYTES = 1024 * 1024;
1147
+ var STDIN_TIMEOUT_MS = SECOND_MS;
1148
+ var WORKER_DEADLINE_MS = 5 * MINUTE_MS;
1149
+ var USAGE = [
1150
+ "tolmete login [--detach] [--api-url <url>] sign in to Tolmete (another API only for development)",
1151
+ "tolmete status show the state of the connection",
1152
+ "tolmete logout sign out and delete the local data"
1153
+ ].join("\n");
1154
+ var readStdin = () => new Promise((resolve2) => {
1155
+ const chunks = [];
1156
+ let size = 0;
1157
+ let done = false;
1158
+ const finish = (overflow) => {
1159
+ if (done) return;
1160
+ done = true;
1161
+ clearTimeout(timer);
1162
+ process.stdin.destroy();
1163
+ resolve2(overflow ? "" : Buffer.concat(chunks).toString("utf8"));
1164
+ };
1165
+ const timer = setTimeout(() => finish(true), STDIN_TIMEOUT_MS);
1166
+ process.stdin.on("data", (chunk) => {
1167
+ size += chunk.length;
1168
+ if (size > STDIN_LIMIT_BYTES) finish(true);
1169
+ else chunks.push(chunk);
1170
+ });
1171
+ process.stdin.on("end", () => finish(false));
1172
+ process.stdin.on("error", () => finish(true));
1173
+ });
1174
+ var runHook = async (adapter) => {
1175
+ try {
1176
+ const payload = JSON.parse(await readStdin());
1177
+ const reply2 = await adapter.hook?.(payload, defaultHome());
1178
+ if (reply2) process.stdout.write(reply2);
1179
+ } catch {
1180
+ }
1181
+ process.exit(0);
1182
+ };
1183
+ var runBackground = async (adapter) => {
1184
+ setTimeout(() => process.exit(0), WORKER_DEADLINE_MS).unref();
1185
+ try {
1186
+ const bundle = fileURLToPath(import.meta.url);
1187
+ await adapter.worker(defaultHome(), () => existsSync(bundle));
1188
+ } catch {
1189
+ }
1190
+ process.exit(0);
1191
+ };
1192
+ var runLogin = async (args) => {
1193
+ const home = defaultHome();
1194
+ const flag = args.indexOf("--api-url");
1195
+ const custom = flag === -1 ? void 0 : args[flag + 1];
1196
+ if (args.includes("--detach")) {
1197
+ await loginDetached(out, custom);
1198
+ return;
1199
+ }
1200
+ const quiet = args.includes("--auto");
1201
+ const apiUrl = assertApiUrl(quiet ? DEFAULT_API_URL : custom || DEFAULT_API_URL);
1202
+ const result = await login({
1203
+ home,
1204
+ apiUrl,
1205
+ print: quiet ? () => void 0 : out,
1206
+ open: openBrowser
1207
+ });
1208
+ if (quiet) return;
1209
+ out(
1210
+ result.ok ? `Signed in (organization ${result.organizationId}). AI usage statistics are sent for repositories connected in Tolmete.` : result.message
1211
+ );
1212
+ if (!result.ok) process.exitCode = 1;
1213
+ };
1214
+ var main = async (adapter) => {
1215
+ ignoreBrokenStdout();
1216
+ const [command2, ...args] = process.argv.slice(2);
1217
+ switch (command2) {
1218
+ case "hook":
1219
+ return runHook(adapter);
1220
+ case "worker":
1221
+ return runBackground(adapter);
1222
+ case "login":
1223
+ return runLogin(args);
1224
+ case "status":
1225
+ for (const line of await statusLines(defaultHome(), adapter.signIn, adapter.statusNotes))
1226
+ out(line);
1227
+ return;
1228
+ case "--help":
1229
+ case "-h":
1230
+ return out(USAGE);
1231
+ case "logout":
1232
+ return out(await logout(defaultHome()));
1233
+ default:
1234
+ out(USAGE);
1235
+ process.exitCode = command2 === void 0 ? 0 : 2;
1236
+ }
1237
+ };
1238
+ var runCli = (adapter) => {
1239
+ main(adapter).catch(() => {
1240
+ out("Tolmete failed. Run this again, or see the README for what is stored.");
1241
+ process.exitCode = 1;
1242
+ });
1243
+ };
1244
+
1245
+ // src/cursor-hook.ts
1246
+ import { existsSync as existsSync2, rmSync as rmSync2, statSync as statSync2 } from "node:fs";
1247
+ import { isAbsolute } from "node:path";
1248
+
1249
+ // src/spool.ts
1250
+ import { randomBytes as randomBytes5 } from "node:crypto";
1251
+ import { mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
1252
+ import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
1253
+ import { join as join8 } from "node:path";
1254
+ var RENAME_ATTEMPTS2 = 8;
1255
+ var RENAME_WAIT_MS = 25;
1256
+ var isSpoolTime = (value) => isFiniteNumber(value) && Math.abs(value) <= 864e13;
1257
+ var writeSpoolFile = (dir, record) => {
1258
+ mkdirSync(dir, { recursive: true, mode: 448 });
1259
+ const file = join8(
1260
+ dir,
1261
+ `${String(record.at).padStart(13, "0")}-${randomBytes5(4).toString("hex")}.json`
1262
+ );
1263
+ const temp = `${file}.tmp`;
1264
+ writeFileSync(temp, JSON.stringify(record), { mode: 384 });
1265
+ for (let attempt = 1; ; attempt++) {
1266
+ try {
1267
+ renameSync(temp, file);
1268
+ return file;
1269
+ } catch (error) {
1270
+ if (attempt === RENAME_ATTEMPTS2 || !TRANSIENT_RENAME_CODES.has(errCode(error) ?? "")) {
1271
+ rmSync(temp, { force: true });
1272
+ throw error;
1273
+ }
1274
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_WAIT_MS);
1275
+ }
1276
+ }
1277
+ };
1278
+ var readSpoolDir = async (dir, guard) => {
1279
+ const names = (await readdir4(dir).catch(() => [])).filter((name) => name.endsWith(".json"));
1280
+ const entries = [];
1281
+ for (const name of names.sort()) {
1282
+ const path = join8(dir, name);
1283
+ try {
1284
+ const text = await readFile4(path, "utf8");
1285
+ const mtimeMs = (await stat4(path)).mtimeMs;
1286
+ let record = null;
1287
+ try {
1288
+ const value = JSON.parse(text);
1289
+ record = guard(value) ? value : null;
1290
+ } catch {
1291
+ }
1292
+ entries.push({ path, record, mtimeMs });
1293
+ } catch {
1294
+ }
1295
+ }
1296
+ return entries;
1297
+ };
1298
+
1299
+ // src/cursor-spool.ts
1300
+ var INT4_MAX2 = 2147483647;
1301
+ var MAX_ROOTS = 20;
1302
+ var MAX_PATH = 4096;
1303
+ var MAX_LOOP = 1e6;
1304
+ var ID_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
1305
+ var nullable = (guard) => (v) => v === null || guard(v);
1306
+ var isCount = nullable(
1307
+ (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= INT4_MAX2
1308
+ );
1309
+ var isText = (max) => nullable((v) => typeof v === "string" && v.length > 0 && v.length <= max);
1310
+ var isRoot = (v) => isRecord(v) && typeof v.cwd === "string" && v.cwd.length > 0 && v.cwd.length <= MAX_PATH && isText(255)(v.branch);
1311
+ var isCursorRecord = (value) => {
1312
+ if (!isRecord(value)) return false;
1313
+ const t = value.tokens;
1314
+ return value.v === 1 && isSpoolTime(value.at) && (value.kind === "prompt" || value.kind === "response" || value.kind === "stop") && typeof value.sessionId === "string" && ID_PATTERN.test(value.sessionId) && typeof value.generationId === "string" && ID_PATTERN.test(value.generationId) && Array.isArray(value.roots) && value.roots.length > 0 && value.roots.length <= MAX_ROOTS && value.roots.every(isRoot) && isText(128)(value.model) && isCount(value.loopCount) && (value.loopCount === null || value.loopCount <= MAX_LOOP) && (t === null || isRecord(t) && [t.inputTokens, t.outputTokens, t.cacheReadTokens, t.cacheWriteTokens].every(isCount));
1315
+ };
1316
+ var writeRecord = (home, partition, record) => writeSpoolFile(paths.cursorSpool(home, partition), record);
1317
+ var readSpool = (home, partition) => readSpoolDir(paths.cursorSpool(home, partition), isCursorRecord);
1318
+
1319
+ // src/cursor-hook.ts
1320
+ var CURSOR_EVENTS = ["sessionStart", "beforeSubmitPrompt", "afterAgentResponse", "stop"];
1321
+ var ID_PATTERN2 = /^[A-Za-z0-9._-]{1,100}$/;
1322
+ var MAX_MODEL = 128;
1323
+ var MAX_LOOP2 = 1e6;
1324
+ var NO_MODEL = /* @__PURE__ */ new Set(["default", "auto", "unknown"]);
1325
+ var modelOf = (payload) => {
1326
+ for (const value of [payload.model_id, payload.model]) {
1327
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_MODEL) continue;
1328
+ return NO_MODEL.has(value.toLowerCase()) ? null : value;
1329
+ }
1330
+ return null;
1331
+ };
1332
+ var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= INT4_MAX2 ? value : null;
1333
+ var tokensOf = (payload) => {
1334
+ const input = count(payload.input_tokens);
1335
+ const output = count(payload.output_tokens);
1336
+ const read = count(payload.cache_read_tokens);
1337
+ const write2 = count(payload.cache_write_tokens);
1338
+ if ([input, output, read, write2].every((v) => v === null || v === 0)) return null;
1339
+ const rest = input !== null && read !== null && write2 !== null ? input - read - write2 : null;
1340
+ return {
1341
+ inputTokens: rest !== null && rest >= 0 ? rest : null,
1342
+ outputTokens: output,
1343
+ cacheReadTokens: read,
1344
+ cacheWriteTokens: write2
1345
+ };
1346
+ };
1347
+ var isFolder = (path) => {
1348
+ try {
1349
+ return isAbsolute(path) && statSync2(path).isDirectory();
1350
+ } catch {
1351
+ return false;
1352
+ }
1353
+ };
1354
+ var folderOf = (value, platform) => {
1355
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_PATH) return null;
1356
+ const path = platform === "win32" ? value.replace(/^\/(?=[A-Za-z]:[\\/])/, "") : value;
1357
+ return isFolder(path) ? path : null;
1358
+ };
1359
+ var rootsOf = (payload, deps) => {
1360
+ const listed = Array.isArray(payload.workspace_roots) ? payload.workspace_roots : [];
1361
+ const found = /* @__PURE__ */ new Set();
1362
+ for (const value of listed.slice(0, MAX_ROOTS)) {
1363
+ const folder = folderOf(value, deps.platform);
1364
+ if (folder) found.add(folder);
1365
+ }
1366
+ if (found.size === 0) {
1367
+ const folder = folderOf(deps.env.CURSOR_PROJECT_DIR, deps.platform);
1368
+ if (folder) found.add(folder);
1369
+ }
1370
+ return [...found];
1371
+ };
1372
+ var hasString = (value) => typeof value === "string" && value.length > 0;
1373
+ var KINDS = {
1374
+ beforeSubmitPrompt: "prompt",
1375
+ afterAgentResponse: "response",
1376
+ stop: "stop"
1377
+ };
1378
+ var handleCursorHook = async (event, payload, deps) => {
1379
+ if (!isRecord(payload) || !hasString(payload.cursor_version)) return;
1380
+ const { home } = deps;
1381
+ const credentials = await readCredentials(home);
1382
+ if (!credentials || credentials.status !== "active") return;
1383
+ const partition = partitionOf(credentials);
1384
+ if (event === "sessionStart") {
1385
+ deps.spawnWorker();
1386
+ return;
1387
+ }
1388
+ if (!Object.hasOwn(KINDS, event)) return;
1389
+ const kind = KINDS[event];
1390
+ const sessionId = payload.conversation_id;
1391
+ const generationId = payload.generation_id;
1392
+ if (typeof sessionId !== "string" || typeof generationId !== "string" || !ID_PATTERN2.test(sessionId) || !ID_PATTERN2.test(generationId) || sessionId === generationId) {
1393
+ return;
1394
+ }
1395
+ const roots = rootsOf(payload, deps).map((cwd) => ({ cwd, branch: readBranch(cwd) }));
1396
+ if (roots.length === 0) return;
1397
+ const loop = payload.loop_count;
1398
+ const record = {
1399
+ v: 1,
1400
+ at: deps.now(),
1401
+ kind,
1402
+ sessionId,
1403
+ generationId,
1404
+ roots,
1405
+ model: modelOf(payload),
1406
+ tokens: kind === "prompt" ? null : tokensOf(payload),
1407
+ loopCount: kind === "stop" && typeof loop === "number" && Number.isInteger(loop) && loop >= 0 && loop <= MAX_LOOP2 ? loop : null
1408
+ };
1409
+ if (kind === "response" && record.tokens === null) return;
1410
+ const file = writeRecord(home, partition, record);
1411
+ const after = await readCredentials(home);
1412
+ if (!after || partitionOf(after) !== partition) {
1413
+ rmSync2(file, { force: true });
1414
+ return;
1415
+ }
1416
+ if (kind === "stop" && existsSync2(file)) deps.spawnWorker();
1417
+ };
1418
+
1419
+ // src/git-remote.ts
1420
+ import { execFile } from "node:child_process";
1421
+ import { existsSync as existsSync3 } from "node:fs";
1422
+ var GIT_TIMEOUT_MS = 2 * SECOND_MS;
1423
+ var SSH_TIMEOUT_MS = 3 * SECOND_MS;
1424
+ var REMOTE_NAMES = ["origin", "upstream"];
1425
+ var ALIAS_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1426
+ var NO_ANSWER_CODES = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "ENOMEM"]);
1427
+ var withoutGitVariables = (env) => Object.fromEntries(
1428
+ Object.entries(env).filter(([name]) => !name.toUpperCase().startsWith("GIT_"))
1429
+ );
1430
+ var defaultExec = (file, args, timeoutMs) => new Promise((resolve2, reject) => {
1431
+ const { cwd, env } = neutralSpawn();
1432
+ execFile(
1433
+ file,
1434
+ args,
1435
+ {
1436
+ timeout: timeoutMs,
1437
+ windowsHide: true,
1438
+ maxBuffer: 64 * 1024,
1439
+ cwd,
1440
+ env: { ...withoutGitVariables(env), GIT_TERMINAL_PROMPT: "0" }
1441
+ },
1442
+ // stderr is never read or logged: it can carry paths and URLs
1443
+ (error, stdout) => {
1444
+ if (!error) resolve2(stdout);
1445
+ else if (error.killed || NO_ANSWER_CODES.has(errCode(error) ?? "")) reject(error);
1446
+ else resolve2(null);
1447
+ }
1448
+ );
1449
+ });
1450
+ var resolveSshHost = async (exec, alias) => {
1451
+ const output = await exec("ssh", ["-G", alias], SSH_TIMEOUT_MS);
1452
+ const line = output?.split(/\r?\n/).find((l) => l.startsWith("hostname "));
1453
+ const host = line?.slice("hostname ".length).trim();
1454
+ return host && ALIAS_PATTERN.test(host) ? host : null;
1455
+ };
1456
+ var createRemoteResolver = (exec = defaultExec, memory) => {
1457
+ const byDirectory = /* @__PURE__ */ new Map();
1458
+ const byAlias = /* @__PURE__ */ new Map();
1459
+ const canonicalOf = async (remote) => {
1460
+ const direct = canonicalizeGitRemote(remote);
1461
+ if (direct) return direct;
1462
+ const parts = splitRemote(remote);
1463
+ const mayBeAlias = parts && !/^https?:/i.test(remote) && !isGitHost(parts.host) && ALIAS_PATTERN.test(parts.host);
1464
+ if (!mayBeAlias) return null;
1465
+ let resolved = byAlias.get(parts.host);
1466
+ if (!resolved) {
1467
+ resolved = resolveSshHost(exec, parts.host);
1468
+ byAlias.set(parts.host, resolved);
1469
+ }
1470
+ const host = await resolved;
1471
+ return host ? canonicalizeGitRemote(`https://${host}/${parts.path}`) : null;
1472
+ };
1473
+ const lookup = async (cwd) => {
1474
+ if (!existsSync3(cwd)) return memory?.get(cwd) ?? [];
1475
+ const found = [];
1476
+ for (const name of REMOTE_NAMES) {
1477
+ const url = (await exec("git", ["-C", cwd, "remote", "get-url", name], GIT_TIMEOUT_MS))?.trim();
1478
+ const canonical = url ? await canonicalOf(url) : null;
1479
+ if (canonical) found.push(canonical);
1480
+ }
1481
+ if (found.length > 0) memory?.set(cwd, found);
1482
+ return found;
1483
+ };
1484
+ return (cwd) => {
1485
+ let remotes = byDirectory.get(cwd);
1486
+ if (!remotes) {
1487
+ remotes = lookup(cwd);
1488
+ byDirectory.set(cwd, remotes);
1489
+ }
1490
+ return remotes;
1491
+ };
1492
+ };
1493
+
1494
+ // src/sender.ts
1495
+ var MAX_AGE_MS2 = 30 * DAY_MS;
1496
+ var FUTURE_RETRY_MS = 5 * MINUTE_MS;
1497
+ var DISCONNECTED_RETRY_MS = 6 * HOUR_MS;
1498
+ var NO_LIST_RETRY_MS = HOUR_MS;
1499
+ var BACKOFF_START_MS = MINUTE_MS;
1500
+ var BACKOFF_MAX_MS = HOUR_MS;
1501
+ var SEND_BUDGET_MS = MINUTE_MS;
1502
+ var SEND_LOCK = { waitMs: 0, staleMs: 10 * MINUTE_MS };
1503
+ var DROP_REASONS = /* @__PURE__ */ new Set(["unknown_field", "invalid_event", "occurred_too_old"]);
1504
+ var backoffMs = (failures, serverHintMs) => {
1505
+ const exponential = Math.min(BACKOFF_MAX_MS, BACKOFF_START_MS * 2 ** Math.max(0, failures - 1));
1506
+ const jittered = exponential * (0.8 + Math.random() * 0.4);
1507
+ return Math.min(BACKOFF_MAX_MS, Math.max(jittered, serverHintMs ?? 0));
1508
+ };
1509
+ var parseAnswer = (json) => {
1510
+ if (!isRecord(json) || !isFiniteNumber(json.accepted) || !isFiniteNumber(json.duplicates)) {
1511
+ return null;
1512
+ }
1513
+ if (!Array.isArray(json.rejected)) return null;
1514
+ const rejected = [];
1515
+ for (const item of json.rejected) {
1516
+ if (!isRecord(item) || !Number.isInteger(item.index) || typeof item.reason !== "string") {
1517
+ return null;
1518
+ }
1519
+ rejected.push({ index: item.index, reason: item.reason });
1520
+ }
1521
+ return rejected;
1522
+ };
1523
+ var identityMatches = (res, credentials) => {
1524
+ const organization = res.headers.get(ORGANIZATION_HEADER);
1525
+ const user = res.headers.get(USER_HEADER);
1526
+ return (organization === null || organization === credentials.organizationId) && (user === null || user === credentials.userId);
1527
+ };
1528
+ var interpretAnswer = (rejected, events, now) => {
1529
+ const held = [];
1530
+ for (const { index, reason } of rejected) {
1531
+ const event = events[index];
1532
+ if (!event || DROP_REASONS.has(reason)) continue;
1533
+ const delay = reason === "occurred_in_future" ? FUTURE_RETRY_MS : DISCONNECTED_RETRY_MS;
1534
+ held.push({ event, notBefore: now + delay });
1535
+ }
1536
+ return held;
1537
+ };
1538
+ var post = async (home, credentials, events, now) => {
1539
+ const result = await authedFetch(
1540
+ home,
1541
+ endpoints(credentials.apiUrl).events,
1542
+ jsonBody({ events }),
1543
+ partitionOf(credentials)
1544
+ );
1545
+ if (result.kind === "auth") {
1546
+ if (result.reason === "needs_login" || result.reason === "identity_changed") {
1547
+ return { kind: "stop", error: result.reason, backoff: false };
1548
+ }
1549
+ return { kind: "retry", error: result.reason, retryAfterMs: null };
1550
+ }
1551
+ const res = result.res;
1552
+ if (!identityMatches(res, credentials)) {
1553
+ return { kind: "stop", error: "identity_mismatch", backoff: true };
1554
+ }
1555
+ if (res.status === 200) {
1556
+ const rejected = parseAnswer(res.json);
1557
+ if (!rejected) return { kind: "retry", error: "bad_response", retryAfterMs: null };
1558
+ const refused = rejected.find((r) => DROP_REASONS.has(r.reason));
1559
+ const held = interpretAnswer(rejected, events, now);
1560
+ return refused ? { kind: "ok", held, error: `rejected_${refused.reason}` } : { kind: "ok", held };
1561
+ }
1562
+ if (res.status === 400) return { kind: "drop", error: "http_400" };
1563
+ if (res.status === 413) {
1564
+ if (events.length === 1) return { kind: "drop", error: "http_413" };
1565
+ const middle = events.length >> 1;
1566
+ const held = [];
1567
+ let error;
1568
+ for (const half of [events.slice(0, middle), events.slice(middle)]) {
1569
+ const result2 = await post(home, credentials, half, now);
1570
+ if (result2.kind === "ok") held.push(...result2.held);
1571
+ else if (result2.kind === "drop") error = result2.error;
1572
+ else return result2;
1573
+ if (result2.kind === "ok" && result2.error) error = result2.error;
1574
+ }
1575
+ return error === void 0 ? { kind: "ok", held } : { kind: "ok", held, error };
1576
+ }
1577
+ return {
1578
+ kind: "retry",
1579
+ error: res.status === 0 ? "network" : `http_${res.status}`,
1580
+ retryAfterMs: retryAfterMs(res)
1581
+ };
1582
+ };
1583
+ var sortEvents = (events, cache, now) => {
1584
+ const listed = cache.hashes === null ? null : new Set(cache.hashes);
1585
+ const sorted = { send: [], held: [], cache, matchedChanged: false };
1586
+ for (const event of events) {
1587
+ if (Date.parse(event.occurredAt) < now - MAX_AGE_MS2) continue;
1588
+ if (listed === null) {
1589
+ sorted.held.push({ event, notBefore: now + NO_LIST_RETRY_MS });
1590
+ continue;
1591
+ }
1592
+ const hash = remoteUrlHash(event.remote);
1593
+ if (listed.has(hash)) {
1594
+ sorted.send.push(event);
1595
+ if (noteMatch(sorted.cache, hash, now)) sorted.matchedChanged = true;
1596
+ continue;
1597
+ }
1598
+ const lastMatch = sorted.cache.matched[hash];
1599
+ if (lastMatch !== void 0 && now - lastMatch < MATCH_MEMORY_MS) {
1600
+ sorted.held.push({ event, notBefore: now + DISCONNECTED_RETRY_MS });
1601
+ }
1602
+ }
1603
+ return sorted;
1604
+ };
1605
+ var requeue = async (home, partition, held, now) => {
1606
+ const byTime = /* @__PURE__ */ new Map();
1607
+ for (const { event, notBefore } of held) {
1608
+ byTime.set(notBefore, [...byTime.get(notBefore) ?? [], event]);
1609
+ }
1610
+ for (const [notBefore, events] of byTime) {
1611
+ const oldest = Math.min(now, ...events.map((e) => Date.parse(e.occurredAt) || now));
1612
+ await enqueue(home, partition, events, oldest, notBefore);
1613
+ }
1614
+ };
1615
+ var isStillSignedIn = async (home, partition) => {
1616
+ const current = await readCredentials(home);
1617
+ return current !== null && partitionOf(current) === partition;
1618
+ };
1619
+ var sendOne = async (home, credentials, partition, batch, now) => {
1620
+ const cache = await readRepositories(home, partition);
1621
+ const sorted = sortEvents(batch.events, cache, now);
1622
+ let held = sorted.held;
1623
+ if (sorted.send.length > 0) {
1624
+ const result = await post(home, credentials, sorted.send, now);
1625
+ if (!await isStillSignedIn(home, partition)) return "stop";
1626
+ if (result.kind === "stop" || result.kind === "retry") {
1627
+ const failures = (await readState(home, partition)).failures + 1;
1628
+ const backoff = result.kind === "retry" || result.backoff;
1629
+ await updateState(home, partition, {
1630
+ failures,
1631
+ lastError: result.error,
1632
+ nextAttemptAt: backoff ? now + backoffMs(failures, result.kind === "retry" ? result.retryAfterMs : null) : 0
1633
+ });
1634
+ return "stop";
1635
+ }
1636
+ if (result.kind === "ok") held = [...held, ...result.held];
1637
+ const error = result.error ?? null;
1638
+ const state = await readState(home, partition);
1639
+ await updateState(home, partition, {
1640
+ failures: 0,
1641
+ nextAttemptAt: 0,
1642
+ lastError: error,
1643
+ lastSuccessAt: result.kind === "ok" ? now : state.lastSuccessAt
1644
+ });
1645
+ if (sorted.matchedChanged) await saveRepositories(home, partition, sorted.cache, now);
1646
+ }
1647
+ await requeue(home, partition, held, now);
1648
+ await removeFiles(batch.files);
1649
+ return "continue";
1650
+ };
1651
+ var sendLoop = async ({
1652
+ home,
1653
+ isInstalled,
1654
+ now = Date.now,
1655
+ budgetMs = SEND_BUDGET_MS
1656
+ }) => {
1657
+ const deadline = now() + budgetMs;
1658
+ while (now() < deadline && isInstalled()) {
1659
+ const credentials = await readCredentials(home);
1660
+ if (!credentials || credentials.status !== "active") return;
1661
+ const partition = partitionOf(credentials);
1662
+ const waitUntil = (await readState(home, partition)).nextAttemptAt;
1663
+ if (waitUntil > now() && waitUntil <= now() + BACKOFF_MAX_MS) return;
1664
+ const batch = await takeBatch(home, partition, now());
1665
+ if (!batch) return;
1666
+ if (await sendOne(home, credentials, partition, batch, now()) === "stop") return;
1667
+ }
1668
+ };
1669
+ var runSender = async (options) => {
1670
+ await withLock(paths.lock(options.home, "send"), SEND_LOCK, () => sendLoop(options));
1671
+ };
1672
+
1673
+ // src/cursor-worker.ts
1674
+ var MAX_AGE_MS3 = 30 * DAY_MS;
1675
+ var SETTLE_MS = 2 * SECOND_MS;
1676
+ var NO_STOP_MS = 6 * HOUR_MS;
1677
+ var UNRESOLVED_MS = 7 * DAY_MS;
1678
+ var FUTURE_MS = HOUR_MS;
1679
+ var providerOf = (model) => {
1680
+ const name = (model ?? "").toLowerCase().split("/").pop() ?? "";
1681
+ const is = (...prefixes) => prefixes.some((p) => name.startsWith(p));
1682
+ if (is("claude", "sonnet", "opus", "haiku")) return "anthropic";
1683
+ if (is("gpt", "chatgpt", "codex") || /^o\d/.test(name)) return "openai";
1684
+ if (is("gemini")) return "google";
1685
+ if (is("grok")) return "xai";
1686
+ if (is("deepseek")) return "deepseek";
1687
+ if (is("kimi")) return "moonshot";
1688
+ if (is("composer", "cursor")) return "cursor";
1689
+ return "unknown";
1690
+ };
1691
+ var latest = (records) => records.reduce((a, r) => !a || r.at >= a.at ? r : a, void 0);
1692
+ var isReady = (records, now, settleMs) => {
1693
+ if (records.some((r) => r.kind === "stop" && now - r.at >= settleMs)) return true;
1694
+ const newest = latest(records);
1695
+ if (newest === void 0) return false;
1696
+ return now - newest.at > NO_STOP_MS || newest.at - now > FUTURE_MS;
1697
+ };
1698
+ var planGroup = (records, now) => {
1699
+ const prompt = records.filter((r) => r.kind === "prompt").reduce((a, r) => !a || r.at < a.at ? r : a, void 0);
1700
+ const withTokens = (kind) => latest(records.filter((r) => r.kind === kind && r.tokens !== null));
1701
+ const usage = withTokens("stop") ?? withTokens("response");
1702
+ const draftsOf = (source, id, interactions, model2, tokens) => source.roots.map((root) => ({
1703
+ inputTokens: null,
1704
+ outputTokens: null,
1705
+ cacheReadTokens: null,
1706
+ cacheWriteTokens: null,
1707
+ ...tokens,
1708
+ toolEventId: id,
1709
+ sessionId: source.sessionId,
1710
+ cwd: root.cwd,
1711
+ branch: root.branch,
1712
+ model: model2,
1713
+ occurredAt: new Date(Math.min(source.at, now)).toISOString(),
1714
+ interactions
1715
+ }));
1716
+ const model = usage?.model ?? prompt?.model ?? records.find((r) => r.model)?.model ?? null;
1717
+ const provider = providerOf(model);
1718
+ const planned = [];
1719
+ if (prompt) {
1720
+ planned.push({
1721
+ drafts: draftsOf(prompt, `p:${prompt.generationId}`, 1, null, null),
1722
+ provider
1723
+ });
1724
+ }
1725
+ if (usage) {
1726
+ planned.push({
1727
+ drafts: draftsOf(usage, `r:${usage.generationId}`, 0, model, usage.tokens),
1728
+ provider
1729
+ });
1730
+ }
1731
+ return planned;
1732
+ };
1733
+ var sameSignIn = async (home, partition) => {
1734
+ const current = await readCredentials(home);
1735
+ return !!current && partitionOf(current) === partition;
1736
+ };
1737
+ var collect = async (deps, prefetched) => {
1738
+ const { home } = deps;
1739
+ const now = (deps.now ?? Date.now)();
1740
+ const settleMs = deps.settleMs ?? SETTLE_MS;
1741
+ const credentials = await readCredentials(home);
1742
+ if (!credentials || credentials.status !== "active") return;
1743
+ const partition = partitionOf(credentials);
1744
+ if (partition !== prefetched.partition) return;
1745
+ const { cache } = prefetched;
1746
+ const done = [];
1747
+ const groups = /* @__PURE__ */ new Map();
1748
+ for (const { path, record, mtimeMs } of await readSpool(home, partition)) {
1749
+ if (!record) {
1750
+ if (now - mtimeMs > HOUR_MS) done.push(path);
1751
+ continue;
1752
+ }
1753
+ if (now - record.at > MAX_AGE_MS3) {
1754
+ done.push(path);
1755
+ continue;
1756
+ }
1757
+ const key = `${record.sessionId}|${record.generationId}`;
1758
+ const group = groups.get(key) ?? { records: [] };
1759
+ group.records.push({ path, record });
1760
+ groups.set(key, group);
1761
+ }
1762
+ if (cache.hashes === null) {
1763
+ if (!await sameSignIn(home, partition)) return;
1764
+ await saveRepositories(home, partition, cache, now);
1765
+ await removeFiles(done);
1766
+ return;
1767
+ }
1768
+ const ready = [...groups.values()].filter(
1769
+ (g) => isReady(
1770
+ g.records.map((r) => r.record),
1771
+ now,
1772
+ settleMs
1773
+ )
1774
+ );
1775
+ const { memory, save: saveMemory } = await loadCwdMemory(home, now);
1776
+ const resolve2 = createRemoteResolver(deps.exec, memory);
1777
+ const pick = async ({ drafts, provider }) => {
1778
+ let remembered = null;
1779
+ let waiting = false;
1780
+ for (const draft of drafts) {
1781
+ const [result] = await toEvents("Cursor", [{ draft, provider }], resolve2, cache, now);
1782
+ if (result?.unresolved) waiting = true;
1783
+ if (!result?.event) continue;
1784
+ if (result.connected) return { event: result.event, waiting };
1785
+ remembered ??= result.event;
1786
+ }
1787
+ return { event: remembered, waiting };
1788
+ };
1789
+ const events = [];
1790
+ for (const group of ready) {
1791
+ const records = group.records.map((r) => r.record);
1792
+ const picked = [];
1793
+ let waiting = false;
1794
+ for (const planned of planGroup(records, now)) {
1795
+ const result = await pick(planned);
1796
+ if (result.waiting) waiting = true;
1797
+ if (result.event) picked.push(result.event);
1798
+ }
1799
+ const age = now - Math.min(...records.map((r) => r.at));
1800
+ if (waiting && age <= UNRESOLVED_MS) continue;
1801
+ events.push(...picked);
1802
+ done.push(...group.records.map((r) => r.path));
1803
+ }
1804
+ if (!await sameSignIn(home, partition)) return;
1805
+ await enqueue(home, partition, events, now);
1806
+ if (await enforceLimit(home, partition) > 0) {
1807
+ await updateState(home, partition, { lastError: "queue_overflow" });
1808
+ }
1809
+ await saveRepositories(home, partition, cache, now);
1810
+ await saveMemory();
1811
+ await removeFiles(done);
1812
+ await noteRecorded(home, partition, "Cursor", events);
1813
+ await removeStaleTemps(paths.cursorSpool(home, partition), now);
1814
+ await pruneOld(home, now);
1815
+ };
1816
+ var runCursorWorker = async (deps) => {
1817
+ await sleep(deps.waitMs ?? deps.settleMs ?? SETTLE_MS);
1818
+ await withPrefetched(deps, (prefetched) => collect(deps, prefetched));
1819
+ await runSender({ home: deps.home, isInstalled: deps.isInstalled, now: deps.now });
1820
+ };
1821
+
1822
+ // src/spawn.ts
1823
+ import { spawn as spawn2 } from "node:child_process";
1824
+ var spawnDetached = (args, extraEnv = {}) => {
1825
+ const { cwd, env } = neutralSpawn();
1826
+ spawn2(process.execPath, [process.argv[1] ?? "", ...args], {
1827
+ detached: true,
1828
+ stdio: "ignore",
1829
+ windowsHide: true,
1830
+ cwd,
1831
+ env: { ...env, ...extraEnv }
1832
+ }).on("error", () => void 0).unref();
1833
+ };
1834
+
1835
+ // src/main-cursor.ts
1836
+ var reply = (event) => event === "beforeSubmitPrompt" ? '{"continue":true}' : "{}";
1837
+ var write = (text) => Promise.race([
1838
+ new Promise((resolve2) => process.stdout.write(text, () => resolve2())),
1839
+ sleep(SECOND_MS)
1840
+ ]);
1841
+ var runHook2 = async (event) => {
1842
+ ignoreBrokenStdout();
1843
+ if (event === void 0 || !CURSOR_EVENTS.includes(event)) process.exit(0);
1844
+ await write(reply(event));
1845
+ try {
1846
+ let text = await readStdin();
1847
+ while (text.charCodeAt(0) === 65279) text = text.slice(1);
1848
+ const payload = JSON.parse(text);
1849
+ await handleCursorHook(event, payload, {
1850
+ home: defaultHome(),
1851
+ env: process.env,
1852
+ now: Date.now,
1853
+ spawnWorker: () => spawnDetached(["worker"]),
1854
+ platform: process.platform
1855
+ });
1856
+ } catch {
1857
+ }
1858
+ process.exit(0);
1859
+ };
1860
+ var command = process.argv[2];
1861
+ if (command === "hook") {
1862
+ runHook2(process.argv[3]).catch(() => process.exit(0));
1863
+ } else {
1864
+ runCli({
1865
+ worker: (home, isInstalled) => runCursorWorker({ home, isInstalled }),
1866
+ signIn: `Run in a terminal: ${terminalCommand("login")}`
1867
+ });
1868
+ }