@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.
- package/README.md +64 -2
- package/dist/bin.js +13 -0
- package/dist/chunks/-SRYAMUCC.js +1119 -0
- package/dist/chunks/chunk-6TTNL3HT.js +214 -0
- package/dist/chunks/chunk-DEUBVELW.js +35984 -0
- package/dist/chunks/hook-process-ZBZ3WF5I.js +429 -0
- package/dist/chunks/wallet-MEBNL43A.js +155 -0
- package/package.json +47 -5
|
@@ -0,0 +1,429 @@
|
|
|
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
|
+
normalizePayee,
|
|
10
|
+
refillSize,
|
|
11
|
+
resolveSettings,
|
|
12
|
+
settingsFor,
|
|
13
|
+
spend,
|
|
14
|
+
startRefill
|
|
15
|
+
} from "./chunk-DEUBVELW.js";
|
|
16
|
+
import {
|
|
17
|
+
readConfig,
|
|
18
|
+
readUsage,
|
|
19
|
+
updateUsage,
|
|
20
|
+
withLock,
|
|
21
|
+
writePrivateFile
|
|
22
|
+
} from "./chunk-6TTNL3HT.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 = normalizePayee(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 = normalizePayee(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
|
+
let pending = domains.slice();
|
|
340
|
+
rounds: for (let round = 0; round < perPage && pending.length > 0; round++) {
|
|
341
|
+
const next = [];
|
|
342
|
+
for (const domain of pending) {
|
|
343
|
+
if (Date.now() >= deadline) break rounds;
|
|
344
|
+
const result = await spend({
|
|
345
|
+
domain,
|
|
346
|
+
fetch: boundedFetch,
|
|
347
|
+
issuer,
|
|
348
|
+
relayUrl: settings.relayUrl,
|
|
349
|
+
store
|
|
350
|
+
}).catch(() => null);
|
|
351
|
+
if (result === void 0) {
|
|
352
|
+
empty = true;
|
|
353
|
+
break rounds;
|
|
354
|
+
}
|
|
355
|
+
if (!result?.ok) continue;
|
|
356
|
+
if (round === 0) paid.push(result.domain || domain);
|
|
357
|
+
next.push(domain);
|
|
358
|
+
}
|
|
359
|
+
pending = next;
|
|
360
|
+
}
|
|
361
|
+
const now = dependencies.now?.() ?? /* @__PURE__ */ new Date();
|
|
362
|
+
if (paid.length > 0)
|
|
363
|
+
await updateUsage(
|
|
364
|
+
settings.home,
|
|
365
|
+
(usage) => {
|
|
366
|
+
usage.paidPages += paid.length;
|
|
367
|
+
for (const domain of paid)
|
|
368
|
+
usage.domains[domain] = (usage.domains[domain] ?? 0) + 1;
|
|
369
|
+
},
|
|
370
|
+
now
|
|
371
|
+
);
|
|
372
|
+
const refill = needsRefill(await store.count()) && refillSize(config, await readUsage(settings.home, now)) > 0;
|
|
373
|
+
if (refill) dependencies.startRefill();
|
|
374
|
+
return {
|
|
375
|
+
paid,
|
|
376
|
+
refill,
|
|
377
|
+
...empty && paid.length === 0 ? { skipped: "no-tokens" } : {}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function withDeadline(fetchFn, deadline) {
|
|
381
|
+
return (input, init) => fetchFn(input, {
|
|
382
|
+
...init,
|
|
383
|
+
signal: AbortSignal.timeout(Math.max(1, deadline - Date.now()))
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
function transcriptPath(turn, agents = { env: process.env, home: homedir() }) {
|
|
387
|
+
if ("transcriptPath" in turn) return Promise.resolve(turn.transcriptPath);
|
|
388
|
+
return findCodexRollout(codexHome(agents.env, agents.home), turn.codexThreadId);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/hook-process.ts
|
|
392
|
+
var MAX_INPUT_BYTES = 8 * 1024 * 1024;
|
|
393
|
+
async function runHookProcess(argument = process.argv[3]) {
|
|
394
|
+
setTimeout(() => process.exit(0), HOOK_TIMEOUT_MS + 500).unref();
|
|
395
|
+
const raw = argument ?? await readStdin(HOOK_TIMEOUT_MS / 2);
|
|
396
|
+
if (isCursorPayload(parseHookInput(raw))) process.stdout.write("{}\n");
|
|
397
|
+
await runHook({
|
|
398
|
+
readInput: async () => raw,
|
|
399
|
+
settings: resolveSettings(),
|
|
400
|
+
startRefill: () => startRefill()
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
function readStdin(timeoutMs) {
|
|
404
|
+
return new Promise((resolve) => {
|
|
405
|
+
const chunks = [];
|
|
406
|
+
let size = 0;
|
|
407
|
+
const finish = () => {
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
process.stdin.removeAllListeners();
|
|
410
|
+
process.stdin.pause();
|
|
411
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
412
|
+
};
|
|
413
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
414
|
+
process.stdin.on("data", (chunk) => {
|
|
415
|
+
size += chunk.length;
|
|
416
|
+
if (size > MAX_INPUT_BYTES) {
|
|
417
|
+
chunks.length = 0;
|
|
418
|
+
finish();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
chunks.push(chunk);
|
|
422
|
+
});
|
|
423
|
+
process.stdin.on("end", finish);
|
|
424
|
+
process.stdin.on("error", finish);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
export {
|
|
428
|
+
runHookProcess
|
|
429
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createRequire as __patronCreateRequire } from 'node:module'
|
|
2
|
+
const require = __patronCreateRequire(import.meta.url)
|
|
3
|
+
import {
|
|
4
|
+
statePaths
|
|
5
|
+
} from "./chunk-6TTNL3HT.js";
|
|
6
|
+
|
|
7
|
+
// src/wallet.ts
|
|
8
|
+
import { Store } from "accounts";
|
|
9
|
+
import { Provider as CliProvider, Storage } from "accounts/cli";
|
|
10
|
+
import { Mppx, tempo as mppxTempo } from "mppx/client";
|
|
11
|
+
import { toHex } from "viem";
|
|
12
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
13
|
+
import { tempo, tempoModerato } from "viem/chains";
|
|
14
|
+
|
|
15
|
+
// src/browser.ts
|
|
16
|
+
import { spawn } from "node:child_process";
|
|
17
|
+
async function openBrowserUrl(url) {
|
|
18
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
19
|
+
await new Promise((resolve, reject) => {
|
|
20
|
+
const child = spawn(command, args, {
|
|
21
|
+
detached: true,
|
|
22
|
+
stdio: "ignore"
|
|
23
|
+
});
|
|
24
|
+
child.once("error", reject);
|
|
25
|
+
child.once("spawn", () => {
|
|
26
|
+
child.unref();
|
|
27
|
+
resolve();
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/wallet.ts
|
|
33
|
+
var BUDGET_PERIOD_SECONDS = 30 * 24 * 60 * 60;
|
|
34
|
+
async function signIn(settings, options) {
|
|
35
|
+
if (settings.privateKey)
|
|
36
|
+
return { address: privateKeyToAccount(settings.privateKey).address, wallet: "key" };
|
|
37
|
+
const provider = tempoProvider(settings, options.issuer.chainId, options.output);
|
|
38
|
+
await Store.waitForHydration(provider.store);
|
|
39
|
+
const result = await provider.request({
|
|
40
|
+
method: "wallet_connect",
|
|
41
|
+
params: [
|
|
42
|
+
{
|
|
43
|
+
capabilities: {
|
|
44
|
+
authorizeAccessKey: {
|
|
45
|
+
expiry: 0,
|
|
46
|
+
limits: [budgetLimit(options.budgetUnits, options.issuer.currency)]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
]
|
|
51
|
+
});
|
|
52
|
+
const address = result.accounts[0]?.address;
|
|
53
|
+
if (!address) throw new Error("Tempo Wallet did not authorize Patron.");
|
|
54
|
+
return { address, wallet: "tempo" };
|
|
55
|
+
}
|
|
56
|
+
async function authorizeBudget(settings, options) {
|
|
57
|
+
if (settings.privateKey) return;
|
|
58
|
+
const provider = tempoProvider(settings, options.issuer.chainId, options.output);
|
|
59
|
+
await Store.waitForHydration(provider.store);
|
|
60
|
+
await provider.request({
|
|
61
|
+
method: "wallet_authorizeAccessKey",
|
|
62
|
+
params: [
|
|
63
|
+
{ expiry: 0, limits: [budgetLimit(options.budgetUnits, options.issuer.currency)] }
|
|
64
|
+
]
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function openWallet(settings, wallet, issuer, maxUnits, output = process.stderr) {
|
|
68
|
+
const policy = {
|
|
69
|
+
currencies: [issuer.currency],
|
|
70
|
+
decimals: 6,
|
|
71
|
+
expectedChainId: issuer.chainId,
|
|
72
|
+
maxAtomicAmount: maxUnits.toString()
|
|
73
|
+
};
|
|
74
|
+
if (wallet === "key") {
|
|
75
|
+
if (!settings.privateKey)
|
|
76
|
+
throw new Error(
|
|
77
|
+
"This Patron install pays with PATRON_PRIVATE_KEY, which is not set."
|
|
78
|
+
);
|
|
79
|
+
const account = privateKeyToAccount(settings.privateKey);
|
|
80
|
+
const payment2 = Mppx.create({
|
|
81
|
+
methods: [mppxTempo.charge({ account, ...policy })],
|
|
82
|
+
polyfill: false
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
address: account.address,
|
|
86
|
+
fetch: payment2.fetch,
|
|
87
|
+
signMessage: (message) => account.signMessage({ message })
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const provider = tempoProvider(settings, issuer.chainId, output);
|
|
91
|
+
await Store.waitForHydration(provider.store);
|
|
92
|
+
const [address] = await provider.request({ method: "eth_accounts" });
|
|
93
|
+
if (!address)
|
|
94
|
+
throw new Error(
|
|
95
|
+
"Tempo Wallet is signed out. Run npx @tempoxyz/patron to sign in again."
|
|
96
|
+
);
|
|
97
|
+
const accessKey = provider.store.getState().accessKeys.find(
|
|
98
|
+
(key) => key.access.toLowerCase() === address.toLowerCase() && key.chainId === issuer.chainId
|
|
99
|
+
);
|
|
100
|
+
const mppParameters = provider.getMppxParameters(
|
|
101
|
+
accessKey ? { accessKey: accessKey.address } : void 0
|
|
102
|
+
);
|
|
103
|
+
const payment = Mppx.create({
|
|
104
|
+
methods: [
|
|
105
|
+
mppxTempo.charge({
|
|
106
|
+
account: provider.getAccount(),
|
|
107
|
+
mode: "pull",
|
|
108
|
+
...policy,
|
|
109
|
+
...mppParameters
|
|
110
|
+
})
|
|
111
|
+
],
|
|
112
|
+
polyfill: false
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
address,
|
|
116
|
+
fetch: payment.fetch,
|
|
117
|
+
signMessage: (message) => provider.request({ method: "personal_sign", params: [toHex(message), address] })
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function budgetLimit(budgetUnits, currency) {
|
|
121
|
+
return {
|
|
122
|
+
limit: toHex(budgetUnits),
|
|
123
|
+
period: BUDGET_PERIOD_SECONDS,
|
|
124
|
+
token: currency
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function tempoProvider(settings, chainId, output) {
|
|
128
|
+
const chain = chainId === tempoModerato.id ? tempoModerato : tempo;
|
|
129
|
+
return CliProvider.create({
|
|
130
|
+
chains: [chain],
|
|
131
|
+
mpp: false,
|
|
132
|
+
name: "Patron",
|
|
133
|
+
open: async (url, prompt) => {
|
|
134
|
+
const code = prompt.userCode.replace(/^(.{4})(.{4})$/, "$1-$2");
|
|
135
|
+
output.write(
|
|
136
|
+
`
|
|
137
|
+
Tempo Wallet sign-in
|
|
138
|
+
Confirm code ${code} in your browser:
|
|
139
|
+
${url}
|
|
140
|
+
|
|
141
|
+
`
|
|
142
|
+
);
|
|
143
|
+
await openBrowserUrl(url).catch(() => void 0);
|
|
144
|
+
},
|
|
145
|
+
storage: Storage.filesystem({
|
|
146
|
+
key: "patron-tempo",
|
|
147
|
+
path: statePaths(settings.home).wallet
|
|
148
|
+
})
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
export {
|
|
152
|
+
authorizeBudget,
|
|
153
|
+
openWallet,
|
|
154
|
+
signIn
|
|
155
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@tempoxyz/patron",
|
|
3
|
+
"version": "0.0.10",
|
|
4
|
+
"description": "Pay the websites your AI agents read, privately",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"patron": "dist/bin.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://patron-web.tempo-dev.workers.dev",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"agent",
|
|
18
|
+
"amp",
|
|
19
|
+
"claude-code",
|
|
20
|
+
"codex",
|
|
21
|
+
"cursor",
|
|
22
|
+
"patron",
|
|
23
|
+
"privacy-pass",
|
|
24
|
+
"tempo"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "node scripts/build.mjs",
|
|
31
|
+
"check:types": "tsc --project tsconfig.json --noEmit",
|
|
32
|
+
"prepack": "pnpm build",
|
|
33
|
+
"test": "vitest run"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@patron/client": "workspace:*",
|
|
37
|
+
"@patron/protocol": "workspace:*",
|
|
38
|
+
"@types/node": "24.19.2",
|
|
39
|
+
"esbuild": "0.28.2",
|
|
40
|
+
"typescript": "5.9.3",
|
|
41
|
+
"vitest": "4.1.12"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"accounts": "0.21.1",
|
|
45
|
+
"mppx": "0.15.0",
|
|
46
|
+
"viem": "2.57.12"
|
|
47
|
+
}
|
|
48
|
+
}
|