@pushary/agent-hooks 0.21.0 → 0.21.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,416 @@
1
+ import {
2
+ DEFAULT_SESSION,
3
+ cancelQuestion,
4
+ deriveReceiptMeta,
5
+ describeToolCall,
6
+ fetchModeState,
7
+ getMachineId,
8
+ isDefaultSession,
9
+ isPolicyConfig,
10
+ isToolResultError,
11
+ listPendingQuestions,
12
+ removePendingQuestion,
13
+ removePendingSession,
14
+ resolvePolicy
15
+ } from "./chunk-6QWFMVCD.js";
16
+ import {
17
+ withRetry
18
+ } from "./chunk-DWED7BS3.js";
19
+ import {
20
+ getApiKey,
21
+ getBaseUrl
22
+ } from "./chunk-NKXSILEW.js";
23
+
24
+ // src/codex-adapter.ts
25
+ import { resolve } from "path";
26
+ var CODEX_AGENT = { type: "codex", label: "Codex" };
27
+ var codexAllow = () => ({ kind: "allow" });
28
+ var codexDeny = (reason) => ({ kind: "deny", reason });
29
+ var codexPass = () => ({ kind: "pass" });
30
+ var toCodexWire = (event, decision) => {
31
+ if (event === "PermissionRequest") {
32
+ if (decision.kind === "allow") {
33
+ return {
34
+ hookSpecificOutput: {
35
+ hookEventName: "PermissionRequest",
36
+ decision: { behavior: "allow" }
37
+ }
38
+ };
39
+ }
40
+ if (decision.kind === "deny") {
41
+ return {
42
+ hookSpecificOutput: {
43
+ hookEventName: "PermissionRequest",
44
+ decision: { behavior: "deny", message: decision.reason }
45
+ }
46
+ };
47
+ }
48
+ return null;
49
+ }
50
+ if (event === "PreToolUse" && decision.kind === "deny") {
51
+ return {
52
+ hookSpecificOutput: {
53
+ hookEventName: "PreToolUse",
54
+ permissionDecision: "deny",
55
+ permissionDecisionReason: decision.reason
56
+ }
57
+ };
58
+ }
59
+ return null;
60
+ };
61
+ var parseApplyPatchOps = (command) => {
62
+ if (typeof command !== "string") return [];
63
+ const ops = [];
64
+ for (const line of command.split("\n")) {
65
+ const file = line.match(/^\*\*\*\s+(Add|Update|Delete) File:\s+(.+?)\s*$/);
66
+ if (file) {
67
+ ops.push({ op: file[1].toLowerCase(), path: file[2] });
68
+ continue;
69
+ }
70
+ const move = line.match(/^\*\*\*\s+Move to:\s+(.+?)\s*$/);
71
+ if (move) ops.push({ op: "move", path: move[1] });
72
+ }
73
+ return ops;
74
+ };
75
+ var parseApplyPatchFiles = (command) => [...new Set(parseApplyPatchOps(command).map((entry) => entry.path))];
76
+ var describeApplyPatch = (command) => {
77
+ const ops = parseApplyPatchOps(command);
78
+ if (ops.length === 0) return null;
79
+ const files = [...new Set(ops.map((entry) => entry.path))];
80
+ if (files.length === 1) {
81
+ const verb = ops[0].op === "add" ? "create" : ops[0].op === "delete" ? "delete" : ops[0].op === "move" ? "move" : "edit";
82
+ return `${verb} file: ${files[0]}`;
83
+ }
84
+ return `apply patch to ${files.length} files`;
85
+ };
86
+ var toPolicyLookup = (toolName, toolInput, cwd) => {
87
+ if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
88
+ const command = toolInput.command;
89
+ const files = parseApplyPatchFiles(command);
90
+ let filePath;
91
+ if (files.length === 1) {
92
+ filePath = files[0];
93
+ } else if (files.length === 0 && typeof command === "string" && command.trim() && !command.includes("\n") && !command.includes("***")) {
94
+ filePath = command.trim();
95
+ }
96
+ const resolved = filePath && cwd ? resolve(cwd, filePath) : filePath;
97
+ return { tool: "Edit", input: resolved ? { file_path: resolved } : {} };
98
+ };
99
+ var permissionTimeoutDecision = (timeoutAction) => {
100
+ if (timeoutAction === "approve") return codexAllow();
101
+ if (timeoutAction === "deny") return codexDeny("No response within timeout");
102
+ return codexPass();
103
+ };
104
+ var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
105
+
106
+ // src/usage.ts
107
+ import { closeSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "fs";
108
+ import { join } from "path";
109
+ import { tmpdir } from "os";
110
+ var DEFAULT_PRICES = [
111
+ { match: "opus-4-1", in: 15, out: 75 },
112
+ { match: "opus-4-0", in: 15, out: 75 },
113
+ { match: "3-opus", in: 15, out: 75 },
114
+ { match: "opus", in: 5, out: 25 },
115
+ { match: "haiku", in: 1, out: 5 },
116
+ { match: "sonnet", in: 3, out: 15 }
117
+ ];
118
+ var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
119
+ var CACHE_WRITE_MULTIPLIER = 1.25;
120
+ var CACHE_READ_MULTIPLIER = 0.1;
121
+ var RECENT_ID_LIMIT = 200;
122
+ var READ_CHUNK_BYTES = 1024 * 1024;
123
+ var isModelPrice = (value) => {
124
+ if (!value || typeof value !== "object") return false;
125
+ const candidate = value;
126
+ return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
127
+ };
128
+ var priceTable = () => {
129
+ const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
130
+ if (!raw) return DEFAULT_PRICES;
131
+ try {
132
+ const parsed = JSON.parse(raw);
133
+ if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
134
+ } catch {
135
+ }
136
+ return DEFAULT_PRICES;
137
+ };
138
+ var estimateCostUsd = (usage, model) => {
139
+ const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
140
+ const perTokenIn = price.in / 1e6;
141
+ const perTokenOut = price.out / 1e6;
142
+ return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
143
+ };
144
+ var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join(tmpdir(), "pushary-usage");
145
+ var stateFile = (sessionId) => join(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
146
+ var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
147
+ var readState = (path) => {
148
+ try {
149
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
150
+ if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
151
+ return {
152
+ offset: parsed.offset,
153
+ tokensIn: parsed.tokensIn,
154
+ tokensOut: parsed.tokensOut,
155
+ costUsd: parsed.costUsd,
156
+ recentIds: parsed.recentIds.filter((id) => typeof id === "string")
157
+ };
158
+ }
159
+ } catch {
160
+ }
161
+ return emptyState();
162
+ };
163
+ var readRange = (path, start, end) => {
164
+ const fd = openSync(path, "r");
165
+ try {
166
+ const chunks = [];
167
+ let position = start;
168
+ while (position < end) {
169
+ const length = Math.min(READ_CHUNK_BYTES, end - position);
170
+ const buffer = Buffer.alloc(length);
171
+ const bytesRead = readSync(fd, buffer, 0, length, position);
172
+ if (bytesRead <= 0) break;
173
+ chunks.push(buffer.subarray(0, bytesRead));
174
+ position += bytesRead;
175
+ }
176
+ return Buffer.concat(chunks);
177
+ } finally {
178
+ closeSync(fd);
179
+ }
180
+ };
181
+ var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
182
+ var applyLine = (state, line) => {
183
+ let parsed;
184
+ try {
185
+ parsed = JSON.parse(line);
186
+ } catch {
187
+ return 0;
188
+ }
189
+ if (parsed.type !== "assistant") return 0;
190
+ const usage = parsed.message?.usage;
191
+ if (!usage || typeof usage !== "object") return 0;
192
+ const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
193
+ if (model.includes("<synthetic>")) return 0;
194
+ const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
195
+ if (id) {
196
+ if (state.recentIds.includes(id)) return 0;
197
+ state.recentIds.push(id);
198
+ if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
199
+ }
200
+ const messageUsage = {
201
+ inputTokens: toCount(usage.input_tokens),
202
+ outputTokens: toCount(usage.output_tokens),
203
+ cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
204
+ cacheReadTokens: toCount(usage.cache_read_input_tokens)
205
+ };
206
+ const cost = estimateCostUsd(messageUsage, model);
207
+ state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
208
+ state.tokensOut += messageUsage.outputTokens;
209
+ state.costUsd += cost;
210
+ return cost;
211
+ };
212
+ var readNewUsage = (transcriptPath, sessionId) => {
213
+ try {
214
+ const size = statSync(transcriptPath).size;
215
+ const path = stateFile(sessionId);
216
+ let state = readState(path);
217
+ if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
218
+ let deltaUsd = 0;
219
+ if (size > state.offset) {
220
+ const buffer = readRange(transcriptPath, state.offset, size);
221
+ const lastNewline = buffer.lastIndexOf(10);
222
+ if (lastNewline >= 0) {
223
+ const complete = buffer.subarray(0, lastNewline + 1);
224
+ for (const line of complete.toString("utf-8").split("\n")) {
225
+ if (line.trim()) deltaUsd += applyLine(state, line);
226
+ }
227
+ state.offset += lastNewline + 1;
228
+ }
229
+ }
230
+ mkdirSync(stateDir(), { recursive: true });
231
+ writeFileSync(path, JSON.stringify(state), "utf-8");
232
+ if (state.tokensIn === 0 && state.tokensOut === 0) return null;
233
+ return {
234
+ tokensIn: state.tokensIn,
235
+ tokensOut: state.tokensOut,
236
+ costUsd: state.costUsd,
237
+ deltaUsd
238
+ };
239
+ } catch {
240
+ return null;
241
+ }
242
+ };
243
+
244
+ // src/events.ts
245
+ import { basename, join as join2 } from "path";
246
+ import { createHash } from "crypto";
247
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
248
+ import { tmpdir as tmpdir2 } from "os";
249
+ var cleanupPendingQuestions = async (sessionId) => {
250
+ try {
251
+ const files = listPendingQuestions(sessionId);
252
+ const apiKey = getApiKey();
253
+ for (const correlationId of files) {
254
+ try {
255
+ await cancelQuestion(apiKey, correlationId);
256
+ } catch {
257
+ }
258
+ removePendingQuestion(sessionId, correlationId);
259
+ }
260
+ if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
261
+ } catch {
262
+ }
263
+ };
264
+ var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
265
+ var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
266
+ var readFreshCachedPolicy = (apiKey) => {
267
+ const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
268
+ const path = join2(tmpdir2(), `pushary-policy-${hash}.json`);
269
+ if (!existsSync(path)) return null;
270
+ const cached = JSON.parse(readFileSync2(path, "utf-8"));
271
+ if (!isPolicyConfig(cached)) return null;
272
+ if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
273
+ return cached;
274
+ };
275
+ var deriveDecisionSource = (toolName, toolInput, liveMode) => {
276
+ try {
277
+ if (liveMode.kill) return "terminal";
278
+ const policy = readFreshCachedPolicy(getApiKey());
279
+ if (!policy) return void 0;
280
+ const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
281
+ if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
282
+ if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
283
+ return "terminal";
284
+ } catch {
285
+ return void 0;
286
+ }
287
+ };
288
+ var deriveUsage = (transcriptPath, sessionId) => {
289
+ if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
290
+ try {
291
+ return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
292
+ } catch {
293
+ return void 0;
294
+ }
295
+ };
296
+ var reportEvent = async (event, options = {}) => {
297
+ const apiKey = getApiKey();
298
+ const baseUrl = getBaseUrl();
299
+ return withRetry(async () => {
300
+ const res = await fetch(`${baseUrl}/api/agent/event`, {
301
+ method: "POST",
302
+ headers: {
303
+ "Content-Type": "application/json",
304
+ "Authorization": `Bearer ${apiKey}`
305
+ },
306
+ body: JSON.stringify({
307
+ ...event,
308
+ machineId: event.machineId ?? getMachineId()
309
+ }),
310
+ signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
311
+ });
312
+ try {
313
+ return await res.json();
314
+ } catch {
315
+ return null;
316
+ }
317
+ }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
318
+ };
319
+ var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
320
+ try {
321
+ const projectName = basename(input.cwd ?? process.cwd());
322
+ const action = describeToolCall(input.tool_name, input.tool_input, "event");
323
+ const lookup = toPolicyLookup(input.tool_name, input.tool_input);
324
+ const isError = isToolResultError(input.tool_result);
325
+ const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
326
+ const liveMode = await fetchModeState(getApiKey(), input.session_id);
327
+ await Promise.allSettled([
328
+ cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
329
+ reportEvent({
330
+ event: isError ? "tool_error" : "tool_complete",
331
+ agentType: agent.type,
332
+ agentName: `${agent.label} - ${projectName}`,
333
+ action,
334
+ sessionId: input.session_id,
335
+ error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
336
+ decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
337
+ meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
338
+ usage: deriveUsage(input.transcript_path, input.session_id)
339
+ })
340
+ ]);
341
+ } catch {
342
+ }
343
+ };
344
+ var TASK_TITLE_MAX_LENGTH = 120;
345
+ var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
346
+ try {
347
+ const projectName = basename(input.cwd ?? process.cwd());
348
+ const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
349
+ const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
350
+ await reportEvent({
351
+ event: "user_prompt",
352
+ agentType: agent.type,
353
+ agentName: `${agent.label} - ${projectName}`,
354
+ sessionId: input.session_id,
355
+ taskTitle
356
+ }, { maxAttempts: 1, timeoutMs: 800 });
357
+ } catch {
358
+ }
359
+ };
360
+ var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
361
+ try {
362
+ const projectName = basename(input.cwd ?? process.cwd());
363
+ const [, reported] = await Promise.allSettled([
364
+ cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
365
+ reportEvent({
366
+ event: "session_end",
367
+ agentType: agent.type,
368
+ agentName: `${agent.label} - ${projectName}`,
369
+ action: "Session ended",
370
+ sessionId: input.session_id,
371
+ usage: deriveUsage(input.transcript_path, input.session_id)
372
+ })
373
+ ]);
374
+ const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
375
+ if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
376
+ return {
377
+ decision: "block",
378
+ reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
379
+ };
380
+ }
381
+ return void 0;
382
+ } catch {
383
+ return void 0;
384
+ }
385
+ };
386
+ var handleNotification = async (input) => {
387
+ try {
388
+ const projectName = basename(input.cwd ?? process.cwd());
389
+ await reportEvent({
390
+ event: input.type === "error" ? "error" : "notification",
391
+ agentType: "claude_code",
392
+ agentName: `Claude Code - ${projectName}`,
393
+ action: input.title ?? input.message ?? "Notification",
394
+ sessionId: input.session_id,
395
+ error: input.type === "error" ? input.message : void 0
396
+ });
397
+ } catch {
398
+ }
399
+ };
400
+
401
+ export {
402
+ CODEX_AGENT,
403
+ codexAllow,
404
+ codexDeny,
405
+ codexPass,
406
+ toCodexWire,
407
+ describeApplyPatch,
408
+ toPolicyLookup,
409
+ permissionTimeoutDecision,
410
+ preToolUseTimeoutDecision,
411
+ reportEvent,
412
+ handlePostToolUse,
413
+ handleUserPrompt,
414
+ handleStop,
415
+ handleNotification
416
+ };