@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,176 +0,0 @@
1
- import {
2
- DEFAULT_SESSION,
3
- askUser,
4
- deriveToolTarget,
5
- describeToolCall,
6
- fetchModeState,
7
- getMachineId,
8
- getPolicy,
9
- resolvePolicy,
10
- savePendingQuestion,
11
- sendNotification,
12
- waitForAnswer
13
- } from "./chunk-CH53PBQN.js";
14
- import {
15
- getApiKey
16
- } from "./chunk-VUNL35KE.js";
17
-
18
- // src/hook.ts
19
- import { basename } from "path";
20
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
- var allow = () => ({
22
- hookSpecificOutput: {
23
- hookEventName: "PreToolUse",
24
- permissionDecision: "allow"
25
- }
26
- });
27
- var deny = (reason) => ({
28
- hookSpecificOutput: {
29
- hookEventName: "PreToolUse",
30
- permissionDecision: "deny",
31
- permissionDecisionReason: reason
32
- }
33
- });
34
- var ask = (reason) => ({
35
- hookSpecificOutput: {
36
- hookEventName: "PreToolUse",
37
- permissionDecision: "ask",
38
- ...reason ? { permissionDecisionReason: reason } : {}
39
- }
40
- });
41
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
42
- while (Date.now() < deadlineMs) {
43
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
44
- let answer;
45
- try {
46
- answer = await waitForAnswer(apiKey, correlationId, remaining);
47
- } catch {
48
- if (Date.now() + pollInterval >= deadlineMs) break;
49
- await sleep(pollInterval);
50
- continue;
51
- }
52
- if (answer.answered) return answer;
53
- if (Date.now() + pollInterval >= deadlineMs) break;
54
- await sleep(pollInterval);
55
- }
56
- return { answered: false };
57
- };
58
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
59
- let result;
60
- try {
61
- result = await askUser(apiKey, {
62
- question: `Allow ${description}?`,
63
- type: "confirm",
64
- context: `Agent wants to run this in ${projectName}`,
65
- agentName: `Claude Code - ${projectName}`,
66
- sessionId,
67
- machineId,
68
- toolName,
69
- toolTarget
70
- });
71
- } catch {
72
- switch (timeoutAction) {
73
- case "approve":
74
- return allow();
75
- case "deny":
76
- return deny("Push notification failed, denying per policy");
77
- default:
78
- return ask("Push notification failed, asking in terminal");
79
- }
80
- }
81
- const deadline = Date.now() + timeoutSeconds * 1e3;
82
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
83
- if (answer.answered) {
84
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
85
- }
86
- switch (timeoutAction) {
87
- case "approve":
88
- return allow();
89
- case "deny":
90
- return deny("No response within timeout");
91
- default:
92
- return ask("No push response, asking in terminal");
93
- }
94
- };
95
- var handleTerminalOnly = () => {
96
- return ask();
97
- };
98
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
99
- let result;
100
- try {
101
- result = await askUser(apiKey, {
102
- question: `Allow ${description}?`,
103
- type: "confirm",
104
- context: `Agent wants to run this in ${projectName}`,
105
- agentName: `Claude Code - ${projectName}`,
106
- sessionId,
107
- machineId,
108
- toolName,
109
- toolTarget
110
- });
111
- } catch {
112
- return ask("Push notification failed, asking in terminal");
113
- }
114
- const deadline = Date.now() + pushFirstSeconds * 1e3;
115
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
116
- if (answer.answered) {
117
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
118
- }
119
- savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
120
- return ask("Sent as push notification. You can also approve here.");
121
- };
122
- var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
123
- try {
124
- await sendNotification(apiKey, {
125
- title: "Agent needs approval",
126
- body: description,
127
- agentName: `Claude Code - ${projectName}`,
128
- sessionId,
129
- machineId
130
- });
131
- } catch {
132
- }
133
- return ask();
134
- };
135
- var handlePreToolUse = async (input) => {
136
- try {
137
- const apiKey = getApiKey();
138
- const [policy, modeState] = await Promise.all([
139
- getPolicy(apiKey),
140
- fetchModeState(apiKey, input.session_id)
141
- ]);
142
- if (modeState.kill) {
143
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
144
- }
145
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
146
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
147
- return allow();
148
- }
149
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
150
- return deny(`Denied by policy for ${toolPolicy.tool}`);
151
- }
152
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
153
- const projectName = basename(input.cwd ?? process.cwd());
154
- const sessionId = input.session_id;
155
- const machineId = getMachineId();
156
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
157
- switch (toolPolicy.mode) {
158
- case "push_only":
159
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
160
- case "terminal_only":
161
- return handleTerminalOnly();
162
- case "push_first":
163
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
164
- case "notify_only":
165
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
166
- default:
167
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
168
- }
169
- } catch {
170
- return ask("Pushary unavailable, falling back to terminal approval");
171
- }
172
- };
173
-
174
- export {
175
- handlePreToolUse
176
- };
@@ -1,29 +0,0 @@
1
- // src/npm.ts
2
- import { execSync } from "child_process";
3
- var cleanNpmEnv = () => {
4
- const env = {};
5
- for (const [key, value] of Object.entries(process.env)) {
6
- if (key.toLowerCase().startsWith("npm_config_workspace")) continue;
7
- env[key] = value;
8
- }
9
- return env;
10
- };
11
- var npmErrorMessage = (err) => {
12
- const e = err;
13
- const text = [e?.stderr, e?.stdout].map((part) => part ? part.toString() : "").join("\n");
14
- const line = text.split("\n").map((l) => l.replace(/^npm error\s*/i, "").trim()).find((l) => l && !l.startsWith("A complete log") && !/^code\s/i.test(l));
15
- return line || e?.message || String(err);
16
- };
17
- var execNpm = (args, options = {}) => {
18
- return execSync(`npm ${args}`, {
19
- timeout: 12e4,
20
- stdio: "pipe",
21
- ...options,
22
- env: { ...cleanNpmEnv(), ...options.env ?? {} }
23
- });
24
- };
25
-
26
- export {
27
- npmErrorMessage,
28
- execNpm
29
- };
@@ -1,38 +0,0 @@
1
- // ../contracts/src/index.ts
2
- var APPROVAL_MODES = ["push_only", "terminal_only", "push_first", "notify_only"];
3
- var isApprovalMode = (value) => typeof value === "string" && APPROVAL_MODES.includes(value);
4
- var MATCH_RANKS = ["none", "tool", "prefix", "exact"];
5
- var matchRankWeight = (rank) => MATCH_RANKS.indexOf(rank);
6
- var matchToolPattern = (pattern, toolName, arg) => {
7
- const open = pattern.indexOf("(");
8
- if (open === -1 || !pattern.endsWith(")")) {
9
- return pattern === toolName ? "tool" : "none";
10
- }
11
- if (pattern.slice(0, open) !== toolName || arg === void 0) return "none";
12
- const inner = pattern.slice(open + 1, -1);
13
- if (inner.endsWith(":*")) {
14
- return arg.startsWith(inner.slice(0, -2)) ? "prefix" : "none";
15
- }
16
- return arg === inner ? "exact" : "none";
17
- };
18
- var POLICY_ARG_KEYS = {
19
- Bash: "command",
20
- Edit: "file_path",
21
- Write: "file_path"
22
- };
23
- var extractPolicyArg = (toolName, toolInput) => {
24
- const key = POLICY_ARG_KEYS[toolName];
25
- if (!key) return void 0;
26
- const value = toolInput[key];
27
- return typeof value === "string" ? value : void 0;
28
- };
29
- var API_KEY_PATTERN = /^pk_[a-f0-9]+\.[a-f0-9]+$/;
30
- var isValidApiKey = (value) => API_KEY_PATTERN.test(value);
31
-
32
- export {
33
- isApprovalMode,
34
- matchRankWeight,
35
- matchToolPattern,
36
- extractPolicyArg,
37
- isValidApiKey
38
- };
@@ -1,241 +0,0 @@
1
- import {
2
- askUser,
3
- describeToolCall,
4
- isPolicyConfig,
5
- savePendingQuestion,
6
- sendNotification,
7
- waitForAnswer
8
- } from "./chunk-4Z4MB37G.js";
9
- import {
10
- getApiKey,
11
- getBaseUrl,
12
- withRetry
13
- } from "./chunk-O6A5RHWY.js";
14
-
15
- // src/policy.ts
16
- import { createHash } from "crypto";
17
- import { existsSync, readFileSync, writeFileSync } from "fs";
18
- import { join } from "path";
19
- import { tmpdir } from "os";
20
- var CACHE_TTL_MS = 5 * 60 * 1e3;
21
- var cacheFile = (apiKey) => {
22
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
23
- return join(tmpdir(), `pushary-policy-${hash}.json`);
24
- };
25
- var fetchPolicy = async (apiKey) => {
26
- return withRetry(async () => {
27
- const baseUrl = getBaseUrl();
28
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
29
- headers: { "Authorization": `Bearer ${apiKey}` },
30
- signal: AbortSignal.timeout(1e4)
31
- });
32
- if (!response.ok) {
33
- throw new Error(`Failed to fetch policy: ${response.status}`);
34
- }
35
- const raw = await response.json();
36
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
37
- return raw;
38
- }, { maxAttempts: 2 });
39
- };
40
- var getPolicy = async (apiKey) => {
41
- const path = cacheFile(apiKey);
42
- let staleCache = null;
43
- if (existsSync(path)) {
44
- try {
45
- const stat = readFileSync(path, "utf-8");
46
- const cached = JSON.parse(stat);
47
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
48
- if (!cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS) {
49
- return cached;
50
- }
51
- staleCache = cached;
52
- } catch {
53
- }
54
- }
55
- try {
56
- const policy = await fetchPolicy(apiKey);
57
- try {
58
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now() }), "utf-8");
59
- } catch {
60
- }
61
- return policy;
62
- } catch {
63
- if (staleCache) return staleCache;
64
- throw new Error("Failed to fetch policy and no cached policy available");
65
- }
66
- };
67
- var resolvePolicy = (config, toolName, modeOverride) => {
68
- const base = config.policies.find((p) => p.tool === toolName) ?? config.policies.find((p) => p.tool === "*") ?? {
69
- tool: toolName,
70
- timeoutSeconds: config.defaultTimeoutSeconds,
71
- timeoutAction: config.defaultTimeoutAction,
72
- mode: config.defaultMode ?? "push_first",
73
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
74
- };
75
- const effectiveOverride = modeOverride ?? config.modeOverride;
76
- if (effectiveOverride) {
77
- return { ...base, mode: effectiveOverride };
78
- }
79
- return base;
80
- };
81
- var fetchModeOverride = async (apiKey) => {
82
- try {
83
- const baseUrl = getBaseUrl();
84
- const response = await fetch(`${baseUrl}/api/mcp/mode`, {
85
- headers: { "Authorization": `Bearer ${apiKey}` },
86
- signal: AbortSignal.timeout(3e3)
87
- });
88
- if (!response.ok) return null;
89
- const data = await response.json();
90
- const mode = data.override?.mode;
91
- if (mode && ["push_only", "terminal_only", "push_first", "notify_only"].includes(mode)) {
92
- return mode;
93
- }
94
- return null;
95
- } catch {
96
- return null;
97
- }
98
- };
99
-
100
- // src/hook.ts
101
- import { basename } from "path";
102
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
103
- var allow = () => ({
104
- hookSpecificOutput: {
105
- hookEventName: "PreToolUse",
106
- permissionDecision: "allow"
107
- }
108
- });
109
- var deny = (reason) => ({
110
- hookSpecificOutput: {
111
- hookEventName: "PreToolUse",
112
- permissionDecision: "deny",
113
- permissionDecisionReason: reason
114
- }
115
- });
116
- var ask = (reason) => ({
117
- hookSpecificOutput: {
118
- hookEventName: "PreToolUse",
119
- permissionDecision: "ask",
120
- ...reason ? { permissionDecisionReason: reason } : {}
121
- }
122
- });
123
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
124
- while (Date.now() < deadlineMs) {
125
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
126
- let answer;
127
- try {
128
- answer = await waitForAnswer(apiKey, correlationId, remaining);
129
- } catch {
130
- if (Date.now() + pollInterval >= deadlineMs) break;
131
- await sleep(pollInterval);
132
- continue;
133
- }
134
- if (answer.answered) return answer;
135
- if (Date.now() + pollInterval >= deadlineMs) break;
136
- await sleep(pollInterval);
137
- }
138
- return { answered: false };
139
- };
140
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction) => {
141
- let result;
142
- try {
143
- result = await askUser(apiKey, {
144
- question: `Allow ${description}?`,
145
- type: "confirm",
146
- context: `Agent wants to run this in ${projectName}`,
147
- agentName: `Claude Code - ${projectName}`
148
- });
149
- } catch {
150
- switch (timeoutAction) {
151
- case "approve":
152
- return allow();
153
- case "deny":
154
- return deny("Push notification failed, denying per policy");
155
- default:
156
- return ask("Push notification failed, asking in terminal");
157
- }
158
- }
159
- const deadline = Date.now() + timeoutSeconds * 1e3;
160
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
161
- if (answer.answered) {
162
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
163
- }
164
- switch (timeoutAction) {
165
- case "approve":
166
- return allow();
167
- case "deny":
168
- return deny("No response within timeout");
169
- default:
170
- return ask("No push response, asking in terminal");
171
- }
172
- };
173
- var handleTerminalOnly = () => {
174
- return ask();
175
- };
176
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds) => {
177
- let result;
178
- try {
179
- result = await askUser(apiKey, {
180
- question: `Allow ${description}?`,
181
- type: "confirm",
182
- context: `Agent wants to run this in ${projectName}`,
183
- agentName: `Claude Code - ${projectName}`
184
- });
185
- } catch {
186
- return ask("Push notification failed, asking in terminal");
187
- }
188
- const deadline = Date.now() + pushFirstSeconds * 1e3;
189
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
190
- if (answer.answered) {
191
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
192
- }
193
- savePendingQuestion(result.correlationId);
194
- return ask("Sent as push notification. You can also approve here.");
195
- };
196
- var handleNotifyOnly = async (apiKey, description, projectName) => {
197
- try {
198
- await sendNotification(apiKey, {
199
- title: "Agent needs approval",
200
- body: description,
201
- agentName: `Claude Code - ${projectName}`
202
- });
203
- } catch {
204
- }
205
- return ask();
206
- };
207
- var handlePreToolUse = async (input) => {
208
- try {
209
- const apiKey = getApiKey();
210
- const [policy, modeOverride] = await Promise.all([
211
- getPolicy(apiKey),
212
- fetchModeOverride(apiKey)
213
- ]);
214
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeOverride);
215
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
216
- return allow();
217
- }
218
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
219
- const projectName = basename(input.cwd ?? process.cwd());
220
- switch (toolPolicy.mode) {
221
- case "push_only":
222
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction);
223
- case "terminal_only":
224
- return handleTerminalOnly();
225
- case "push_first":
226
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
227
- case "notify_only":
228
- return handleNotifyOnly(apiKey, description, projectName);
229
- default:
230
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
231
- }
232
- } catch {
233
- return ask("Pushary unavailable, falling back to terminal approval");
234
- }
235
- };
236
-
237
- export {
238
- getPolicy,
239
- resolvePolicy,
240
- handlePreToolUse
241
- };
@@ -1,175 +0,0 @@
1
- import {
2
- DEFAULT_SESSION,
3
- askUser,
4
- deriveToolTarget,
5
- describeToolCall,
6
- fetchModeState,
7
- getMachineId,
8
- getPolicy,
9
- resolvePolicy,
10
- savePendingQuestion,
11
- sendNotification,
12
- waitForAnswer
13
- } from "./chunk-ACE77TKQ.js";
14
- import {
15
- getApiKey
16
- } from "./chunk-NKXSILEW.js";
17
-
18
- // src/hook.ts
19
- import { basename } from "path";
20
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
- var denyReasonFrom = (value) => value && value !== "no" && value !== "yes" ? `Denied from your phone: ${value}` : "Denied via push notification";
22
- var allow = () => ({
23
- hookSpecificOutput: {
24
- hookEventName: "PreToolUse",
25
- permissionDecision: "allow"
26
- }
27
- });
28
- var deny = (reason) => ({
29
- hookSpecificOutput: {
30
- hookEventName: "PreToolUse",
31
- permissionDecision: "deny",
32
- permissionDecisionReason: reason
33
- }
34
- });
35
- var ask = (reason) => ({
36
- hookSpecificOutput: {
37
- hookEventName: "PreToolUse",
38
- permissionDecision: "ask",
39
- ...reason ? { permissionDecisionReason: reason } : {}
40
- }
41
- });
42
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
43
- while (Date.now() < deadlineMs) {
44
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
45
- let answer;
46
- try {
47
- answer = await waitForAnswer(apiKey, correlationId, remaining);
48
- } catch {
49
- if (Date.now() + pollInterval >= deadlineMs) break;
50
- await sleep(pollInterval);
51
- continue;
52
- }
53
- if (answer.answered) return answer;
54
- if (Date.now() + pollInterval >= deadlineMs) break;
55
- await sleep(pollInterval);
56
- }
57
- return { answered: false };
58
- };
59
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
60
- let result;
61
- try {
62
- result = await askUser(apiKey, {
63
- question: `Allow ${description}?`,
64
- type: "confirm",
65
- context: `Agent wants to run this in ${projectName}`,
66
- agentName: `Claude Code - ${projectName}`,
67
- sessionId,
68
- machineId,
69
- toolName,
70
- toolTarget
71
- });
72
- } catch {
73
- switch (timeoutAction) {
74
- case "approve":
75
- return allow();
76
- case "deny":
77
- return deny("Push notification failed, denying per policy");
78
- default:
79
- return ask("Push notification failed, asking in terminal");
80
- }
81
- }
82
- const deadline = Date.now() + timeoutSeconds * 1e3;
83
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
84
- if (answer.answered) {
85
- return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
86
- }
87
- switch (timeoutAction) {
88
- case "approve":
89
- return allow();
90
- case "deny":
91
- return deny("No response within timeout");
92
- default:
93
- return ask("No push response, asking in terminal");
94
- }
95
- };
96
- var handleTerminalOnly = () => {
97
- return ask();
98
- };
99
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
100
- let result;
101
- try {
102
- result = await askUser(apiKey, {
103
- question: `Allow ${description}?`,
104
- type: "confirm",
105
- context: `Agent wants to run this in ${projectName}`,
106
- agentName: `Claude Code - ${projectName}`,
107
- sessionId,
108
- machineId,
109
- toolName,
110
- toolTarget
111
- });
112
- } catch {
113
- return ask("Push notification failed, asking in terminal");
114
- }
115
- const deadline = Date.now() + pushFirstSeconds * 1e3;
116
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
117
- if (answer.answered) {
118
- return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
119
- }
120
- savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
121
- return ask("Sent as push notification. You can also approve here.");
122
- };
123
- var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
124
- try {
125
- await sendNotification(apiKey, {
126
- title: "Agent needs approval",
127
- body: description,
128
- agentName: `Claude Code - ${projectName}`,
129
- sessionId,
130
- machineId
131
- });
132
- } catch {
133
- }
134
- return ask();
135
- };
136
- var handlePreToolUse = async (input) => {
137
- try {
138
- const apiKey = getApiKey();
139
- const modeState = await fetchModeState(apiKey, input.session_id);
140
- const policy = await getPolicy(apiKey, modeState.policyVersion);
141
- if (modeState.kill) {
142
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
143
- }
144
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
145
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
146
- return allow();
147
- }
148
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
149
- return deny(`Denied by policy for ${toolPolicy.tool}`);
150
- }
151
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
152
- const projectName = basename(input.cwd ?? process.cwd());
153
- const sessionId = input.session_id;
154
- const machineId = getMachineId();
155
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
156
- switch (toolPolicy.mode) {
157
- case "push_only":
158
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
159
- case "terminal_only":
160
- return handleTerminalOnly();
161
- case "push_first":
162
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
163
- case "notify_only":
164
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
165
- default:
166
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
167
- }
168
- } catch {
169
- return ask("Pushary unavailable, falling back to terminal approval");
170
- }
171
- };
172
-
173
- export {
174
- handlePreToolUse
175
- };