@pushary/agent-hooks 0.22.0 → 0.23.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.
Files changed (82) hide show
  1. package/data/cursor-plugin/README.md +5 -1
  2. package/data/cursor-plugin/mcp.json +1 -1
  3. package/dist/bin/pushary-clean.js +1 -1
  4. package/dist/bin/pushary-doctor.js +2 -2
  5. package/dist/bin/pushary-setup.js +23 -1
  6. package/dist/{chunk-BHAMEPOP.js → chunk-JPRRYC5X.js} +5 -0
  7. package/package.json +1 -1
  8. package/dist/chunk-22CV7V7A.js +0 -38
  9. package/dist/chunk-2BE2IPMO.js +0 -315
  10. package/dist/chunk-2CRLBMOX.js +0 -244
  11. package/dist/chunk-2HMNOZPY.js +0 -109
  12. package/dist/chunk-2I6DLXJN.js +0 -219
  13. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  14. package/dist/chunk-3LC4YUMA.js +0 -194
  15. package/dist/chunk-3MIR7ODJ.js +0 -112
  16. package/dist/chunk-3QZESA66.js +0 -222
  17. package/dist/chunk-4Z4MB37G.js +0 -96
  18. package/dist/chunk-5GFUI5N6.js +0 -132
  19. package/dist/chunk-5JEDLXEC.js +0 -99
  20. package/dist/chunk-5LTQNC7R.js +0 -824
  21. package/dist/chunk-5QHQVXWN.js +0 -174
  22. package/dist/chunk-6A3WCJO2.js +0 -416
  23. package/dist/chunk-6QWFMVCD.js +0 -328
  24. package/dist/chunk-6SRXMZAN.js +0 -99
  25. package/dist/chunk-7PTU7TGE.js +0 -96
  26. package/dist/chunk-AB4KX4XT.js +0 -109
  27. package/dist/chunk-AC4UYAGX.js +0 -136
  28. package/dist/chunk-ACE77TKQ.js +0 -328
  29. package/dist/chunk-BYNYYZWW.js +0 -412
  30. package/dist/chunk-C5TFTNHG.js +0 -244
  31. package/dist/chunk-CH53PBQN.js +0 -265
  32. package/dist/chunk-DF3BM6BF.js +0 -195
  33. package/dist/chunk-DKZVKEOW.js +0 -175
  34. package/dist/chunk-EMPL27ZV.js +0 -96
  35. package/dist/chunk-EQJXMEIR.js +0 -175
  36. package/dist/chunk-FXYTRZHC.js +0 -177
  37. package/dist/chunk-GTJGZBTQ.js +0 -328
  38. package/dist/chunk-HJMFYDWY.js +0 -222
  39. package/dist/chunk-HRQEECB6.js +0 -315
  40. package/dist/chunk-HWEMAAOY.js +0 -370
  41. package/dist/chunk-IBWCHA5M.js +0 -10
  42. package/dist/chunk-KTM4ZQ3W.js +0 -96
  43. package/dist/chunk-KTP2EPVB.js +0 -27
  44. package/dist/chunk-KYARP7KP.js +0 -97
  45. package/dist/chunk-M2N5DYWN.js +0 -247
  46. package/dist/chunk-M5F2L4KF.js +0 -177
  47. package/dist/chunk-M6S3M6E3.js +0 -244
  48. package/dist/chunk-N7VXDBQU.js +0 -6
  49. package/dist/chunk-O6A5RHWY.js +0 -122
  50. package/dist/chunk-ODUXELPM.js +0 -219
  51. package/dist/chunk-OF5WIOYS.js +0 -129
  52. package/dist/chunk-OP4QAN23.js +0 -99
  53. package/dist/chunk-P4JH2Q7Z.js +0 -102
  54. package/dist/chunk-PMD5JSV3.js +0 -242
  55. package/dist/chunk-PSSHNBEL.js +0 -177
  56. package/dist/chunk-QEPRH7JB.js +0 -315
  57. package/dist/chunk-QRXWPZKN.js +0 -308
  58. package/dist/chunk-QY4L6XHN.js +0 -384
  59. package/dist/chunk-RNWPCELY.js +0 -176
  60. package/dist/chunk-RSHN2AQ7.js +0 -29
  61. package/dist/chunk-RZLVE57X.js +0 -38
  62. package/dist/chunk-SDCIKREA.js +0 -241
  63. package/dist/chunk-SDREQWNI.js +0 -175
  64. package/dist/chunk-SH26ZOHU.js +0 -159
  65. package/dist/chunk-TRLBBLSS.js +0 -176
  66. package/dist/chunk-U6OXZPYC.js +0 -384
  67. package/dist/chunk-UIBTFZUD.js +0 -314
  68. package/dist/chunk-USUCPCUC.js +0 -156
  69. package/dist/chunk-V4GLWPD7.js +0 -174
  70. package/dist/chunk-VC6U3QGF.js +0 -142
  71. package/dist/chunk-VIST7ACL.js +0 -88
  72. package/dist/chunk-VUNL35KE.js +0 -16
  73. package/dist/chunk-VWBNI4SC.js +0 -174
  74. package/dist/chunk-W5KRWUNE.js +0 -262
  75. package/dist/chunk-WCGKLHCL.js +0 -154
  76. package/dist/chunk-WNXGIEX7.js +0 -219
  77. package/dist/chunk-XPVSZIA3.js +0 -315
  78. package/dist/chunk-Y633ZIJF.js +0 -384
  79. package/dist/chunk-YCL4GUFR.js +0 -222
  80. package/dist/chunk-YTMKB44I.js +0 -220
  81. package/dist/chunk-ZWBS3T7Q.js +0 -244
  82. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
