@tempoxyz/patron 0.0.0-stage → 0.0.10

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,214 @@
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
+ ...typeof config.tokensPerPage === "number" ? { tokensPerPage: config.tokensPerPage } : {}
148
+ };
149
+ }
150
+ async function writeConfig(home, config) {
151
+ await ensureHome(home);
152
+ await writePrivateFile(
153
+ statePaths(home).config,
154
+ `${JSON.stringify(config, null, " ")}
155
+ `
156
+ );
157
+ }
158
+ function emptyUsage(month) {
159
+ return { boughtTokens: 0, domains: {}, month, paidPages: 0 };
160
+ }
161
+ async function readUsage(home, now = /* @__PURE__ */ new Date()) {
162
+ const month = monthOf(now);
163
+ const path = statePaths(home).usage;
164
+ const value = await readJson(path).catch(() => {
165
+ throw unreadableUsage(path);
166
+ });
167
+ if (value === void 0) return emptyUsage(month);
168
+ if (!isUsageRecord(value)) throw unreadableUsage(path);
169
+ if (value.month !== month) return emptyUsage(month);
170
+ return {
171
+ boughtTokens: value.boughtTokens,
172
+ domains: value.domains && typeof value.domains === "object" ? { ...value.domains } : {},
173
+ month,
174
+ paidPages: Number(value.paidPages ?? 0)
175
+ };
176
+ }
177
+ function isUsageRecord(value) {
178
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
179
+ const usage = value;
180
+ return typeof usage.month === "string" && typeof usage.boughtTokens === "number" && Number.isFinite(usage.boughtTokens) && usage.boughtTokens >= 0;
181
+ }
182
+ function unreadableUsage(path) {
183
+ return new Error(
184
+ `${path} is unreadable, so Patron stops buying seals. Delete it to restart this month's budget count.`
185
+ );
186
+ }
187
+ async function updateUsage(home, update, now = /* @__PURE__ */ new Date()) {
188
+ await ensureHome(home);
189
+ return withLock(statePaths(home).usageLock, async () => {
190
+ const usage = await readUsage(home, now);
191
+ update(usage);
192
+ await writePrivateFile(statePaths(home).usage, `${JSON.stringify(usage)}
193
+ `);
194
+ return usage;
195
+ });
196
+ }
197
+
198
+ export {
199
+ __require,
200
+ __commonJS,
201
+ __export,
202
+ __toESM,
203
+ withLock,
204
+ tryLock,
205
+ AGENT_IDS,
206
+ statePaths,
207
+ ensureHome,
208
+ readJson,
209
+ writePrivateFile,
210
+ readConfig,
211
+ writeConfig,
212
+ readUsage,
213
+ updateUsage
214
+ };