@pushary/agent-hooks 0.24.0 → 0.26.0

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.
@@ -1,824 +0,0 @@
1
- import {
2
- ACTION_BODY_MAX,
3
- DECISION_LINE_MAX,
4
- extractPolicyArg,
5
- isApprovalMode,
6
- isSafeReadOnlyCommand,
7
- matchRankWeight,
8
- matchToolPattern
9
- } from "./chunk-WPVL6VIT.js";
10
- import {
11
- callMcpTool,
12
- withRetry
13
- } from "./chunk-DWED7BS3.js";
14
- import {
15
- getApiKey,
16
- getBaseUrl
17
- } from "./chunk-NKXSILEW.js";
18
-
19
- // src/validate.ts
20
- var isPolicyConfig = (data) => {
21
- if (!data || typeof data !== "object") return false;
22
- const d = data;
23
- return Array.isArray(d.policies) && typeof d.defaultTimeoutSeconds === "number" && typeof d.defaultTimeoutAction === "string";
24
- };
25
- var isAskUserResponse = (data) => {
26
- if (!data || typeof data !== "object") return false;
27
- const d = data;
28
- return typeof d.correlationId === "string" && typeof d.status === "string";
29
- };
30
- var isWaitForAnswerResponse = (data) => {
31
- if (!data || typeof data !== "object") return false;
32
- const d = data;
33
- return typeof d.answered === "boolean";
34
- };
35
-
36
- // src/api.ts
37
- var askUser = async (apiKey, params, timeoutMs = 15e3) => {
38
- const result = await callMcpTool(apiKey, "ask_user", { ...params, wait: false }, { maxRetries: 3, timeoutMs });
39
- if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
40
- return result;
41
- };
42
- var waitForAnswer = async (apiKey, correlationId, timeoutMs = 3e4) => {
43
- const result = await callMcpTool(apiKey, "wait_for_answer", {
44
- correlationId,
45
- timeoutMs
46
- }, { timeoutMs: timeoutMs + 1e4 });
47
- if (!isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
48
- return result;
49
- };
50
- var cancelQuestion = async (apiKey, correlationId) => {
51
- await callMcpTool(apiKey, "cancel_question", { correlationId });
52
- };
53
- var sendNotification = async (apiKey, params, timeoutMs = 15e3) => {
54
- await callMcpTool(apiKey, "send_notification", { ...params }, { maxRetries: 3, timeoutMs });
55
- };
56
-
57
- // src/policy.ts
58
- import { createHash } from "crypto";
59
- import { existsSync, readFileSync, writeFileSync } from "fs";
60
- import { join } from "path";
61
- import { tmpdir } from "os";
62
- var CACHE_TTL_MS = 60 * 1e3;
63
- var cacheFile = (apiKey) => {
64
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
65
- return join(tmpdir(), `pushary-policy-${hash}.json`);
66
- };
67
- var fetchPolicy = async (apiKey) => {
68
- return withRetry(async () => {
69
- const baseUrl = getBaseUrl();
70
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
71
- headers: { "Authorization": `Bearer ${apiKey}` },
72
- signal: AbortSignal.timeout(1e4)
73
- });
74
- if (!response.ok) {
75
- throw new Error(`Failed to fetch policy: ${response.status}`);
76
- }
77
- const raw = await response.json();
78
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
79
- return raw;
80
- }, { maxAttempts: 2 });
81
- };
82
- var getPolicy = async (apiKey, expectedVersion) => {
83
- const path = cacheFile(apiKey);
84
- let staleCache = null;
85
- if (existsSync(path)) {
86
- try {
87
- const stat = readFileSync(path, "utf-8");
88
- const cached = JSON.parse(stat);
89
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
90
- const versionStale = expectedVersion != null && (cached._policyVersion ?? null) !== expectedVersion;
91
- const ttlFresh = !cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS;
92
- if (ttlFresh && !versionStale) {
93
- return cached;
94
- }
95
- staleCache = cached;
96
- } catch {
97
- }
98
- }
99
- try {
100
- const policy = await fetchPolicy(apiKey);
101
- try {
102
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now(), _policyVersion: expectedVersion ?? null }), "utf-8");
103
- } catch {
104
- }
105
- return policy;
106
- } catch {
107
- if (staleCache) return staleCache;
108
- throw new Error("Failed to fetch policy and no cached policy available");
109
- }
110
- };
111
- var findBestMatch = (policies, toolName, arg) => {
112
- let best;
113
- let bestWeight = 0;
114
- let bestLength = -1;
115
- for (const candidate of policies) {
116
- const rank = matchToolPattern(candidate.tool, toolName, arg);
117
- if (rank === "none") continue;
118
- const weight = matchRankWeight(rank);
119
- const length = rank === "prefix" ? candidate.tool.length : -1;
120
- if (weight > bestWeight || weight === bestWeight && length > bestLength) {
121
- best = { policy: candidate, rank };
122
- bestWeight = weight;
123
- bestLength = length;
124
- }
125
- }
126
- return best;
127
- };
128
- var autoApprove = (tool) => ({
129
- tool,
130
- timeoutSeconds: 0,
131
- timeoutAction: "approve",
132
- mode: "terminal_only",
133
- pushFirstSeconds: 0
134
- });
135
- var resolvePolicy = (config, toolName, modeOverride, toolInput) => {
136
- const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
137
- const match = findBestMatch(config.policies, toolName, arg);
138
- let base = match?.policy ?? config.policies.find((p) => p.tool === "*") ?? {
139
- tool: toolName,
140
- timeoutSeconds: config.defaultTimeoutSeconds,
141
- timeoutAction: config.defaultTimeoutAction,
142
- mode: config.defaultMode ?? "push_first",
143
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
144
- };
145
- const governedBySpecificRule = match?.rank === "exact" || match?.rank === "prefix";
146
- if (!governedBySpecificRule && toolName === "Bash" && typeof arg === "string" && isSafeReadOnlyCommand(arg)) {
147
- base = autoApprove(base.tool);
148
- }
149
- const effectiveOverride = modeOverride ?? config.modeOverride;
150
- if (effectiveOverride) {
151
- return { ...base, mode: effectiveOverride };
152
- }
153
- return base;
154
- };
155
- var toPolicyVersion = (value) => typeof value === "string" || typeof value === "number" ? String(value) : null;
156
- var fetchModeState = async (apiKey, sessionId) => {
157
- try {
158
- const baseUrl = getBaseUrl();
159
- const url = sessionId ? `${baseUrl}/api/mcp/mode?session=${encodeURIComponent(sessionId)}` : `${baseUrl}/api/mcp/mode`;
160
- const response = await fetch(url, {
161
- headers: { "Authorization": `Bearer ${apiKey}` },
162
- signal: AbortSignal.timeout(3e3)
163
- });
164
- if (!response.ok) return { mode: null, kill: false, policyVersion: null };
165
- const data = await response.json();
166
- const mode = data.override?.mode;
167
- return {
168
- mode: isApprovalMode(mode) ? mode : null,
169
- kill: data.kill === true,
170
- policyVersion: toPolicyVersion(data.policyVersion)
171
- };
172
- } catch {
173
- return { mode: null, kill: false, policyVersion: null };
174
- }
175
- };
176
- var fetchModeOverride = async (apiKey) => (await fetchModeState(apiKey)).mode;
177
-
178
- // src/describe.ts
179
- import { isAbsolute, relative } from "path";
180
- var hookPrefixes = {
181
- Bash: (input) => `bash: ${input.command ?? "(no command)"}`,
182
- Write: (input) => `write file: ${input.file_path ?? "(unknown path)"}`,
183
- Edit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
184
- Read: (input) => `read file: ${input.file_path ?? "(unknown path)"}`
185
- };
186
- var eventPrefixes = {
187
- Bash: (input) => `ran: ${String(input.command ?? "").slice(0, 120)}`,
188
- Write: (input) => `wrote: ${input.file_path ?? "unknown"}`,
189
- Edit: (input) => `edited: ${input.file_path ?? "unknown"}`,
190
- Read: (input) => `read: ${input.file_path ?? "unknown"}`
191
- };
192
- var describeToolCall = (toolName, toolInput, format = "hook") => {
193
- const prefixes = format === "hook" ? hookPrefixes : eventPrefixes;
194
- const builder = prefixes[toolName];
195
- if (builder) return builder(toolInput);
196
- return format === "hook" ? `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}` : `${toolName}: done`;
197
- };
198
- var TOOL_TARGET_MAX_LENGTH = 80;
199
- var deriveCommandHead = (command) => {
200
- if (typeof command !== "string") return void 0;
201
- const head = command.trim().split(/\s+/).slice(0, 2).join(" ");
202
- return head ? head.slice(0, TOOL_TARGET_MAX_LENGTH) : void 0;
203
- };
204
- var deriveToolTarget = (toolName, toolInput) => {
205
- if (toolName === "Bash") {
206
- return deriveCommandHead(toolInput.command);
207
- }
208
- if (toolName === "Edit" || toolName === "Write") {
209
- const filePath = toolInput.file_path;
210
- if (typeof filePath !== "string") return void 0;
211
- const separator = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
212
- const base = filePath.slice(separator + 1);
213
- const dot = base.lastIndexOf(".");
214
- if (dot <= 0) return void 0;
215
- return base.slice(dot).slice(0, TOOL_TARGET_MAX_LENGTH);
216
- }
217
- return void 0;
218
- };
219
- var RECEIPT_TARGET_MAX_LENGTH = 256;
220
- var isToolResultError = (toolResult) => {
221
- try {
222
- return Boolean(toolResult && ("error" in toolResult || "is_error" in toolResult));
223
- } catch {
224
- return false;
225
- }
226
- };
227
- var relativizeReceiptPath = (filePath, cwd) => {
228
- if (!cwd || !isAbsolute(filePath)) return filePath;
229
- return relative(cwd, filePath);
230
- };
231
- var deriveReceiptMeta = (toolName, toolInput, toolResult, cwd) => {
232
- try {
233
- const ok = !isToolResultError(toolResult);
234
- if (toolName === "Edit" || toolName === "Write") {
235
- const filePath = toolInput.file_path;
236
- if (typeof filePath !== "string" || !filePath) return void 0;
237
- return {
238
- kind: toolName === "Edit" ? "edit" : "write",
239
- target: relativizeReceiptPath(filePath, cwd).slice(0, RECEIPT_TARGET_MAX_LENGTH),
240
- ok
241
- };
242
- }
243
- if (toolName === "Bash") {
244
- const head = deriveCommandHead(toolInput.command);
245
- if (!head) return void 0;
246
- return {
247
- kind: head === "git commit" ? "commit" : "bash",
248
- target: head,
249
- ok
250
- };
251
- }
252
- return void 0;
253
- } catch {
254
- return void 0;
255
- }
256
- };
257
- var firstString = (...values) => values.find((v) => typeof v === "string" && v.length > 0);
258
- var REDACTION_RULES = [
259
- { pattern: /\bsk-[A-Za-z0-9]{20,}\b/g, replacement: "[redacted]" },
260
- { pattern: /\bpk_(?:live|test)_[A-Za-z0-9]+\b/g, replacement: "[redacted]" },
261
- { pattern: /\brk_[A-Za-z0-9]+\b/g, replacement: "[redacted]" },
262
- { pattern: /\bAKIA[0-9A-Z]{16}\b/g, replacement: "[redacted]" },
263
- { pattern: /\bbearer\s+[A-Za-z0-9._-]+/gi, replacement: "bearer [redacted]" },
264
- { pattern: /\bauthorization:\s*\S+/gi, replacement: "authorization: [redacted]" },
265
- {
266
- pattern: /((?:secret|token|password|passwd|api[_-]?key|private[_-]?key)\s*[=:]\s*)(\S+)/gi,
267
- replacement: "$1[redacted]"
268
- },
269
- { pattern: /[A-Za-z0-9+/]{40,}={0,2}/g, replacement: "[redacted]" }
270
- ];
271
- var redactSecrets = (text) => REDACTION_RULES.reduce((acc, rule) => acc.replace(rule.pattern, rule.replacement), text);
272
- var ACTION_BODY_TRUNCATION_MARKER = "\n\u2026 [truncated]";
273
- var capActionBody = (text) => text.length <= ACTION_BODY_MAX ? text : `${text.slice(0, ACTION_BODY_MAX - ACTION_BODY_TRUNCATION_MARKER.length)}${ACTION_BODY_TRUNCATION_MARKER}`;
274
- var rawActionBody = (toolName, toolInput) => {
275
- if (toolName === "Edit" || toolName === "replace") {
276
- const before = firstString(toolInput.old_string);
277
- const after = firstString(toolInput.new_string);
278
- if (before === void 0 && after === void 0) return void 0;
279
- return `- ${before ?? ""}
280
- + ${after ?? ""}`;
281
- }
282
- if (toolName === "Write" || toolName === "write_file") return firstString(toolInput.content);
283
- if (toolName === "Bash" || toolName === "run_shell_command" || toolName === "shell" || toolName === "apply_patch") {
284
- return firstString(toolInput.command);
285
- }
286
- return void 0;
287
- };
288
- var deriveActionBody = (toolName, toolInput) => {
289
- try {
290
- const raw = rawActionBody(toolName, toolInput);
291
- if (!raw) return void 0;
292
- return capActionBody(redactSecrets(raw));
293
- } catch {
294
- return void 0;
295
- }
296
- };
297
- var deriveAction = (toolName, toolInput) => describeToolCall(toolName, toolInput, "hook").slice(0, DECISION_LINE_MAX);
298
- var BLOCKER_BY_MODE = {
299
- push_only: "Approval required before this runs",
300
- push_first: "Paused for your approval before continuing",
301
- escalate: "Escalated to you after the approval timeout"
302
- };
303
- var deriveBlocker = (mode, reason) => {
304
- const text = reason?.replace(/\s+/g, " ").trim() || BLOCKER_BY_MODE[mode] || "Waiting for your approval";
305
- return text.slice(0, DECISION_LINE_MAX);
306
- };
307
-
308
- // src/identity.ts
309
- import { createHash as createHash2 } from "crypto";
310
- import { hostname } from "os";
311
- var deriveMachineId = (host) => createHash2("sha256").update(host).digest("hex").slice(0, 8);
312
- var getMachineId = () => deriveMachineId(hostname());
313
-
314
- // src/pending.ts
315
- import { join as join2 } from "path";
316
- import { tmpdir as tmpdir2 } from "os";
317
- import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2, readdirSync, unlinkSync, rmSync, statSync } from "fs";
318
- var PENDING_DIR = join2(tmpdir2(), "pushary-pending");
319
- var DEFAULT_SESSION = "_no_session";
320
- var GRACE_MS = 10 * 60 * 1e3;
321
- var sanitize = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
322
- var dirFor = (sessionId) => join2(PENDING_DIR, sanitize(sessionId));
323
- var isDefaultSession = (sessionId) => sanitize(sessionId) === DEFAULT_SESSION;
324
- var savePendingQuestion = (sessionId, correlationId) => {
325
- const dir = dirFor(sessionId);
326
- if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
327
- writeFileSync2(join2(dir, correlationId), "", "utf-8");
328
- };
329
- var listPendingQuestions = (sessionId) => {
330
- const dir = dirFor(sessionId);
331
- let files;
332
- try {
333
- files = readdirSync(dir);
334
- } catch {
335
- return [];
336
- }
337
- if (!isDefaultSession(sessionId)) return files;
338
- const cutoff = Date.now() - GRACE_MS;
339
- return files.filter((name) => {
340
- try {
341
- return statSync(join2(dir, name)).mtimeMs < cutoff;
342
- } catch {
343
- return false;
344
- }
345
- });
346
- };
347
- var removePendingQuestion = (sessionId, correlationId) => {
348
- try {
349
- unlinkSync(join2(dirFor(sessionId), correlationId));
350
- } catch {
351
- }
352
- };
353
- var removePendingSession = (sessionId) => {
354
- try {
355
- rmSync(dirFor(sessionId), { recursive: true, force: true });
356
- } catch {
357
- }
358
- };
359
-
360
- // src/usage.ts
361
- import { closeSync, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync2, readSync, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
362
- import { join as join3 } from "path";
363
- import { tmpdir as tmpdir3 } from "os";
364
- var DEFAULT_PRICES = [
365
- { match: "opus-4-1", in: 15, out: 75 },
366
- { match: "opus-4-0", in: 15, out: 75 },
367
- { match: "3-opus", in: 15, out: 75 },
368
- { match: "opus", in: 5, out: 25 },
369
- { match: "haiku", in: 1, out: 5 },
370
- { match: "sonnet", in: 3, out: 15 }
371
- ];
372
- var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
373
- var CACHE_WRITE_MULTIPLIER = 1.25;
374
- var CACHE_READ_MULTIPLIER = 0.1;
375
- var RECENT_ID_LIMIT = 200;
376
- var READ_CHUNK_BYTES = 1024 * 1024;
377
- var isModelPrice = (value) => {
378
- if (!value || typeof value !== "object") return false;
379
- const candidate = value;
380
- return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
381
- };
382
- var priceTable = () => {
383
- const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
384
- if (!raw) return DEFAULT_PRICES;
385
- try {
386
- const parsed = JSON.parse(raw);
387
- if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
388
- } catch {
389
- }
390
- return DEFAULT_PRICES;
391
- };
392
- var estimateCostUsd = (usage, model) => {
393
- const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
394
- const perTokenIn = price.in / 1e6;
395
- const perTokenOut = price.out / 1e6;
396
- return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
397
- };
398
- var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join3(tmpdir3(), "pushary-usage");
399
- var stateFile = (sessionId) => join3(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
400
- var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
401
- var readState = (path) => {
402
- try {
403
- const parsed = JSON.parse(readFileSync2(path, "utf-8"));
404
- if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
405
- return {
406
- offset: parsed.offset,
407
- tokensIn: parsed.tokensIn,
408
- tokensOut: parsed.tokensOut,
409
- costUsd: parsed.costUsd,
410
- recentIds: parsed.recentIds.filter((id) => typeof id === "string")
411
- };
412
- }
413
- } catch {
414
- }
415
- return emptyState();
416
- };
417
- var readRange = (path, start, end) => {
418
- const fd = openSync(path, "r");
419
- try {
420
- const chunks = [];
421
- let position = start;
422
- while (position < end) {
423
- const length = Math.min(READ_CHUNK_BYTES, end - position);
424
- const buffer = Buffer.alloc(length);
425
- const bytesRead = readSync(fd, buffer, 0, length, position);
426
- if (bytesRead <= 0) break;
427
- chunks.push(buffer.subarray(0, bytesRead));
428
- position += bytesRead;
429
- }
430
- return Buffer.concat(chunks);
431
- } finally {
432
- closeSync(fd);
433
- }
434
- };
435
- var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
436
- var applyLine = (state, line) => {
437
- let parsed;
438
- try {
439
- parsed = JSON.parse(line);
440
- } catch {
441
- return 0;
442
- }
443
- if (parsed.type !== "assistant") return 0;
444
- const usage = parsed.message?.usage;
445
- if (!usage || typeof usage !== "object") return 0;
446
- const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
447
- if (model.includes("<synthetic>")) return 0;
448
- const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
449
- if (id) {
450
- if (state.recentIds.includes(id)) return 0;
451
- state.recentIds.push(id);
452
- if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
453
- }
454
- const messageUsage = {
455
- inputTokens: toCount(usage.input_tokens),
456
- outputTokens: toCount(usage.output_tokens),
457
- cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
458
- cacheReadTokens: toCount(usage.cache_read_input_tokens)
459
- };
460
- const cost = estimateCostUsd(messageUsage, model);
461
- state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
462
- state.tokensOut += messageUsage.outputTokens;
463
- state.costUsd += cost;
464
- return cost;
465
- };
466
- var USER_PROMPT_TAIL_BYTES = 256 * 1024;
467
- var USER_PROMPT_MAX = 2048;
468
- var extractUserText = (content) => {
469
- if (typeof content === "string") return content.replace(/\s+/g, " ").trim() || void 0;
470
- if (Array.isArray(content)) {
471
- const text = content.filter((block) => Boolean(block) && typeof block === "object").filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ").replace(/\s+/g, " ").trim();
472
- return text || void 0;
473
- }
474
- return void 0;
475
- };
476
- var readLastUserPrompt = (transcriptPath) => {
477
- try {
478
- const size = statSync2(transcriptPath).size;
479
- const start = Math.max(0, size - USER_PROMPT_TAIL_BYTES);
480
- const lines = readRange(transcriptPath, start, size).toString("utf-8").split("\n");
481
- for (let i = lines.length - 1; i >= 0; i -= 1) {
482
- const line = lines[i].trim();
483
- if (!line) continue;
484
- let parsed;
485
- try {
486
- parsed = JSON.parse(line);
487
- } catch {
488
- continue;
489
- }
490
- if (parsed.type !== "user") continue;
491
- const text = extractUserText(parsed.message?.content);
492
- if (text) return text.slice(0, USER_PROMPT_MAX);
493
- }
494
- return void 0;
495
- } catch {
496
- return void 0;
497
- }
498
- };
499
- var readNewUsage = (transcriptPath, sessionId) => {
500
- try {
501
- const size = statSync2(transcriptPath).size;
502
- const path = stateFile(sessionId);
503
- let state = readState(path);
504
- if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
505
- let deltaUsd = 0;
506
- if (size > state.offset) {
507
- const buffer = readRange(transcriptPath, state.offset, size);
508
- const lastNewline = buffer.lastIndexOf(10);
509
- if (lastNewline >= 0) {
510
- const complete = buffer.subarray(0, lastNewline + 1);
511
- for (const line of complete.toString("utf-8").split("\n")) {
512
- if (line.trim()) deltaUsd += applyLine(state, line);
513
- }
514
- state.offset += lastNewline + 1;
515
- }
516
- }
517
- mkdirSync2(stateDir(), { recursive: true });
518
- writeFileSync3(path, JSON.stringify(state), "utf-8");
519
- if (state.tokensIn === 0 && state.tokensOut === 0) return null;
520
- return {
521
- tokensIn: state.tokensIn,
522
- tokensOut: state.tokensOut,
523
- costUsd: state.costUsd,
524
- deltaUsd
525
- };
526
- } catch {
527
- return null;
528
- }
529
- };
530
-
531
- // src/codex-adapter.ts
532
- import { resolve } from "path";
533
- var CODEX_AGENT = { type: "codex", label: "Codex" };
534
- var codexAllow = () => ({ kind: "allow" });
535
- var codexDeny = (reason) => ({ kind: "deny", reason });
536
- var codexPass = () => ({ kind: "pass" });
537
- var toCodexWire = (event, decision) => {
538
- if (event === "PermissionRequest") {
539
- if (decision.kind === "allow") {
540
- return {
541
- hookSpecificOutput: {
542
- hookEventName: "PermissionRequest",
543
- decision: { behavior: "allow" }
544
- }
545
- };
546
- }
547
- if (decision.kind === "deny") {
548
- return {
549
- hookSpecificOutput: {
550
- hookEventName: "PermissionRequest",
551
- decision: { behavior: "deny", message: decision.reason }
552
- }
553
- };
554
- }
555
- return null;
556
- }
557
- if (event === "PreToolUse" && decision.kind === "deny") {
558
- return {
559
- hookSpecificOutput: {
560
- hookEventName: "PreToolUse",
561
- permissionDecision: "deny",
562
- permissionDecisionReason: decision.reason
563
- }
564
- };
565
- }
566
- return null;
567
- };
568
- var parseApplyPatchOps = (command) => {
569
- if (typeof command !== "string") return [];
570
- const ops = [];
571
- for (const line of command.split("\n")) {
572
- const file = line.match(/^\*\*\*\s+(Add|Update|Delete) File:\s+(.+?)\s*$/);
573
- if (file) {
574
- ops.push({ op: file[1].toLowerCase(), path: file[2] });
575
- continue;
576
- }
577
- const move = line.match(/^\*\*\*\s+Move to:\s+(.+?)\s*$/);
578
- if (move) ops.push({ op: "move", path: move[1] });
579
- }
580
- return ops;
581
- };
582
- var parseApplyPatchFiles = (command) => [...new Set(parseApplyPatchOps(command).map((entry) => entry.path))];
583
- var describeApplyPatch = (command) => {
584
- const ops = parseApplyPatchOps(command);
585
- if (ops.length === 0) return null;
586
- const files = [...new Set(ops.map((entry) => entry.path))];
587
- if (files.length === 1) {
588
- const verb = ops[0].op === "add" ? "create" : ops[0].op === "delete" ? "delete" : ops[0].op === "move" ? "move" : "edit";
589
- return `${verb} file: ${files[0]}`;
590
- }
591
- return `apply patch to ${files.length} files`;
592
- };
593
- var toPolicyLookup = (toolName, toolInput, cwd) => {
594
- if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
595
- const command = toolInput.command;
596
- const files = parseApplyPatchFiles(command);
597
- if (files.length === 1) {
598
- return { tool: "Edit", input: { file_path: cwd ? resolve(cwd, files[0]) : files[0] } };
599
- }
600
- return { tool: "Edit", input: typeof command === "string" ? { file_path: command } : {} };
601
- };
602
- var permissionTimeoutDecision = (timeoutAction) => {
603
- if (timeoutAction === "approve") return codexAllow();
604
- if (timeoutAction === "deny") return codexDeny("No response within timeout");
605
- return codexPass();
606
- };
607
- var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
608
-
609
- // src/events.ts
610
- import { basename, join as join4 } from "path";
611
- import { createHash as createHash3 } from "crypto";
612
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "fs";
613
- import { tmpdir as tmpdir4 } from "os";
614
- var INTENT_DIR = join4(tmpdir4(), "pushary-intent");
615
- var INTENT_MAX_BYTES = 2048;
616
- var INTENT_GRACE_MS = 10 * 60 * 1e3;
617
- var sanitizeSession = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
618
- var intentFile = (sessionId) => join4(INTENT_DIR, sanitizeSession(sessionId));
619
- var saveLastPrompt = (sessionId, prompt) => {
620
- try {
621
- const trimmed = prompt.replace(/\s+/g, " ").trim().slice(0, INTENT_MAX_BYTES);
622
- if (!trimmed) return;
623
- mkdirSync3(INTENT_DIR, { recursive: true });
624
- writeFileSync4(intentFile(sessionId), trimmed, "utf-8");
625
- } catch {
626
- }
627
- };
628
- var readLastPrompt = (sessionId) => {
629
- try {
630
- const path = intentFile(sessionId);
631
- if (isDefaultSession(sessionId) && statSync3(path).mtimeMs < Date.now() - INTENT_GRACE_MS) return void 0;
632
- const value = readFileSync3(path, "utf-8").trim();
633
- return value.length > 0 ? value : void 0;
634
- } catch {
635
- return void 0;
636
- }
637
- };
638
- var cleanupPendingQuestions = async (sessionId) => {
639
- try {
640
- const files = listPendingQuestions(sessionId);
641
- const apiKey = getApiKey();
642
- for (const correlationId of files) {
643
- try {
644
- await cancelQuestion(apiKey, correlationId);
645
- } catch {
646
- }
647
- removePendingQuestion(sessionId, correlationId);
648
- }
649
- if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
650
- } catch {
651
- }
652
- };
653
- var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
654
- var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
655
- var readFreshCachedPolicy = (apiKey) => {
656
- const hash = createHash3("sha256").update(apiKey).digest("hex").slice(0, 12);
657
- const path = join4(tmpdir4(), `pushary-policy-${hash}.json`);
658
- if (!existsSync3(path)) return null;
659
- const cached = JSON.parse(readFileSync3(path, "utf-8"));
660
- if (!isPolicyConfig(cached)) return null;
661
- if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
662
- return cached;
663
- };
664
- var deriveDecisionSource = (toolName, toolInput, liveMode) => {
665
- try {
666
- if (liveMode.kill) return "terminal";
667
- const policy = readFreshCachedPolicy(getApiKey());
668
- if (!policy) return void 0;
669
- const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
670
- if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
671
- if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
672
- return "terminal";
673
- } catch {
674
- return void 0;
675
- }
676
- };
677
- var deriveUsage = (transcriptPath, sessionId) => {
678
- if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
679
- try {
680
- return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
681
- } catch {
682
- return void 0;
683
- }
684
- };
685
- var reportEvent = async (event, options = {}) => {
686
- const apiKey = getApiKey();
687
- const baseUrl = getBaseUrl();
688
- return withRetry(async () => {
689
- const res = await fetch(`${baseUrl}/api/agent/event`, {
690
- method: "POST",
691
- headers: {
692
- "Content-Type": "application/json",
693
- "Authorization": `Bearer ${apiKey}`
694
- },
695
- body: JSON.stringify({
696
- ...event,
697
- machineId: event.machineId ?? getMachineId()
698
- }),
699
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
700
- });
701
- try {
702
- return await res.json();
703
- } catch {
704
- return null;
705
- }
706
- }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
707
- };
708
- var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
709
- try {
710
- const projectName = basename(input.cwd ?? process.cwd());
711
- const action = describeToolCall(input.tool_name, input.tool_input, "event");
712
- const lookup = toPolicyLookup(input.tool_name, input.tool_input);
713
- const isError = isToolResultError(input.tool_result);
714
- const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
715
- const liveMode = await fetchModeState(getApiKey(), input.session_id);
716
- await Promise.allSettled([
717
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
718
- reportEvent({
719
- event: isError ? "tool_error" : "tool_complete",
720
- agentType: agent.type,
721
- agentName: `${agent.label} - ${projectName}`,
722
- action,
723
- sessionId: input.session_id,
724
- error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
725
- decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
726
- meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
727
- usage: deriveUsage(input.transcript_path, input.session_id)
728
- })
729
- ]);
730
- } catch {
731
- }
732
- };
733
- var TASK_TITLE_MAX_LENGTH = 120;
734
- var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
735
- try {
736
- const projectName = basename(input.cwd ?? process.cwd());
737
- const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
738
- const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
739
- if (input.prompt) saveLastPrompt(input.session_id || DEFAULT_SESSION, input.prompt);
740
- await reportEvent({
741
- event: "user_prompt",
742
- agentType: agent.type,
743
- agentName: `${agent.label} - ${projectName}`,
744
- sessionId: input.session_id,
745
- taskTitle
746
- }, { maxAttempts: 1, timeoutMs: 800 });
747
- } catch {
748
- }
749
- };
750
- var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
751
- try {
752
- const projectName = basename(input.cwd ?? process.cwd());
753
- const [, reported] = await Promise.allSettled([
754
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
755
- reportEvent({
756
- event: "session_end",
757
- agentType: agent.type,
758
- agentName: `${agent.label} - ${projectName}`,
759
- action: "Session ended",
760
- sessionId: input.session_id,
761
- usage: deriveUsage(input.transcript_path, input.session_id)
762
- })
763
- ]);
764
- const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
765
- if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
766
- return {
767
- decision: "block",
768
- reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
769
- };
770
- }
771
- return void 0;
772
- } catch {
773
- return void 0;
774
- }
775
- };
776
- var handleNotification = async (input) => {
777
- try {
778
- const projectName = basename(input.cwd ?? process.cwd());
779
- await reportEvent({
780
- event: input.type === "error" ? "error" : "notification",
781
- agentType: "claude_code",
782
- agentName: `Claude Code - ${projectName}`,
783
- action: input.title ?? input.message ?? "Notification",
784
- sessionId: input.session_id,
785
- error: input.type === "error" ? input.message : void 0
786
- });
787
- } catch {
788
- }
789
- };
790
-
791
- export {
792
- askUser,
793
- waitForAnswer,
794
- cancelQuestion,
795
- sendNotification,
796
- getPolicy,
797
- resolvePolicy,
798
- fetchModeState,
799
- fetchModeOverride,
800
- describeToolCall,
801
- deriveToolTarget,
802
- deriveActionBody,
803
- deriveAction,
804
- deriveBlocker,
805
- getMachineId,
806
- DEFAULT_SESSION,
807
- savePendingQuestion,
808
- readLastUserPrompt,
809
- CODEX_AGENT,
810
- codexAllow,
811
- codexDeny,
812
- codexPass,
813
- toCodexWire,
814
- describeApplyPatch,
815
- toPolicyLookup,
816
- permissionTimeoutDecision,
817
- preToolUseTimeoutDecision,
818
- readLastPrompt,
819
- reportEvent,
820
- handlePostToolUse,
821
- handleUserPrompt,
822
- handleStop,
823
- handleNotification
824
- };