@pushary/agent-hooks 0.28.1 → 0.28.2

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