@@ -1,412 +0,0 @@
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
- if (files.length === 1) {
91
- return { tool: "Edit", input: { file_path: cwd ? resolve(cwd, files[0]) : files[0] } };
92
- }
93
- return { tool: "Edit", input: typeof command === "string" ? { file_path: command } : {} };
94
- };
95
- var permissionTimeoutDecision = (timeoutAction) => {
96
- if (timeoutAction === "approve") return codexAllow();
97
- if (timeoutAction === "deny") return codexDeny("No response within timeout");
98
- return codexPass();
99
- };
100
- var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
101
-
102
- // src/usage.ts
103
- import { closeSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "fs";
104
- import { join } from "path";
105
- import { tmpdir } from "os";
106
- var DEFAULT_PRICES = [
107
- { match: "opus-4-1", in: 15, out: 75 },
108
- { match: "opus-4-0", in: 15, out: 75 },
109
- { match: "3-opus", in: 15, out: 75 },
110
- { match: "opus", in: 5, out: 25 },
111
- { match: "haiku", in: 1, out: 5 },
112
- { match: "sonnet", in: 3, out: 15 }
113
- ];
114
- var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
115
- var CACHE_WRITE_MULTIPLIER = 1.25;
116
- var CACHE_READ_MULTIPLIER = 0.1;
117
- var RECENT_ID_LIMIT = 200;
118
- var READ_CHUNK_BYTES = 1024 * 1024;
119
- var isModelPrice = (value) => {
120
- if (!value || typeof value !== "object") return false;
121
- const candidate = value;
122
- return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
123
- };
124
- var priceTable = () => {
125
- const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
126
- if (!raw) return DEFAULT_PRICES;
127
- try {
128
- const parsed = JSON.parse(raw);
129
- if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
130
- } catch {
131
- }
132
- return DEFAULT_PRICES;
133
- };
134
- var estimateCostUsd = (usage, model) => {
135
- const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
136
- const perTokenIn = price.in / 1e6;
137
- const perTokenOut = price.out / 1e6;
138
- return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
139
- };
140
- var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join(tmpdir(), "pushary-usage");
141
- var stateFile = (sessionId) => join(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
142
- var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
143
- var readState = (path) => {
144
- try {
145
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
146
- if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
147
- return {
148
- offset: parsed.offset,
149
- tokensIn: parsed.tokensIn,
150
- tokensOut: parsed.tokensOut,
151
- costUsd: parsed.costUsd,
152
- recentIds: parsed.recentIds.filter((id) => typeof id === "string")
153
- };
154
- }
155
- } catch {
156
- }
157
- return emptyState();
158
- };
159
- var readRange = (path, start, end) => {
160
- const fd = openSync(path, "r");
161
- try {
162
- const chunks = [];
163
- let position = start;
164
- while (position < end) {
165
- const length = Math.min(READ_CHUNK_BYTES, end - position);
166
- const buffer = Buffer.alloc(length);
167
- const bytesRead = readSync(fd, buffer, 0, length, position);
168
- if (bytesRead <= 0) break;
169
- chunks.push(buffer.subarray(0, bytesRead));
170
- position += bytesRead;
171
- }
172
- return Buffer.concat(chunks);
173
- } finally {
174
- closeSync(fd);
175
- }
176
- };
177
- var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
178
- var applyLine = (state, line) => {
179
- let parsed;
180
- try {
181
- parsed = JSON.parse(line);
182
- } catch {
183
- return 0;
184
- }
185
- if (parsed.type !== "assistant") return 0;
186
- const usage = parsed.message?.usage;
187
- if (!usage || typeof usage !== "object") return 0;
188
- const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
189
- if (model.includes("<synthetic>")) return 0;
190
- const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
191
- if (id) {
192
- if (state.recentIds.includes(id)) return 0;
193
- state.recentIds.push(id);
194
- if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
195
- }
196
- const messageUsage = {
197
- inputTokens: toCount(usage.input_tokens),
198
- outputTokens: toCount(usage.output_tokens),
199
- cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
200
- cacheReadTokens: toCount(usage.cache_read_input_tokens)
201
- };
202
- const cost = estimateCostUsd(messageUsage, model);
203
- state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
204
- state.tokensOut += messageUsage.outputTokens;
205
- state.costUsd += cost;
206
- return cost;
207
- };
208
- var readNewUsage = (transcriptPath, sessionId) => {
209
- try {
210
- const size = statSync(transcriptPath).size;
211
- const path = stateFile(sessionId);
212
- let state = readState(path);
213
- if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
214
- let deltaUsd = 0;
215
- if (size > state.offset) {
216
- const buffer = readRange(transcriptPath, state.offset, size);
217
- const lastNewline = buffer.lastIndexOf(10);
218
- if (lastNewline >= 0) {
219
- const complete = buffer.subarray(0, lastNewline + 1);
220
- for (const line of complete.toString("utf-8").split("\n")) {
221
- if (line.trim()) deltaUsd += applyLine(state, line);
222
- }
223
- state.offset += lastNewline + 1;
224
- }
225
- }
226
- mkdirSync(stateDir(), { recursive: true });
227
- writeFileSync(path, JSON.stringify(state), "utf-8");
228
- if (state.tokensIn === 0 && state.tokensOut === 0) return null;
229
- return {
230
- tokensIn: state.tokensIn,
231
- tokensOut: state.tokensOut,
232
- costUsd: state.costUsd,
233
- deltaUsd
234
- };
235
- } catch {
236
- return null;
237
- }
238
- };
239
-
240
- // src/events.ts
241
- import { basename, join as join2 } from "path";
242
- import { createHash } from "crypto";
243
- import { existsSync, readFileSync as readFileSync2 } from "fs";
244
- import { tmpdir as tmpdir2 } from "os";
245
- var cleanupPendingQuestions = async (sessionId) => {
246
- try {
247
- const files = listPendingQuestions(sessionId);
248
- const apiKey = getApiKey();
249
- for (const correlationId of files) {
250
- try {
251
- await cancelQuestion(apiKey, correlationId);
252
- } catch {
253
- }
254
- removePendingQuestion(sessionId, correlationId);
255
- }
256
- if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
257
- } catch {
258
- }
259
- };
260
- var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
261
- var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
262
- var readFreshCachedPolicy = (apiKey) => {
263
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
264
- const path = join2(tmpdir2(), `pushary-policy-${hash}.json`);
265
- if (!existsSync(path)) return null;
266
- const cached = JSON.parse(readFileSync2(path, "utf-8"));
267
- if (!isPolicyConfig(cached)) return null;
268
- if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
269
- return cached;
270
- };
271
- var deriveDecisionSource = (toolName, toolInput, liveMode) => {
272
- try {
273
- if (liveMode.kill) return "terminal";
274
- const policy = readFreshCachedPolicy(getApiKey());
275
- if (!policy) return void 0;
276
- const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
277
- if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
278
- if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
279
- return "terminal";
280
- } catch {
281
- return void 0;
282
- }
283
- };
284
- var deriveUsage = (transcriptPath, sessionId) => {
285
- if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
286
- try {
287
- return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
288
- } catch {
289
- return void 0;
290
- }
291
- };
292
- var reportEvent = async (event, options = {}) => {
293
- const apiKey = getApiKey();
294
- const baseUrl = getBaseUrl();
295
- return withRetry(async () => {
296
- const res = await fetch(`${baseUrl}/api/agent/event`, {
297
- method: "POST",
298
- headers: {
299
- "Content-Type": "application/json",
300
- "Authorization": `Bearer ${apiKey}`
301
- },
302
- body: JSON.stringify({
303
- ...event,
304
- machineId: event.machineId ?? getMachineId()
305
- }),
306
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
307
- });
308
- try {
309
- return await res.json();
310
- } catch {
311
- return null;
312
- }
313
- }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
314
- };
315
- var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
316
- try {
317
- const projectName = basename(input.cwd ?? process.cwd());
318
- const action = describeToolCall(input.tool_name, input.tool_input, "event");
319
- const lookup = toPolicyLookup(input.tool_name, input.tool_input);
320
- const isError = isToolResultError(input.tool_result);
321
- const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
322
- const liveMode = await fetchModeState(getApiKey(), input.session_id);
323
- await Promise.allSettled([
324
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
325
- reportEvent({
326
- event: isError ? "tool_error" : "tool_complete",
327
- agentType: agent.type,
328
- agentName: `${agent.label} - ${projectName}`,
329
- action,
330
- sessionId: input.session_id,
331
- error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
332
- decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
333
- meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
334
- usage: deriveUsage(input.transcript_path, input.session_id)
335
- })
336
- ]);
337
- } catch {
338
- }
339
- };
340
- var TASK_TITLE_MAX_LENGTH = 120;
341
- var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
342
- try {
343
- const projectName = basename(input.cwd ?? process.cwd());
344
- const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
345
- const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
346
- await reportEvent({
347
- event: "user_prompt",
348
- agentType: agent.type,
349
- agentName: `${agent.label} - ${projectName}`,
350
- sessionId: input.session_id,
351
- taskTitle
352
- }, { maxAttempts: 1, timeoutMs: 800 });
353
- } catch {
354
- }
355
- };
356
- var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
357
- try {
358
- const projectName = basename(input.cwd ?? process.cwd());
359
- const [, reported] = await Promise.allSettled([
360
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
361
- reportEvent({
362
- event: "session_end",
363
- agentType: agent.type,
364
- agentName: `${agent.label} - ${projectName}`,
365
- action: "Session ended",
366
- sessionId: input.session_id,
367
- usage: deriveUsage(input.transcript_path, input.session_id)
368
- })
369
- ]);
370
- const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
371
- if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
372
- return {
373
- decision: "block",
374
- reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
375
- };
376
- }
377
- return void 0;
378
- } catch {
379
- return void 0;
380
- }
381
- };
382
- var handleNotification = async (input) => {
383
- try {
384
- const projectName = basename(input.cwd ?? process.cwd());
385
- await reportEvent({
386
- event: input.type === "error" ? "error" : "notification",
387
- agentType: "claude_code",
388
- agentName: `Claude Code - ${projectName}`,
389
- action: input.title ?? input.message ?? "Notification",
390
- sessionId: input.session_id,
391
- error: input.type === "error" ? input.message : void 0
392
- });
393
- } catch {
394
- }
395
- };
396
-
397
- export {
398
- CODEX_AGENT,
399
- codexAllow,
400
- codexDeny,
401
- codexPass,
402
- toCodexWire,
403
- describeApplyPatch,
404
- toPolicyLookup,
405
- permissionTimeoutDecision,
406
- preToolUseTimeoutDecision,
407
- reportEvent,
408
- handlePostToolUse,
409
- handleUserPrompt,
410
- handleStop,
411
- handleNotification
412
- };
@@ -1,244 +0,0 @@
1
- import {
2
- askUser,
3
- describeToolCall,
4
- isPolicyConfig,
5
- savePendingQuestion,
6
- sendNotification,
7
- waitForAnswer
8
- } from "./chunk-EMPL27ZV.js";
9
- import {
10
- withRetry
11
- } from "./chunk-3MIR7ODJ.js";
12
- import {
13
- getApiKey,
14
- getBaseUrl
15
- } from "./chunk-VUNL35KE.js";
16
-
17
- // src/policy.ts
18
- import { createHash } from "crypto";
19
- import { existsSync, readFileSync, writeFileSync } from "fs";
20
- import { join } from "path";
21
- import { tmpdir } from "os";
22
- var CACHE_TTL_MS = 5 * 60 * 1e3;
23
- var cacheFile = (apiKey) => {
24
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
25
- return join(tmpdir(), `pushary-policy-${hash}.json`);
26
- };
27
- var fetchPolicy = async (apiKey) => {
28
- return withRetry(async () => {
29
- const baseUrl = getBaseUrl();
30
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
31
- headers: { "Authorization": `Bearer ${apiKey}` },
32
- signal: AbortSignal.timeout(1e4)
33
- });
34
- if (!response.ok) {
35
- throw new Error(`Failed to fetch policy: ${response.status}`);
36
- }
37
- const raw = await response.json();
38
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
39
- return raw;
40
- }, { maxAttempts: 2 });
41
- };
42
- var getPolicy = async (apiKey) => {
43
- const path = cacheFile(apiKey);
44
- let staleCache = null;
45
- if (existsSync(path)) {
46
- try {
47
- const stat = readFileSync(path, "utf-8");
48
- const cached = JSON.parse(stat);
49
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
50
- if (!cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS) {
51
- return cached;
52
- }
53
- staleCache = cached;
54
- } catch {
55
- }
56
- }
57
- try {
58
- const policy = await fetchPolicy(apiKey);
59
- try {
60
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now() }), "utf-8");
61
- } catch {
62
- }
63
- return policy;
64
- } catch {
65
- if (staleCache) return staleCache;
66
- throw new Error("Failed to fetch policy and no cached policy available");
67
- }
68
- };
69
- var resolvePolicy = (config, toolName, modeOverride) => {
70
- const base = config.policies.find((p) => p.tool === toolName) ?? config.policies.find((p) => p.tool === "*") ?? {
71
- tool: toolName,
72
- timeoutSeconds: config.defaultTimeoutSeconds,
73
- timeoutAction: config.defaultTimeoutAction,
74
- mode: config.defaultMode ?? "push_first",
75
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
76
- };
77
- const effectiveOverride = modeOverride ?? config.modeOverride;
78
- if (effectiveOverride) {
79
- return { ...base, mode: effectiveOverride };
80
- }
81
- return base;
82
- };
83
- var fetchModeOverride = async (apiKey) => {
84
- try {
85
- const baseUrl = getBaseUrl();
86
- const response = await fetch(`${baseUrl}/api/mcp/mode`, {
87
- headers: { "Authorization": `Bearer ${apiKey}` },
88
- signal: AbortSignal.timeout(3e3)
89
- });
90
- if (!response.ok) return null;
91
- const data = await response.json();
92
- const mode = data.override?.mode;
93
- if (mode && ["push_only", "terminal_only", "push_first", "notify_only"].includes(mode)) {
94
- return mode;
95
- }
96
- return null;
97
- } catch {
98
- return null;
99
- }
100
- };
101
-
102
- // src/hook.ts
103
- import { basename } from "path";
104
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
105
- var allow = () => ({
106
- hookSpecificOutput: {
107
- hookEventName: "PreToolUse",
108
- permissionDecision: "allow"
109
- }
110
- });
111
- var deny = (reason) => ({
112
- hookSpecificOutput: {
113
- hookEventName: "PreToolUse",
114
- permissionDecision: "deny",
115
- permissionDecisionReason: reason
116
- }
117
- });
118
- var ask = (reason) => ({
119
- hookSpecificOutput: {
120
- hookEventName: "PreToolUse",
121
- permissionDecision: "ask",
122
- ...reason ? { permissionDecisionReason: reason } : {}
123
- }
124
- });
125
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
126
- while (Date.now() < deadlineMs) {
127
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
128
- let answer;
129
- try {
130
- answer = await waitForAnswer(apiKey, correlationId, remaining);
131
- } catch {
132
- if (Date.now() + pollInterval >= deadlineMs) break;
133
- await sleep(pollInterval);
134
- continue;
135
- }
136
- if (answer.answered) return answer;
137
- if (Date.now() + pollInterval >= deadlineMs) break;
138
- await sleep(pollInterval);
139
- }
140
- return { answered: false };
141
- };
142
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction) => {
143
- let result;
144
- try {
145
- result = await askUser(apiKey, {
146
- question: `Allow ${description}?`,
147
- type: "confirm",
148
- context: `Agent wants to run this in ${projectName}`,
149
- agentName: `Claude Code - ${projectName}`
150
- });
151
- } catch {
152
- switch (timeoutAction) {
153
- case "approve":
154
- return allow();
155
- case "deny":
156
- return deny("Push notification failed, denying per policy");
157
- default:
158
- return ask("Push notification failed, asking in terminal");
159
- }
160
- }
161
- const deadline = Date.now() + timeoutSeconds * 1e3;
162
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
163
- if (answer.answered) {
164
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
165
- }
166
- switch (timeoutAction) {
167
- case "approve":
168
- return allow();
169
- case "deny":
170
- return deny("No response within timeout");
171
- default:
172
- return ask("No push response, asking in terminal");
173
- }
174
- };
175
- var handleTerminalOnly = () => {
176
- return ask();
177
- };
178
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds) => {
179
- let result;
180
- try {
181
- result = await askUser(apiKey, {
182
- question: `Allow ${description}?`,
183
- type: "confirm",
184
- context: `Agent wants to run this in ${projectName}`,
185
- agentName: `Claude Code - ${projectName}`
186
- });
187
- } catch {
188
- return ask("Push notification failed, asking in terminal");
189
- }
190
- const deadline = Date.now() + pushFirstSeconds * 1e3;
191
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
192
- if (answer.answered) {
193
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
194
- }
195
- savePendingQuestion(result.correlationId);
196
- return ask("Sent as push notification. You can also approve here.");
197
- };
198
- var handleNotifyOnly = async (apiKey, description, projectName) => {
199
- try {
200
- await sendNotification(apiKey, {
201
- title: "Agent needs approval",
202
- body: description,
203
- agentName: `Claude Code - ${projectName}`
204
- });
205
- } catch {
206
- }
207
- return ask();
208
- };
209
- var handlePreToolUse = async (input) => {
210
- try {
211
- const apiKey = getApiKey();
212
- const [policy, modeOverride] = await Promise.all([
213
- getPolicy(apiKey),
214
- fetchModeOverride(apiKey)
215
- ]);
216
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeOverride);
217
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
218
- return allow();
219
- }
220
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
221
- const projectName = basename(input.cwd ?? process.cwd());
222
- switch (toolPolicy.mode) {
223
- case "push_only":
224
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction);
225
- case "terminal_only":
226
- return handleTerminalOnly();
227
- case "push_first":
228
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
229
- case "notify_only":
230
- return handleNotifyOnly(apiKey, description, projectName);
231
- default:
232
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
233
- }
234
- } catch {
235
- return ask("Pushary unavailable, falling back to terminal approval");
236
- }
237
- };
238
-
239
- export {
240
- getPolicy,
241
- resolvePolicy,
242
- fetchModeOverride,
243
- handlePreToolUse
244
- };