@tolmete/cli 0.0.0-stage → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/codex/.codex-plugin/plugin.json +11 -0
- package/codex/hooks/hooks.json +66 -0
- package/codex/runtime/bootstrap.ps1 +91 -0
- package/codex/runtime/bootstrap.sh +147 -0
- package/codex/runtime/tolmete.mjs +1866 -0
- package/codex/runtime/tolmete.ps1 +66 -0
- package/codex/runtime/tolmete.sh +95 -0
- package/install.mjs +173 -0
- package/package.json +11 -4
- package/README.md +0 -3
|
@@ -0,0 +1,1866 @@
|
|
|
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.dev.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 latest = await readRepositories(home, partition);
|
|
493
|
+
const base = mine.hashes !== null && mine.fetchedAt >= latest.fetchedAt ? mine : latest;
|
|
494
|
+
const matched = { ...latest.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, latest.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(latest)) {
|
|
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 latest = Math.max(known[tool] ?? 0, ...times);
|
|
631
|
+
if (latest !== known[tool]) {
|
|
632
|
+
await writeJsonAtomic(paths.lastRecorded(home, partition), { ...known, [tool]: latest });
|
|
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 = (message2) => ({ ok: false, message: message2 });
|
|
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 reply = await adapter.hook?.(payload, defaultHome());
|
|
1178
|
+
if (reply) process.stdout.write(reply);
|
|
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 [command, ...args] = process.argv.slice(2);
|
|
1217
|
+
switch (command) {
|
|
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 = command === 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/codex-hook.ts
|
|
1246
|
+
import { readdirSync, rmSync as rmSync2, statSync as statSync2 } from "node:fs";
|
|
1247
|
+
import { isAbsolute } from "node:path";
|
|
1248
|
+
|
|
1249
|
+
// src/codex-rollout.ts
|
|
1250
|
+
import { open as open3 } from "node:fs/promises";
|
|
1251
|
+
var HEAD_BYTES = 1024 * 1024;
|
|
1252
|
+
var BEFORE_BYTES = 1024 * 1024;
|
|
1253
|
+
var AFTER_BYTES = 256 * 1024;
|
|
1254
|
+
var readRange = async (path, start, length) => {
|
|
1255
|
+
let handle;
|
|
1256
|
+
try {
|
|
1257
|
+
handle = await open3(path, "r");
|
|
1258
|
+
} catch {
|
|
1259
|
+
return "";
|
|
1260
|
+
}
|
|
1261
|
+
try {
|
|
1262
|
+
const buffer = Buffer.alloc(length);
|
|
1263
|
+
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
|
1264
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
1265
|
+
} catch {
|
|
1266
|
+
return "";
|
|
1267
|
+
} finally {
|
|
1268
|
+
await handle.close();
|
|
1269
|
+
}
|
|
1270
|
+
};
|
|
1271
|
+
var readSessionMeta = async (path) => {
|
|
1272
|
+
const first = (await readRange(path, 0, HEAD_BYTES)).split("\n")[0] ?? "";
|
|
1273
|
+
const field = (name) => new RegExp(`"${name}":"([^"\\\\]*)"`).exec(first)?.[1] ?? null;
|
|
1274
|
+
return { modelProvider: field("model_provider"), source: field("source") };
|
|
1275
|
+
};
|
|
1276
|
+
var readTurnTrigger = async (path, size, turnId) => {
|
|
1277
|
+
const start = Math.max(0, size - BEFORE_BYTES - 1);
|
|
1278
|
+
const lines = (await readRange(path, start, size - start + AFTER_BYTES)).split("\n");
|
|
1279
|
+
if (start > 0) lines.shift();
|
|
1280
|
+
for (const raw of lines) {
|
|
1281
|
+
if (!raw.includes('"task_started"') || !raw.includes(turnId)) continue;
|
|
1282
|
+
try {
|
|
1283
|
+
const line = JSON.parse(raw);
|
|
1284
|
+
const body = isRecord(line) && isRecord(line.payload) ? line.payload : line;
|
|
1285
|
+
if (!isRecord(body) || body.type !== "task_started" || body.turn_id !== turnId) continue;
|
|
1286
|
+
const trigger = isRecord(body.turn_attribution) ? body.turn_attribution.turn_trigger : null;
|
|
1287
|
+
return typeof trigger === "string" ? trigger : null;
|
|
1288
|
+
} catch {
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
return null;
|
|
1292
|
+
};
|
|
1293
|
+
|
|
1294
|
+
// src/spool.ts
|
|
1295
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
1296
|
+
import { mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
1297
|
+
import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
|
|
1298
|
+
import { join as join8 } from "node:path";
|
|
1299
|
+
var RENAME_ATTEMPTS2 = 8;
|
|
1300
|
+
var RENAME_WAIT_MS = 25;
|
|
1301
|
+
var isSpoolTime = (value) => isFiniteNumber(value) && Math.abs(value) <= 864e13;
|
|
1302
|
+
var writeSpoolFile = (dir, record) => {
|
|
1303
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1304
|
+
const file = join8(
|
|
1305
|
+
dir,
|
|
1306
|
+
`${String(record.at).padStart(13, "0")}-${randomBytes5(4).toString("hex")}.json`
|
|
1307
|
+
);
|
|
1308
|
+
const temp = `${file}.tmp`;
|
|
1309
|
+
writeFileSync(temp, JSON.stringify(record), { mode: 384 });
|
|
1310
|
+
for (let attempt = 1; ; attempt++) {
|
|
1311
|
+
try {
|
|
1312
|
+
renameSync(temp, file);
|
|
1313
|
+
return file;
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
if (attempt === RENAME_ATTEMPTS2 || !TRANSIENT_RENAME_CODES.has(errCode(error) ?? "")) {
|
|
1316
|
+
rmSync(temp, { force: true });
|
|
1317
|
+
throw error;
|
|
1318
|
+
}
|
|
1319
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, RENAME_WAIT_MS);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
var readSpoolDir = async (dir, guard) => {
|
|
1324
|
+
const names = (await readdir4(dir).catch(() => [])).filter((name) => name.endsWith(".json"));
|
|
1325
|
+
const entries = [];
|
|
1326
|
+
for (const name of names.sort()) {
|
|
1327
|
+
const path = join8(dir, name);
|
|
1328
|
+
try {
|
|
1329
|
+
const text = await readFile4(path, "utf8");
|
|
1330
|
+
const mtimeMs = (await stat4(path)).mtimeMs;
|
|
1331
|
+
let record = null;
|
|
1332
|
+
try {
|
|
1333
|
+
const value = JSON.parse(text);
|
|
1334
|
+
record = guard(value) ? value : null;
|
|
1335
|
+
} catch {
|
|
1336
|
+
}
|
|
1337
|
+
entries.push({ path, record, mtimeMs });
|
|
1338
|
+
} catch {
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
return entries;
|
|
1342
|
+
};
|
|
1343
|
+
|
|
1344
|
+
// src/codex-spool.ts
|
|
1345
|
+
var nullable = (guard) => (v) => v === null || guard(v);
|
|
1346
|
+
var isString = (v) => typeof v === "string";
|
|
1347
|
+
var isCount = nullable(isFiniteNumber);
|
|
1348
|
+
var isCodexRecord = (value) => {
|
|
1349
|
+
if (!isRecord(value)) return false;
|
|
1350
|
+
const t = value.tokens;
|
|
1351
|
+
return value.v === 1 && isSpoolTime(value.at) && (value.kind === "prompt" || value.kind === "usage") && isString(value.id) && isString(value.sessionId) && isString(value.cwd) && [value.turnId, value.branch, value.model, value.transcriptPath].every(nullable(isString)) && isCount(value.transcriptSize) && (t === null || isRecord(t) && [t.inputTokens, t.outputTokens, t.cacheReadTokens, t.cacheWriteTokens].every(isCount));
|
|
1352
|
+
};
|
|
1353
|
+
var writeRecord = (home, partition, record) => writeSpoolFile(paths.codexSpool(home, partition), record);
|
|
1354
|
+
var readSpool = (home, partition) => readSpoolDir(paths.codexSpool(home, partition), isCodexRecord);
|
|
1355
|
+
|
|
1356
|
+
// src/spawn.ts
|
|
1357
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1358
|
+
import { open as open4 } from "node:fs/promises";
|
|
1359
|
+
import { dirname as dirname5 } from "node:path";
|
|
1360
|
+
var claim = async (file) => {
|
|
1361
|
+
try {
|
|
1362
|
+
await ensureDir(dirname5(file));
|
|
1363
|
+
await (await open4(file, "wx", 384)).close();
|
|
1364
|
+
return true;
|
|
1365
|
+
} catch {
|
|
1366
|
+
return false;
|
|
1367
|
+
}
|
|
1368
|
+
};
|
|
1369
|
+
var spawnDetached = (args, extraEnv = {}) => {
|
|
1370
|
+
const { cwd, env } = neutralSpawn();
|
|
1371
|
+
spawn2(process.execPath, [process.argv[1] ?? "", ...args], {
|
|
1372
|
+
detached: true,
|
|
1373
|
+
stdio: "ignore",
|
|
1374
|
+
windowsHide: true,
|
|
1375
|
+
cwd,
|
|
1376
|
+
env: { ...env, ...extraEnv }
|
|
1377
|
+
}).on("error", () => void 0).unref();
|
|
1378
|
+
};
|
|
1379
|
+
|
|
1380
|
+
// src/codex-hook.ts
|
|
1381
|
+
var REQUEST_ID_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
|
|
1382
|
+
var MAX_ID = 120;
|
|
1383
|
+
var MAX_PATH = 4096;
|
|
1384
|
+
var truthy = (value) => value !== void 0 && value !== "" && value !== "0" && value !== "false";
|
|
1385
|
+
var message = (text) => JSON.stringify({ systemMessage: text }).replace(
|
|
1386
|
+
/[^\x20-\x7e]/g,
|
|
1387
|
+
(c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`
|
|
1388
|
+
);
|
|
1389
|
+
var str = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max ? value : null;
|
|
1390
|
+
var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
|
1391
|
+
var tokensOf = (usage) => {
|
|
1392
|
+
const input = count(usage.input_tokens);
|
|
1393
|
+
const output = count(usage.output_tokens);
|
|
1394
|
+
const cached = count(usage.cached_input_tokens);
|
|
1395
|
+
const written = count(usage.cache_write_input_tokens);
|
|
1396
|
+
if ([input, output, cached, written].every((v) => v === null)) return null;
|
|
1397
|
+
const rest = input === null ? null : input - (cached ?? 0) - (written ?? 0);
|
|
1398
|
+
return {
|
|
1399
|
+
inputTokens: rest !== null && rest >= 0 ? rest : null,
|
|
1400
|
+
outputTokens: output,
|
|
1401
|
+
cacheReadTokens: cached,
|
|
1402
|
+
cacheWriteTokens: written
|
|
1403
|
+
};
|
|
1404
|
+
};
|
|
1405
|
+
var present = (value) => value !== void 0 && value !== null && value !== "";
|
|
1406
|
+
var recordOf = (payload, now) => {
|
|
1407
|
+
const sessionId = str(payload.session_id, MAX_ID);
|
|
1408
|
+
const cwd = str(payload.cwd, MAX_PATH);
|
|
1409
|
+
if (!sessionId || !cwd) return null;
|
|
1410
|
+
const path = str(payload.transcript_path, MAX_PATH);
|
|
1411
|
+
const base = {
|
|
1412
|
+
v: 1,
|
|
1413
|
+
at: now,
|
|
1414
|
+
sessionId,
|
|
1415
|
+
turnId: str(payload.turn_id, MAX_ID),
|
|
1416
|
+
cwd,
|
|
1417
|
+
branch: null,
|
|
1418
|
+
model: str(payload.model, MAX_ID),
|
|
1419
|
+
transcriptPath: path !== null && isAbsolute(path) && path.endsWith(".jsonl") ? path : null,
|
|
1420
|
+
transcriptSize: null
|
|
1421
|
+
};
|
|
1422
|
+
if (payload.hook_event_name === "UserPromptSubmit") {
|
|
1423
|
+
if (!base.turnId || present(payload.agent_id)) return null;
|
|
1424
|
+
return { ...base, kind: "prompt", id: `p:${base.turnId}`, tokens: null };
|
|
1425
|
+
}
|
|
1426
|
+
if (payload.hook_event_name === "PostModelRequest" && isRecord(payload.token_usage)) {
|
|
1427
|
+
const requestId = str(payload.request_id, MAX_ID);
|
|
1428
|
+
const tokens = tokensOf(payload.token_usage);
|
|
1429
|
+
if (!requestId || !REQUEST_ID_PATTERN.test(requestId) || !tokens) return null;
|
|
1430
|
+
const attempt = count(payload.attempt_number) ?? 0;
|
|
1431
|
+
return { ...base, kind: "usage", id: `r:${requestId}:${attempt}`, tokens };
|
|
1432
|
+
}
|
|
1433
|
+
return null;
|
|
1434
|
+
};
|
|
1435
|
+
var sizeOf = (path) => {
|
|
1436
|
+
try {
|
|
1437
|
+
return path ? statSync2(path).size : null;
|
|
1438
|
+
} catch {
|
|
1439
|
+
return null;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
var hasSpool = (home, partition) => {
|
|
1443
|
+
try {
|
|
1444
|
+
return readdirSync(paths.codexSpool(home, partition)).some((name) => name.endsWith(".json"));
|
|
1445
|
+
} catch {
|
|
1446
|
+
return false;
|
|
1447
|
+
}
|
|
1448
|
+
};
|
|
1449
|
+
var handleCodexHook = async (payload, deps) => {
|
|
1450
|
+
if (!isRecord(payload)) return null;
|
|
1451
|
+
const { home, env } = deps;
|
|
1452
|
+
const event = payload.hook_event_name;
|
|
1453
|
+
const credentials = await readCredentials(home);
|
|
1454
|
+
if (!credentials) {
|
|
1455
|
+
if (event !== "SessionStart" || payload.source !== "startup") return null;
|
|
1456
|
+
if (truthy(env.CI) || truthy(env.SSH_CONNECTION)) return null;
|
|
1457
|
+
const path = str(payload.transcript_path, MAX_PATH);
|
|
1458
|
+
if (path && (await readSessionMeta(path)).source === "exec") return null;
|
|
1459
|
+
return await claim(paths.codexHint(home)) ? message(
|
|
1460
|
+
`Tolmete: not signed in. To start sending AI usage statistics, run in a terminal: ${deps.signIn}`
|
|
1461
|
+
) : null;
|
|
1462
|
+
}
|
|
1463
|
+
const sessionId = str(payload.session_id, MAX_ID);
|
|
1464
|
+
if (credentials.status === "needs_login") {
|
|
1465
|
+
const speaks = event === "SessionStart" || event === "UserPromptSubmit";
|
|
1466
|
+
const firstTime = sessionId !== null && speaks && await claim(paths.notified(home, sessionId));
|
|
1467
|
+
return firstTime ? message(`Tolmete: sign in again. Run in a terminal: ${deps.signIn}`) : null;
|
|
1468
|
+
}
|
|
1469
|
+
const partition = partitionOf(credentials);
|
|
1470
|
+
if (event === "SessionStart" || event === "Stop" || event === "SessionEnd") {
|
|
1471
|
+
if (event === "SessionStart" || hasSpool(home, partition)) deps.spawnWorker();
|
|
1472
|
+
return null;
|
|
1473
|
+
}
|
|
1474
|
+
const record = recordOf(payload, deps.now());
|
|
1475
|
+
if (!record) return null;
|
|
1476
|
+
record.branch = readBranch(record.cwd);
|
|
1477
|
+
if (record.kind === "prompt") record.transcriptSize = sizeOf(record.transcriptPath);
|
|
1478
|
+
const file = writeRecord(home, partition, record);
|
|
1479
|
+
const after = await readCredentials(home);
|
|
1480
|
+
if (!after || partitionOf(after) !== partition) rmSync2(file, { force: true });
|
|
1481
|
+
return null;
|
|
1482
|
+
};
|
|
1483
|
+
|
|
1484
|
+
// src/git-remote.ts
|
|
1485
|
+
import { execFile } from "node:child_process";
|
|
1486
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
1487
|
+
var GIT_TIMEOUT_MS = 2 * SECOND_MS;
|
|
1488
|
+
var SSH_TIMEOUT_MS = 3 * SECOND_MS;
|
|
1489
|
+
var REMOTE_NAMES = ["origin", "upstream"];
|
|
1490
|
+
var ALIAS_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1491
|
+
var NO_ANSWER_CODES = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "ENOMEM"]);
|
|
1492
|
+
var withoutGitVariables = (env) => Object.fromEntries(
|
|
1493
|
+
Object.entries(env).filter(([name]) => !name.toUpperCase().startsWith("GIT_"))
|
|
1494
|
+
);
|
|
1495
|
+
var defaultExec = (file, args, timeoutMs) => new Promise((resolve2, reject) => {
|
|
1496
|
+
const { cwd, env } = neutralSpawn();
|
|
1497
|
+
execFile(
|
|
1498
|
+
file,
|
|
1499
|
+
args,
|
|
1500
|
+
{
|
|
1501
|
+
timeout: timeoutMs,
|
|
1502
|
+
windowsHide: true,
|
|
1503
|
+
maxBuffer: 64 * 1024,
|
|
1504
|
+
cwd,
|
|
1505
|
+
env: { ...withoutGitVariables(env), GIT_TERMINAL_PROMPT: "0" }
|
|
1506
|
+
},
|
|
1507
|
+
// stderr is never read or logged: it can carry paths and URLs
|
|
1508
|
+
(error, stdout) => {
|
|
1509
|
+
if (!error) resolve2(stdout);
|
|
1510
|
+
else if (error.killed || NO_ANSWER_CODES.has(errCode(error) ?? "")) reject(error);
|
|
1511
|
+
else resolve2(null);
|
|
1512
|
+
}
|
|
1513
|
+
);
|
|
1514
|
+
});
|
|
1515
|
+
var resolveSshHost = async (exec, alias) => {
|
|
1516
|
+
const output = await exec("ssh", ["-G", alias], SSH_TIMEOUT_MS);
|
|
1517
|
+
const line = output?.split(/\r?\n/).find((l) => l.startsWith("hostname "));
|
|
1518
|
+
const host = line?.slice("hostname ".length).trim();
|
|
1519
|
+
return host && ALIAS_PATTERN.test(host) ? host : null;
|
|
1520
|
+
};
|
|
1521
|
+
var createRemoteResolver = (exec = defaultExec, memory) => {
|
|
1522
|
+
const byDirectory = /* @__PURE__ */ new Map();
|
|
1523
|
+
const byAlias = /* @__PURE__ */ new Map();
|
|
1524
|
+
const canonicalOf = async (remote) => {
|
|
1525
|
+
const direct = canonicalizeGitRemote(remote);
|
|
1526
|
+
if (direct) return direct;
|
|
1527
|
+
const parts = splitRemote(remote);
|
|
1528
|
+
const mayBeAlias = parts && !/^https?:/i.test(remote) && !isGitHost(parts.host) && ALIAS_PATTERN.test(parts.host);
|
|
1529
|
+
if (!mayBeAlias) return null;
|
|
1530
|
+
let resolved = byAlias.get(parts.host);
|
|
1531
|
+
if (!resolved) {
|
|
1532
|
+
resolved = resolveSshHost(exec, parts.host);
|
|
1533
|
+
byAlias.set(parts.host, resolved);
|
|
1534
|
+
}
|
|
1535
|
+
const host = await resolved;
|
|
1536
|
+
return host ? canonicalizeGitRemote(`https://${host}/${parts.path}`) : null;
|
|
1537
|
+
};
|
|
1538
|
+
const lookup = async (cwd) => {
|
|
1539
|
+
if (!existsSync2(cwd)) return memory?.get(cwd) ?? [];
|
|
1540
|
+
const found = [];
|
|
1541
|
+
for (const name of REMOTE_NAMES) {
|
|
1542
|
+
const url = (await exec("git", ["-C", cwd, "remote", "get-url", name], GIT_TIMEOUT_MS))?.trim();
|
|
1543
|
+
const canonical = url ? await canonicalOf(url) : null;
|
|
1544
|
+
if (canonical) found.push(canonical);
|
|
1545
|
+
}
|
|
1546
|
+
if (found.length > 0) memory?.set(cwd, found);
|
|
1547
|
+
return found;
|
|
1548
|
+
};
|
|
1549
|
+
return (cwd) => {
|
|
1550
|
+
let remotes = byDirectory.get(cwd);
|
|
1551
|
+
if (!remotes) {
|
|
1552
|
+
remotes = lookup(cwd);
|
|
1553
|
+
byDirectory.set(cwd, remotes);
|
|
1554
|
+
}
|
|
1555
|
+
return remotes;
|
|
1556
|
+
};
|
|
1557
|
+
};
|
|
1558
|
+
|
|
1559
|
+
// src/sender.ts
|
|
1560
|
+
var MAX_AGE_MS2 = 30 * DAY_MS;
|
|
1561
|
+
var FUTURE_RETRY_MS = 5 * MINUTE_MS;
|
|
1562
|
+
var DISCONNECTED_RETRY_MS = 6 * HOUR_MS;
|
|
1563
|
+
var NO_LIST_RETRY_MS = HOUR_MS;
|
|
1564
|
+
var BACKOFF_START_MS = MINUTE_MS;
|
|
1565
|
+
var BACKOFF_MAX_MS = HOUR_MS;
|
|
1566
|
+
var SEND_BUDGET_MS = MINUTE_MS;
|
|
1567
|
+
var SEND_LOCK = { waitMs: 0, staleMs: 10 * MINUTE_MS };
|
|
1568
|
+
var DROP_REASONS = /* @__PURE__ */ new Set(["unknown_field", "invalid_event", "occurred_too_old"]);
|
|
1569
|
+
var backoffMs = (failures, serverHintMs) => {
|
|
1570
|
+
const exponential = Math.min(BACKOFF_MAX_MS, BACKOFF_START_MS * 2 ** Math.max(0, failures - 1));
|
|
1571
|
+
const jittered = exponential * (0.8 + Math.random() * 0.4);
|
|
1572
|
+
return Math.min(BACKOFF_MAX_MS, Math.max(jittered, serverHintMs ?? 0));
|
|
1573
|
+
};
|
|
1574
|
+
var parseAnswer = (json) => {
|
|
1575
|
+
if (!isRecord(json) || !isFiniteNumber(json.accepted) || !isFiniteNumber(json.duplicates)) {
|
|
1576
|
+
return null;
|
|
1577
|
+
}
|
|
1578
|
+
if (!Array.isArray(json.rejected)) return null;
|
|
1579
|
+
const rejected = [];
|
|
1580
|
+
for (const item of json.rejected) {
|
|
1581
|
+
if (!isRecord(item) || !Number.isInteger(item.index) || typeof item.reason !== "string") {
|
|
1582
|
+
return null;
|
|
1583
|
+
}
|
|
1584
|
+
rejected.push({ index: item.index, reason: item.reason });
|
|
1585
|
+
}
|
|
1586
|
+
return rejected;
|
|
1587
|
+
};
|
|
1588
|
+
var identityMatches = (res, credentials) => {
|
|
1589
|
+
const organization = res.headers.get(ORGANIZATION_HEADER);
|
|
1590
|
+
const user = res.headers.get(USER_HEADER);
|
|
1591
|
+
return (organization === null || organization === credentials.organizationId) && (user === null || user === credentials.userId);
|
|
1592
|
+
};
|
|
1593
|
+
var interpretAnswer = (rejected, events, now) => {
|
|
1594
|
+
const held = [];
|
|
1595
|
+
for (const { index, reason } of rejected) {
|
|
1596
|
+
const event = events[index];
|
|
1597
|
+
if (!event || DROP_REASONS.has(reason)) continue;
|
|
1598
|
+
const delay = reason === "occurred_in_future" ? FUTURE_RETRY_MS : DISCONNECTED_RETRY_MS;
|
|
1599
|
+
held.push({ event, notBefore: now + delay });
|
|
1600
|
+
}
|
|
1601
|
+
return held;
|
|
1602
|
+
};
|
|
1603
|
+
var post = async (home, credentials, events, now) => {
|
|
1604
|
+
const result = await authedFetch(
|
|
1605
|
+
home,
|
|
1606
|
+
endpoints(credentials.apiUrl).events,
|
|
1607
|
+
jsonBody({ events }),
|
|
1608
|
+
partitionOf(credentials)
|
|
1609
|
+
);
|
|
1610
|
+
if (result.kind === "auth") {
|
|
1611
|
+
if (result.reason === "needs_login" || result.reason === "identity_changed") {
|
|
1612
|
+
return { kind: "stop", error: result.reason, backoff: false };
|
|
1613
|
+
}
|
|
1614
|
+
return { kind: "retry", error: result.reason, retryAfterMs: null };
|
|
1615
|
+
}
|
|
1616
|
+
const res = result.res;
|
|
1617
|
+
if (!identityMatches(res, credentials)) {
|
|
1618
|
+
return { kind: "stop", error: "identity_mismatch", backoff: true };
|
|
1619
|
+
}
|
|
1620
|
+
if (res.status === 200) {
|
|
1621
|
+
const rejected = parseAnswer(res.json);
|
|
1622
|
+
if (!rejected) return { kind: "retry", error: "bad_response", retryAfterMs: null };
|
|
1623
|
+
const refused = rejected.find((r) => DROP_REASONS.has(r.reason));
|
|
1624
|
+
const held = interpretAnswer(rejected, events, now);
|
|
1625
|
+
return refused ? { kind: "ok", held, error: `rejected_${refused.reason}` } : { kind: "ok", held };
|
|
1626
|
+
}
|
|
1627
|
+
if (res.status === 400) return { kind: "drop", error: "http_400" };
|
|
1628
|
+
if (res.status === 413) {
|
|
1629
|
+
if (events.length === 1) return { kind: "drop", error: "http_413" };
|
|
1630
|
+
const middle = events.length >> 1;
|
|
1631
|
+
const held = [];
|
|
1632
|
+
let error;
|
|
1633
|
+
for (const half of [events.slice(0, middle), events.slice(middle)]) {
|
|
1634
|
+
const result2 = await post(home, credentials, half, now);
|
|
1635
|
+
if (result2.kind === "ok") held.push(...result2.held);
|
|
1636
|
+
else if (result2.kind === "drop") error = result2.error;
|
|
1637
|
+
else return result2;
|
|
1638
|
+
if (result2.kind === "ok" && result2.error) error = result2.error;
|
|
1639
|
+
}
|
|
1640
|
+
return error === void 0 ? { kind: "ok", held } : { kind: "ok", held, error };
|
|
1641
|
+
}
|
|
1642
|
+
return {
|
|
1643
|
+
kind: "retry",
|
|
1644
|
+
error: res.status === 0 ? "network" : `http_${res.status}`,
|
|
1645
|
+
retryAfterMs: retryAfterMs(res)
|
|
1646
|
+
};
|
|
1647
|
+
};
|
|
1648
|
+
var sortEvents = (events, cache, now) => {
|
|
1649
|
+
const listed = cache.hashes === null ? null : new Set(cache.hashes);
|
|
1650
|
+
const sorted = { send: [], held: [], cache, matchedChanged: false };
|
|
1651
|
+
for (const event of events) {
|
|
1652
|
+
if (Date.parse(event.occurredAt) < now - MAX_AGE_MS2) continue;
|
|
1653
|
+
if (listed === null) {
|
|
1654
|
+
sorted.held.push({ event, notBefore: now + NO_LIST_RETRY_MS });
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
const hash = remoteUrlHash(event.remote);
|
|
1658
|
+
if (listed.has(hash)) {
|
|
1659
|
+
sorted.send.push(event);
|
|
1660
|
+
if (noteMatch(sorted.cache, hash, now)) sorted.matchedChanged = true;
|
|
1661
|
+
continue;
|
|
1662
|
+
}
|
|
1663
|
+
const lastMatch = sorted.cache.matched[hash];
|
|
1664
|
+
if (lastMatch !== void 0 && now - lastMatch < MATCH_MEMORY_MS) {
|
|
1665
|
+
sorted.held.push({ event, notBefore: now + DISCONNECTED_RETRY_MS });
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
return sorted;
|
|
1669
|
+
};
|
|
1670
|
+
var requeue = async (home, partition, held, now) => {
|
|
1671
|
+
const byTime = /* @__PURE__ */ new Map();
|
|
1672
|
+
for (const { event, notBefore } of held) {
|
|
1673
|
+
byTime.set(notBefore, [...byTime.get(notBefore) ?? [], event]);
|
|
1674
|
+
}
|
|
1675
|
+
for (const [notBefore, events] of byTime) {
|
|
1676
|
+
const oldest = Math.min(now, ...events.map((e) => Date.parse(e.occurredAt) || now));
|
|
1677
|
+
await enqueue(home, partition, events, oldest, notBefore);
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
var isStillSignedIn = async (home, partition) => {
|
|
1681
|
+
const current = await readCredentials(home);
|
|
1682
|
+
return current !== null && partitionOf(current) === partition;
|
|
1683
|
+
};
|
|
1684
|
+
var sendOne = async (home, credentials, partition, batch, now) => {
|
|
1685
|
+
const cache = await readRepositories(home, partition);
|
|
1686
|
+
const sorted = sortEvents(batch.events, cache, now);
|
|
1687
|
+
let held = sorted.held;
|
|
1688
|
+
if (sorted.send.length > 0) {
|
|
1689
|
+
const result = await post(home, credentials, sorted.send, now);
|
|
1690
|
+
if (!await isStillSignedIn(home, partition)) return "stop";
|
|
1691
|
+
if (result.kind === "stop" || result.kind === "retry") {
|
|
1692
|
+
const failures = (await readState(home, partition)).failures + 1;
|
|
1693
|
+
const backoff = result.kind === "retry" || result.backoff;
|
|
1694
|
+
await updateState(home, partition, {
|
|
1695
|
+
failures,
|
|
1696
|
+
lastError: result.error,
|
|
1697
|
+
nextAttemptAt: backoff ? now + backoffMs(failures, result.kind === "retry" ? result.retryAfterMs : null) : 0
|
|
1698
|
+
});
|
|
1699
|
+
return "stop";
|
|
1700
|
+
}
|
|
1701
|
+
if (result.kind === "ok") held = [...held, ...result.held];
|
|
1702
|
+
const error = result.error ?? null;
|
|
1703
|
+
const state = await readState(home, partition);
|
|
1704
|
+
await updateState(home, partition, {
|
|
1705
|
+
failures: 0,
|
|
1706
|
+
nextAttemptAt: 0,
|
|
1707
|
+
lastError: error,
|
|
1708
|
+
lastSuccessAt: result.kind === "ok" ? now : state.lastSuccessAt
|
|
1709
|
+
});
|
|
1710
|
+
if (sorted.matchedChanged) await saveRepositories(home, partition, sorted.cache, now);
|
|
1711
|
+
}
|
|
1712
|
+
await requeue(home, partition, held, now);
|
|
1713
|
+
await removeFiles(batch.files);
|
|
1714
|
+
return "continue";
|
|
1715
|
+
};
|
|
1716
|
+
var sendLoop = async ({
|
|
1717
|
+
home,
|
|
1718
|
+
isInstalled,
|
|
1719
|
+
now = Date.now,
|
|
1720
|
+
budgetMs = SEND_BUDGET_MS
|
|
1721
|
+
}) => {
|
|
1722
|
+
const deadline = now() + budgetMs;
|
|
1723
|
+
while (now() < deadline && isInstalled()) {
|
|
1724
|
+
const credentials = await readCredentials(home);
|
|
1725
|
+
if (!credentials || credentials.status !== "active") return;
|
|
1726
|
+
const partition = partitionOf(credentials);
|
|
1727
|
+
const waitUntil = (await readState(home, partition)).nextAttemptAt;
|
|
1728
|
+
if (waitUntil > now() && waitUntil <= now() + BACKOFF_MAX_MS) return;
|
|
1729
|
+
const batch = await takeBatch(home, partition, now());
|
|
1730
|
+
if (!batch) return;
|
|
1731
|
+
if (await sendOne(home, credentials, partition, batch, now()) === "stop") return;
|
|
1732
|
+
}
|
|
1733
|
+
};
|
|
1734
|
+
var runSender = async (options) => {
|
|
1735
|
+
await withLock(paths.lock(options.home, "send"), SEND_LOCK, () => sendLoop(options));
|
|
1736
|
+
};
|
|
1737
|
+
|
|
1738
|
+
// src/codex-worker.ts
|
|
1739
|
+
var MAX_AGE_MS3 = 30 * DAY_MS;
|
|
1740
|
+
var UNRESOLVED_MS = 7 * DAY_MS;
|
|
1741
|
+
var DEFAULT_PROVIDER = "openai";
|
|
1742
|
+
var NOT_A_PERSON = /* @__PURE__ */ new Set(["exec", "goal", "guardian_review", "memory_consolidation"]);
|
|
1743
|
+
var KNOWN_PROVIDERS = /* @__PURE__ */ new Set([
|
|
1744
|
+
"openai",
|
|
1745
|
+
"azure",
|
|
1746
|
+
"anthropic",
|
|
1747
|
+
"google",
|
|
1748
|
+
"gemini",
|
|
1749
|
+
"mistral",
|
|
1750
|
+
"ollama",
|
|
1751
|
+
"lmstudio",
|
|
1752
|
+
"openrouter",
|
|
1753
|
+
"bedrock",
|
|
1754
|
+
"amazon-bedrock",
|
|
1755
|
+
"xai",
|
|
1756
|
+
"deepseek",
|
|
1757
|
+
"groq",
|
|
1758
|
+
"together",
|
|
1759
|
+
"fireworks"
|
|
1760
|
+
]);
|
|
1761
|
+
var providerOf = (modelProvider) => {
|
|
1762
|
+
const id = (modelProvider ?? "").trim().toLowerCase();
|
|
1763
|
+
if (id === "") return DEFAULT_PROVIDER;
|
|
1764
|
+
return KNOWN_PROVIDERS.has(id) ? id : "custom";
|
|
1765
|
+
};
|
|
1766
|
+
var draftOf = (record, trigger) => {
|
|
1767
|
+
const prompt = record.kind === "prompt";
|
|
1768
|
+
if (prompt && trigger !== null && (NOT_A_PERSON.has(trigger) || trigger.startsWith("automation"))) {
|
|
1769
|
+
return null;
|
|
1770
|
+
}
|
|
1771
|
+
return {
|
|
1772
|
+
inputTokens: null,
|
|
1773
|
+
outputTokens: null,
|
|
1774
|
+
cacheReadTokens: null,
|
|
1775
|
+
cacheWriteTokens: null,
|
|
1776
|
+
...record.tokens,
|
|
1777
|
+
toolEventId: record.id,
|
|
1778
|
+
sessionId: record.sessionId,
|
|
1779
|
+
cwd: record.cwd,
|
|
1780
|
+
branch: record.branch,
|
|
1781
|
+
model: prompt ? null : record.model,
|
|
1782
|
+
occurredAt: new Date(record.at).toISOString(),
|
|
1783
|
+
interactions: prompt ? 1 : 0
|
|
1784
|
+
};
|
|
1785
|
+
};
|
|
1786
|
+
var collect = async (deps, prefetched) => {
|
|
1787
|
+
const { home } = deps;
|
|
1788
|
+
const now = (deps.now ?? Date.now)();
|
|
1789
|
+
const credentials = await readCredentials(home);
|
|
1790
|
+
if (!credentials || credentials.status !== "active") return;
|
|
1791
|
+
const partition = partitionOf(credentials);
|
|
1792
|
+
if (partition !== prefetched.partition) return;
|
|
1793
|
+
const { cache } = prefetched;
|
|
1794
|
+
const done = [];
|
|
1795
|
+
const drafts = [];
|
|
1796
|
+
const metas = /* @__PURE__ */ new Map();
|
|
1797
|
+
for (const { path, record, mtimeMs } of await readSpool(home, partition)) {
|
|
1798
|
+
if (!record) {
|
|
1799
|
+
if (now - mtimeMs > HOUR_MS) done.push(path);
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
if (now - record.at > MAX_AGE_MS3) {
|
|
1803
|
+
done.push(path);
|
|
1804
|
+
continue;
|
|
1805
|
+
}
|
|
1806
|
+
const file = record.transcriptPath;
|
|
1807
|
+
let meta = file ? metas.get(file) : void 0;
|
|
1808
|
+
if (file && !meta) metas.set(file, meta = readSessionMeta(file));
|
|
1809
|
+
const isPrompt = record.kind === "prompt";
|
|
1810
|
+
const trigger = (isPrompt && file && record.transcriptSize !== null && record.turnId ? await readTurnTrigger(file, record.transcriptSize, record.turnId) : null) ?? (isPrompt && (await meta)?.source === "exec" ? "exec" : null);
|
|
1811
|
+
const draft = draftOf(record, trigger);
|
|
1812
|
+
if (!draft) {
|
|
1813
|
+
done.push(path);
|
|
1814
|
+
continue;
|
|
1815
|
+
}
|
|
1816
|
+
const provider = providerOf((await meta)?.modelProvider ?? null);
|
|
1817
|
+
drafts.push({ draft, provider, path, at: record.at });
|
|
1818
|
+
}
|
|
1819
|
+
const { memory, save: saveMemory } = await loadCwdMemory(home, now);
|
|
1820
|
+
const converted = await toEvents(
|
|
1821
|
+
"CodexCli",
|
|
1822
|
+
drafts,
|
|
1823
|
+
createRemoteResolver(deps.exec, memory),
|
|
1824
|
+
cache,
|
|
1825
|
+
now
|
|
1826
|
+
);
|
|
1827
|
+
const events = [];
|
|
1828
|
+
converted.forEach((result, i) => {
|
|
1829
|
+
const entry = drafts[i];
|
|
1830
|
+
if (!entry) return;
|
|
1831
|
+
if (!result.unresolved || now - entry.at > UNRESOLVED_MS) done.push(entry.path);
|
|
1832
|
+
if (result.event) events.push(result.event);
|
|
1833
|
+
});
|
|
1834
|
+
const current = await readCredentials(home);
|
|
1835
|
+
if (!current || partitionOf(current) !== partition) return;
|
|
1836
|
+
await enqueue(home, partition, events, now);
|
|
1837
|
+
if (await enforceLimit(home, partition) > 0) {
|
|
1838
|
+
await updateState(home, partition, { lastError: "queue_overflow" });
|
|
1839
|
+
}
|
|
1840
|
+
await saveRepositories(home, partition, cache, now);
|
|
1841
|
+
await saveMemory();
|
|
1842
|
+
await removeFiles(done);
|
|
1843
|
+
await noteRecorded(home, partition, "CodexCli", events);
|
|
1844
|
+
await removeStaleTemps(paths.codexSpool(home, partition), now);
|
|
1845
|
+
await pruneOld(home, now);
|
|
1846
|
+
};
|
|
1847
|
+
var runCodexWorker = async (deps) => {
|
|
1848
|
+
await withPrefetched(deps, (prefetched) => collect(deps, prefetched));
|
|
1849
|
+
await runSender({ home: deps.home, isInstalled: deps.isInstalled, now: deps.now });
|
|
1850
|
+
};
|
|
1851
|
+
|
|
1852
|
+
// src/main-codex.ts
|
|
1853
|
+
runCli({
|
|
1854
|
+
hook: (payload, home) => handleCodexHook(payload, {
|
|
1855
|
+
home,
|
|
1856
|
+
env: process.env,
|
|
1857
|
+
now: Date.now,
|
|
1858
|
+
spawnWorker: () => spawnDetached(["worker"]),
|
|
1859
|
+
signIn: terminalCommand("login")
|
|
1860
|
+
}),
|
|
1861
|
+
worker: (home, isInstalled) => runCodexWorker({ home, isInstalled }),
|
|
1862
|
+
signIn: `Run in a terminal: ${terminalCommand("login")}`,
|
|
1863
|
+
statusNotes: [
|
|
1864
|
+
"Codex CLI: its hooks run only after you trust them in /hooks, again after each update."
|
|
1865
|
+
]
|
|
1866
|
+
});
|