@tempoxyz/patron 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,213 @@
1
+ import { createRequire as __patronCreateRequire } from 'node:module'
2
+ const require = __patronCreateRequire(import.meta.url)
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ try {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ } catch (e) {
19
+ throw mod = 0, e;
20
+ }
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+
43
+ // src/state.ts
44
+ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
45
+ import { join } from "node:path";
46
+
47
+ // src/lock.ts
48
+ import { open, rm, stat } from "node:fs/promises";
49
+ async function withLock(path, fn, options = {}) {
50
+ const deadline = Date.now() + (options.timeoutMs ?? 3e3);
51
+ const staleMs = options.staleMs ?? 1e4;
52
+ for (; ; ) {
53
+ try {
54
+ const handle = await open(path, "wx", 384);
55
+ await handle.close();
56
+ break;
57
+ } catch (error) {
58
+ if (error.code !== "EEXIST") throw error;
59
+ const age = await stat(path).then(
60
+ (stats) => Date.now() - stats.mtimeMs,
61
+ () => 0
62
+ );
63
+ if (age > staleMs) {
64
+ await rm(path, { force: true });
65
+ continue;
66
+ }
67
+ if (Date.now() > deadline) throw new Error(`Patron state is busy: ${path}`);
68
+ await new Promise((resolve) => setTimeout(resolve, 10 + Math.random() * 20));
69
+ }
70
+ }
71
+ try {
72
+ return await fn();
73
+ } finally {
74
+ await rm(path, { force: true });
75
+ }
76
+ }
77
+ async function tryLock(path, staleMs) {
78
+ try {
79
+ const handle = await open(path, "wx", 384);
80
+ await handle.close();
81
+ } catch (error) {
82
+ if (error.code !== "EEXIST") throw error;
83
+ const age = await stat(path).then(
84
+ (stats) => Date.now() - stats.mtimeMs,
85
+ () => 0
86
+ );
87
+ if (age <= staleMs) return void 0;
88
+ await rm(path, { force: true });
89
+ return tryLock(path, staleMs);
90
+ }
91
+ return () => rm(path, { force: true });
92
+ }
93
+
94
+ // src/state.ts
95
+ var AGENT_IDS = ["claude-code", "codex", "cursor", "amp"];
96
+ function statePaths(home) {
97
+ return {
98
+ config: join(home, "config.json"),
99
+ issuer: join(home, "issuer.json"),
100
+ key: join(home, "key"),
101
+ refillLock: join(home, "refill.lock"),
102
+ stateLock: join(home, "state.lock"),
103
+ tokens: join(home, "tokens.enc"),
104
+ usage: join(home, "usage.json"),
105
+ usageLock: join(home, "usage.lock"),
106
+ wallet: join(home, "wallet.json")
107
+ };
108
+ }
109
+ function monthOf(now) {
110
+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
111
+ }
112
+ async function ensureHome(home) {
113
+ await mkdir(home, { mode: 448, recursive: true });
114
+ }
115
+ async function readJson(path) {
116
+ try {
117
+ return JSON.parse(await readFile(path, "utf8"));
118
+ } catch (error) {
119
+ if (error.code === "ENOENT") return void 0;
120
+ throw error;
121
+ }
122
+ }
123
+ async function writePrivateFile(path, contents) {
124
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
125
+ await writeFile(temporary, contents, { mode: 384 });
126
+ await chmod(temporary, 384);
127
+ await rename(temporary, path);
128
+ }
129
+ async function readConfig(home) {
130
+ const value = await readJson(statePaths(home).config).catch(() => void 0);
131
+ if (!value || typeof value !== "object") return void 0;
132
+ const config = value;
133
+ if (config.version !== 1 || typeof config.address !== "string") return void 0;
134
+ return {
135
+ agents: Array.isArray(config.agents) ? config.agents.filter(
136
+ (agent) => AGENT_IDS.includes(agent)
137
+ ) : [],
138
+ address: config.address,
139
+ gatewayUrl: String(config.gatewayUrl ?? ""),
140
+ monthlyBudgetUsd: Number(config.monthlyBudgetUsd ?? 0),
141
+ network: config.network === "testnet" ? "testnet" : "mainnet",
142
+ paused: config.paused === true,
143
+ relayUrl: String(config.relayUrl ?? ""),
144
+ version: 1,
145
+ wallet: config.wallet === "key" ? "key" : "tempo",
146
+ ...typeof config.name === "string" ? { name: config.name } : {}
147
+ };
148
+ }
149
+ async function writeConfig(home, config) {
150
+ await ensureHome(home);
151
+ await writePrivateFile(
152
+ statePaths(home).config,
153
+ `${JSON.stringify(config, null, " ")}
154
+ `
155
+ );
156
+ }
157
+ function emptyUsage(month) {
158
+ return { boughtTokens: 0, domains: {}, month, paidPages: 0 };
159
+ }
160
+ async function readUsage(home, now = /* @__PURE__ */ new Date()) {
161
+ const month = monthOf(now);
162
+ const path = statePaths(home).usage;
163
+ const value = await readJson(path).catch(() => {
164
+ throw unreadableUsage(path);
165
+ });
166
+ if (value === void 0) return emptyUsage(month);
167
+ if (!isUsageRecord(value)) throw unreadableUsage(path);
168
+ if (value.month !== month) return emptyUsage(month);
169
+ return {
170
+ boughtTokens: value.boughtTokens,
171
+ domains: value.domains && typeof value.domains === "object" ? { ...value.domains } : {},
172
+ month,
173
+ paidPages: Number(value.paidPages ?? 0)
174
+ };
175
+ }
176
+ function isUsageRecord(value) {
177
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
178
+ const usage = value;
179
+ return typeof usage.month === "string" && typeof usage.boughtTokens === "number" && Number.isFinite(usage.boughtTokens) && usage.boughtTokens >= 0;
180
+ }
181
+ function unreadableUsage(path) {
182
+ return new Error(
183
+ `${path} is unreadable, so Patron stops buying tokens. Delete it to restart this month's budget count.`
184
+ );
185
+ }
186
+ async function updateUsage(home, update, now = /* @__PURE__ */ new Date()) {
187
+ await ensureHome(home);
188
+ return withLock(statePaths(home).usageLock, async () => {
189
+ const usage = await readUsage(home, now);
190
+ update(usage);
191
+ await writePrivateFile(statePaths(home).usage, `${JSON.stringify(usage)}
192
+ `);
193
+ return usage;
194
+ });
195
+ }
196
+
197
+ export {
198
+ __require,
199
+ __commonJS,
200
+ __export,
201
+ __toESM,
202
+ withLock,
203
+ tryLock,
204
+ AGENT_IDS,
205
+ statePaths,
206
+ ensureHome,
207
+ readJson,
208
+ writePrivateFile,
209
+ readConfig,
210
+ writeConfig,
211
+ readUsage,
212
+ updateUsage
213
+ };
@@ -0,0 +1,425 @@
1
+ import { createRequire as __patronCreateRequire } from 'node:module'
2
+ const require = __patronCreateRequire(import.meta.url)
3
+ import {
4
+ FileTokenStore,
5
+ clampTokensPerPage,
6
+ codexHome,
7
+ loadIssuer,
8
+ needsRefill,
9
+ normalizeDomain,
10
+ refillSize,
11
+ resolveSettings,
12
+ settingsFor,
13
+ spend,
14
+ startRefill
15
+ } from "./chunk-6Q7AFS33.js";
16
+ import {
17
+ readConfig,
18
+ readUsage,
19
+ updateUsage,
20
+ withLock,
21
+ writePrivateFile
22
+ } from "./chunk-NLCZ2IHE.js";
23
+
24
+ // src/hook.ts
25
+ import { homedir } from "node:os";
26
+
27
+ // src/hook-input.ts
28
+ var MAX_DOMAINS_PER_HOOK = 10;
29
+ var MAX_DEPTH = 6;
30
+ var MAX_URLS = 50;
31
+ var FETCH_TOOLS = /* @__PURE__ */ new Set(["WebFetch", "read_web_page"]);
32
+ var SEARCH_TOOLS = /* @__PURE__ */ new Set(["WebSearch", "web_search"]);
33
+ function hookUrls(payload) {
34
+ if (!isRecord(payload) || typeof payload.tool_name !== "string") return [];
35
+ const tool = payload.tool_name;
36
+ const response = "tool_response" in payload ? payload.tool_response : jsonValue(payload.tool_output);
37
+ if (FETCH_TOOLS.has(tool)) {
38
+ const input = payload.tool_input;
39
+ if (isRecord(input) && typeof input.url === "string") return [input.url];
40
+ const urls2 = [];
41
+ collectUrls(response, urls2, 0);
42
+ return urls2.slice(0, 1);
43
+ }
44
+ if (!SEARCH_TOOLS.has(tool)) return [];
45
+ const urls = [];
46
+ collectUrls(response, urls, 0);
47
+ if (urls.length === 0 && tool === "web_search") collectTextUrls(response, urls, 0);
48
+ return urls;
49
+ }
50
+ function hookDomains(payload) {
51
+ const domains = [];
52
+ for (const url of hookUrls(payload)) {
53
+ const domain = normalizeDomain(url);
54
+ if (domain && !domains.includes(domain)) domains.push(domain);
55
+ if (domains.length >= MAX_DOMAINS_PER_HOOK) break;
56
+ }
57
+ return domains;
58
+ }
59
+ function turnEnd(payload) {
60
+ if (!isRecord(payload)) return void 0;
61
+ if (payload.hook_event_name === "Stop" && typeof payload.turn_id === "string" && typeof payload.transcript_path === "string")
62
+ return { transcriptPath: payload.transcript_path };
63
+ if (payload.type === "agent-turn-complete" && typeof payload["thread-id"] === "string")
64
+ return { codexThreadId: payload["thread-id"] };
65
+ return void 0;
66
+ }
67
+ function isCursorPayload(payload) {
68
+ return isRecord(payload) && typeof payload.cursor_version === "string";
69
+ }
70
+ function parseHookInput(raw) {
71
+ try {
72
+ return JSON.parse(raw);
73
+ } catch {
74
+ return void 0;
75
+ }
76
+ }
77
+ function jsonValue(value) {
78
+ if (typeof value !== "string") return value;
79
+ try {
80
+ return JSON.parse(value);
81
+ } catch {
82
+ return value;
83
+ }
84
+ }
85
+ function collectUrls(value, urls, depth) {
86
+ if (depth > MAX_DEPTH || urls.length >= MAX_URLS) return;
87
+ if (Array.isArray(value)) {
88
+ for (const item of value) collectUrls(item, urls, depth + 1);
89
+ return;
90
+ }
91
+ if (!isRecord(value)) return;
92
+ for (const [key, item] of Object.entries(value)) {
93
+ if (key === "url" && typeof item === "string") urls.push(item);
94
+ else collectUrls(item, urls, depth + 1);
95
+ }
96
+ }
97
+ function collectTextUrls(value, urls, depth) {
98
+ if (depth > MAX_DEPTH || urls.length >= MAX_URLS) return;
99
+ if (typeof value === "string") {
100
+ for (const match of value.matchAll(/https?:\/\/[^\s"'<>()[\]`]+/g)) {
101
+ if (urls.length >= MAX_URLS) return;
102
+ urls.push(match[0].replace(/[.,;:!?]+$/, ""));
103
+ }
104
+ return;
105
+ }
106
+ if (Array.isArray(value))
107
+ for (const item of value) collectTextUrls(item, urls, depth + 1);
108
+ else if (isRecord(value))
109
+ for (const item of Object.values(value)) collectTextUrls(item, urls, depth + 1);
110
+ }
111
+ function isRecord(value) {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+
115
+ // src/transcript.ts
116
+ import { createHash } from "node:crypto";
117
+ import { mkdir, open, readdir, readFile, rm, stat } from "node:fs/promises";
118
+ import { basename, join } from "node:path";
119
+ var MAX_ROLLOUT_READ_BYTES = 16 * 1024 * 1024;
120
+ var SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
121
+ var MAX_REMEMBERED_DOMAINS = 2e3;
122
+ var MAX_DAY_DIRECTORIES = 400;
123
+ function isCodexRollout(path) {
124
+ const name = basename(path);
125
+ return name.startsWith("rollout-") && name.endsWith(".jsonl");
126
+ }
127
+ function codexRolloutUrls(lines) {
128
+ const urls = [];
129
+ for (const line of lines) {
130
+ if (!line.includes("http")) continue;
131
+ let record;
132
+ try {
133
+ record = JSON.parse(line);
134
+ } catch {
135
+ continue;
136
+ }
137
+ if (!isRecord2(record) || !isRecord2(record.payload)) continue;
138
+ const payload = record.payload;
139
+ if (record.type === "response_item") responseItemUrls(payload, urls);
140
+ else if (record.type === "event_msg") eventUrls(payload, urls);
141
+ }
142
+ return urls;
143
+ }
144
+ function responseItemUrls(item, urls) {
145
+ if (item.type === "web_search_call") pushUrl(urls, field(item.action, "url"));
146
+ else if (item.type === "message" && item.role === "assistant") {
147
+ for (const content of asArray(item.content))
148
+ for (const annotation of asArray(field(content, "annotations")))
149
+ if (field(annotation, "type") === "url_citation")
150
+ pushUrl(urls, field(annotation, "url"));
151
+ } else if (item.type === "function_call" && item.namespace === "web" && item.name === "run" && typeof item.arguments === "string") {
152
+ let commands;
153
+ try {
154
+ commands = JSON.parse(item.arguments);
155
+ } catch {
156
+ return;
157
+ }
158
+ for (const key of ["open", "find"])
159
+ for (const operation of asArray(field(commands, key)))
160
+ pushUrl(urls, field(operation, "ref_id"));
161
+ }
162
+ }
163
+ function eventUrls(event, urls) {
164
+ const search = event.type === "web_search_end" ? event : event.type === "item_completed" && field(event.item, "type") === "WebSearch" ? event.item : void 0;
165
+ if (!isRecord2(search)) return;
166
+ pushUrl(urls, field(search.action, "url"));
167
+ for (const result of asArray(search.results)) pushUrl(urls, field(result, "url"));
168
+ }
169
+ async function takeTranscriptDomains(home, transcriptPath2, options) {
170
+ if (!isCodexRollout(transcriptPath2)) return [];
171
+ const paths = sessionPaths(home, transcriptPath2);
172
+ await mkdir(paths.directory, { mode: 448, recursive: true });
173
+ return withLock(
174
+ paths.lock,
175
+ async () => {
176
+ const saved = await readState(paths.state);
177
+ const state = saved ?? { offset: 0, paid: [], pending: [] };
178
+ const { lines, offset } = await readNewLines(transcriptPath2, state.offset);
179
+ const known = /* @__PURE__ */ new Set([...state.paid, ...state.pending]);
180
+ const pending = [...state.pending];
181
+ for (const url of codexRolloutUrls(lines)) {
182
+ const domain = normalizeDomain(url);
183
+ if (domain && !known.has(domain)) {
184
+ known.add(domain);
185
+ pending.push(domain);
186
+ }
187
+ }
188
+ const taken = options.discard ? [] : pending.slice(0, options.max);
189
+ const next = {
190
+ offset,
191
+ paid: [...state.paid, ...taken].slice(-MAX_REMEMBERED_DOMAINS),
192
+ pending: options.discard ? [] : pending.slice(taken.length)
193
+ };
194
+ await writePrivateFile(paths.state, JSON.stringify(next));
195
+ if (!saved) await pruneSessions(paths.directory).catch(() => void 0);
196
+ return taken;
197
+ },
198
+ { timeoutMs: 1500 }
199
+ );
200
+ }
201
+ async function findCodexRollout(codexHome2, threadId) {
202
+ if (!/^[0-9a-f-]{8,64}$/i.test(threadId)) return void 0;
203
+ const root = join(codexHome2, "sessions");
204
+ let searched = 0;
205
+ for (const year of await numericEntries(root))
206
+ for (const month of await numericEntries(year))
207
+ for (const day of await numericEntries(month)) {
208
+ if (++searched > MAX_DAY_DIRECTORIES) return void 0;
209
+ const names = await readdir(day).catch(() => []);
210
+ const name = names.find(
211
+ (entry) => isCodexRollout(entry) && (entry.endsWith(`-${threadId}.jsonl`) || entry.includes(`-${threadId}_`))
212
+ );
213
+ if (name) return join(day, name);
214
+ }
215
+ return void 0;
216
+ }
217
+ async function numericEntries(directory) {
218
+ const names = await readdir(directory).catch(() => []);
219
+ return names.filter((name) => /^\d+$/.test(name)).sort((left, right) => Number(right) - Number(left)).map((name) => join(directory, name));
220
+ }
221
+ async function readNewLines(path, from) {
222
+ const handle = await open(path, "r");
223
+ try {
224
+ const { size } = await handle.stat();
225
+ const start = size < from ? 0 : from;
226
+ const length = Math.min(size - start, MAX_ROLLOUT_READ_BYTES);
227
+ if (length <= 0) return { lines: [], offset: start };
228
+ const buffer = Buffer.alloc(length);
229
+ const { bytesRead } = await handle.read(buffer, 0, length, start);
230
+ const end = buffer.subarray(0, bytesRead).lastIndexOf(10);
231
+ if (end === -1)
232
+ return {
233
+ lines: [],
234
+ offset: length === MAX_ROLLOUT_READ_BYTES ? start + length : start
235
+ };
236
+ return {
237
+ lines: buffer.subarray(0, end).toString("utf8").split("\n"),
238
+ offset: start + end + 1
239
+ };
240
+ } finally {
241
+ await handle.close();
242
+ }
243
+ }
244
+ function sessionPaths(home, transcriptPath2) {
245
+ const id = createHash("sha256").update(transcriptPath2).digest("hex").slice(0, 32);
246
+ const directory = join(home, "sessions");
247
+ return {
248
+ directory,
249
+ lock: join(directory, `${id}.lock`),
250
+ state: join(directory, `${id}.json`)
251
+ };
252
+ }
253
+ async function readState(path) {
254
+ let value;
255
+ try {
256
+ value = JSON.parse(await readFile(path, "utf8"));
257
+ } catch {
258
+ return void 0;
259
+ }
260
+ if (!isRecord2(value) || typeof value.offset !== "number") return void 0;
261
+ const strings = (list) => asArray(list).filter((item) => typeof item === "string");
262
+ return {
263
+ offset: value.offset,
264
+ paid: strings(value.paid),
265
+ pending: strings(value.pending)
266
+ };
267
+ }
268
+ async function pruneSessions(directory) {
269
+ const now = Date.now();
270
+ for (const name of await readdir(directory)) {
271
+ if (!name.endsWith(".json")) continue;
272
+ const path = join(directory, name);
273
+ const { mtimeMs } = await stat(path);
274
+ if (now - mtimeMs > SESSION_TTL_MS) await rm(path, { force: true });
275
+ }
276
+ }
277
+ function pushUrl(urls, value) {
278
+ if (typeof value === "string" && /^https?:\/\//i.test(value)) urls.push(value);
279
+ }
280
+ function field(value, key) {
281
+ return isRecord2(value) ? value[key] : void 0;
282
+ }
283
+ function asArray(value) {
284
+ return Array.isArray(value) ? value : [];
285
+ }
286
+ function isRecord2(value) {
287
+ return typeof value === "object" && value !== null && !Array.isArray(value);
288
+ }
289
+
290
+ // src/hook.ts
291
+ var HOOK_TIMEOUT_MS = 2e3;
292
+ var ABORT_MARGIN_MS = 500;
293
+ async function runHook(dependencies, timeoutMs = HOOK_TIMEOUT_MS) {
294
+ let timer;
295
+ const timeout = new Promise((resolve) => {
296
+ timer = setTimeout(
297
+ () => resolve({ paid: [], refill: false, skipped: "timeout" }),
298
+ timeoutMs
299
+ );
300
+ });
301
+ try {
302
+ const deadline = Date.now() + timeoutMs - Math.min(ABORT_MARGIN_MS, timeoutMs / 4);
303
+ return await Promise.race([payReads(dependencies, deadline).catch(failed), timeout]);
304
+ } catch {
305
+ return failed();
306
+ } finally {
307
+ clearTimeout(timer);
308
+ }
309
+ }
310
+ function failed() {
311
+ return { paid: [], refill: false, skipped: "error" };
312
+ }
313
+ async function payReads(dependencies, deadline) {
314
+ const payload = parseHookInput(await dependencies.readInput());
315
+ const turn = turnEnd(payload);
316
+ let domains = turn ? [] : hookDomains(payload);
317
+ if (!turn && domains.length === 0) return { paid: [], refill: false, skipped: "empty" };
318
+ const config = await readConfig(dependencies.settings.home);
319
+ if (!config) return { paid: [], refill: false, skipped: "not-setup" };
320
+ const settings = settingsFor(dependencies.settings, config);
321
+ if (turn) {
322
+ const path = await transcriptPath(turn, dependencies.agents);
323
+ if (!path) return { paid: [], refill: false, skipped: "empty" };
324
+ domains = await takeTranscriptDomains(settings.home, path, {
325
+ discard: config.paused,
326
+ max: MAX_DOMAINS_PER_HOOK
327
+ });
328
+ }
329
+ if (config.paused) return { paid: [], refill: false, skipped: "paused" };
330
+ if (domains.length === 0) return { paid: [], refill: false, skipped: "empty" };
331
+ const store = new FileTokenStore(settings.home);
332
+ const boundedFetch = withDeadline(dependencies.fetch ?? fetch, deadline);
333
+ const issuer = await loadIssuer(settings.home, settings.gatewayUrl, {
334
+ fetch: boundedFetch
335
+ });
336
+ const paid = [];
337
+ let empty = false;
338
+ const perPage = clampTokensPerPage(config.tokensPerPage);
339
+ reads: for (const domain of domains) {
340
+ for (let token = 0; token < perPage; token++) {
341
+ if (Date.now() >= deadline) break reads;
342
+ const result = await spend({
343
+ domain,
344
+ fetch: boundedFetch,
345
+ issuer,
346
+ relayUrl: settings.relayUrl,
347
+ store
348
+ }).catch(() => null);
349
+ if (result === void 0) {
350
+ empty = true;
351
+ break reads;
352
+ }
353
+ if (token === 0 && result?.ok) paid.push(result.domain || domain);
354
+ if (!result?.ok) break;
355
+ }
356
+ }
357
+ const now = dependencies.now?.() ?? /* @__PURE__ */ new Date();
358
+ if (paid.length > 0)
359
+ await updateUsage(
360
+ settings.home,
361
+ (usage) => {
362
+ usage.paidPages += paid.length;
363
+ for (const domain of paid)
364
+ usage.domains[domain] = (usage.domains[domain] ?? 0) + 1;
365
+ },
366
+ now
367
+ );
368
+ const refill = needsRefill(await store.count()) && refillSize(config, await readUsage(settings.home, now)) > 0;
369
+ if (refill) dependencies.startRefill();
370
+ return {
371
+ paid,
372
+ refill,
373
+ ...empty && paid.length === 0 ? { skipped: "no-tokens" } : {}
374
+ };
375
+ }
376
+ function withDeadline(fetchFn, deadline) {
377
+ return (input, init) => fetchFn(input, {
378
+ ...init,
379
+ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now()))
380
+ });
381
+ }
382
+ function transcriptPath(turn, agents = { env: process.env, home: homedir() }) {
383
+ if ("transcriptPath" in turn) return Promise.resolve(turn.transcriptPath);
384
+ return findCodexRollout(codexHome(agents.env, agents.home), turn.codexThreadId);
385
+ }
386
+
387
+ // src/hook-process.ts
388
+ var MAX_INPUT_BYTES = 8 * 1024 * 1024;
389
+ async function runHookProcess(argument = process.argv[3]) {
390
+ setTimeout(() => process.exit(0), HOOK_TIMEOUT_MS + 500).unref();
391
+ const raw = argument ?? await readStdin(HOOK_TIMEOUT_MS / 2);
392
+ if (isCursorPayload(parseHookInput(raw))) process.stdout.write("{}\n");
393
+ await runHook({
394
+ readInput: async () => raw,
395
+ settings: resolveSettings(),
396
+ startRefill: () => startRefill()
397
+ });
398
+ }
399
+ function readStdin(timeoutMs) {
400
+ return new Promise((resolve) => {
401
+ const chunks = [];
402
+ let size = 0;
403
+ const finish = () => {
404
+ clearTimeout(timer);
405
+ process.stdin.removeAllListeners();
406
+ process.stdin.pause();
407
+ resolve(Buffer.concat(chunks).toString("utf8"));
408
+ };
409
+ const timer = setTimeout(finish, timeoutMs);
410
+ process.stdin.on("data", (chunk) => {
411
+ size += chunk.length;
412
+ if (size > MAX_INPUT_BYTES) {
413
+ chunks.length = 0;
414
+ finish();
415
+ return;
416
+ }
417
+ chunks.push(chunk);
418
+ });
419
+ process.stdin.on("end", finish);
420
+ process.stdin.on("error", finish);
421
+ });
422
+ }
423
+ export {
424
+ runHookProcess
425
+ };