@pushary/agent-hooks 0.24.0 → 0.25.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 (88) hide show
  1. package/dist/bin/pushary-codex-hook.js +1 -1
  2. package/dist/bin/pushary-codex.js +1 -1
  3. package/dist/bin/pushary-gemini-hook.js +1 -1
  4. package/dist/bin/pushary-hook.js +2 -2
  5. package/dist/bin/pushary-post-hook.js +1 -1
  6. package/dist/bin/pushary-prompt-hook.js +1 -1
  7. package/dist/bin/pushary-setup.js +1 -1
  8. package/dist/bin/pushary-stop-hook.js +1 -1
  9. package/dist/chunk-22CV7V7A.js +38 -0
  10. package/dist/chunk-2BE2IPMO.js +315 -0
  11. package/dist/chunk-2CRLBMOX.js +244 -0
  12. package/dist/chunk-2HMNOZPY.js +109 -0
  13. package/dist/chunk-2I6DLXJN.js +219 -0
  14. package/dist/chunk-2Q6XPZ4Q.js +395 -0
  15. package/dist/{chunk-U4SSWRVM.js → chunk-3LC4YUMA.js} +1 -1
  16. package/dist/chunk-3MIR7ODJ.js +112 -0
  17. package/dist/chunk-3QZESA66.js +222 -0
  18. package/dist/chunk-4Z4MB37G.js +96 -0
  19. package/dist/chunk-5GFUI5N6.js +132 -0
  20. package/dist/chunk-5JEDLXEC.js +99 -0
  21. package/dist/chunk-5LTQNC7R.js +824 -0
  22. package/dist/chunk-5QHQVXWN.js +174 -0
  23. package/dist/chunk-6A3WCJO2.js +416 -0
  24. package/dist/chunk-6QWFMVCD.js +328 -0
  25. package/dist/chunk-6SRXMZAN.js +99 -0
  26. package/dist/chunk-7PTU7TGE.js +96 -0
  27. package/dist/chunk-AB4KX4XT.js +109 -0
  28. package/dist/chunk-AC4UYAGX.js +136 -0
  29. package/dist/chunk-ACE77TKQ.js +328 -0
  30. package/dist/chunk-BHAMEPOP.js +323 -0
  31. package/dist/chunk-BYNYYZWW.js +412 -0
  32. package/dist/chunk-C5TFTNHG.js +244 -0
  33. package/dist/chunk-CH53PBQN.js +265 -0
  34. package/dist/chunk-DF3BM6BF.js +195 -0
  35. package/dist/chunk-DKZVKEOW.js +175 -0
  36. package/dist/chunk-EMPL27ZV.js +96 -0
  37. package/dist/chunk-EQJXMEIR.js +175 -0
  38. package/dist/chunk-FXYTRZHC.js +177 -0
  39. package/dist/chunk-GTJGZBTQ.js +328 -0
  40. package/dist/{chunk-OQZH5PVA.js → chunk-GYPPVD3P.js} +32 -18
  41. package/dist/chunk-HJMFYDWY.js +222 -0
  42. package/dist/chunk-HRQEECB6.js +315 -0
  43. package/dist/chunk-HWEMAAOY.js +370 -0
  44. package/dist/chunk-IBWCHA5M.js +10 -0
  45. package/dist/chunk-KTM4ZQ3W.js +96 -0
  46. package/dist/chunk-KTP2EPVB.js +27 -0
  47. package/dist/chunk-KYARP7KP.js +97 -0
  48. package/dist/chunk-M2N5DYWN.js +247 -0
  49. package/dist/chunk-M5F2L4KF.js +177 -0
  50. package/dist/chunk-M6S3M6E3.js +244 -0
  51. package/dist/chunk-N7VXDBQU.js +6 -0
  52. package/dist/chunk-O2QL6U6G.js +194 -0
  53. package/dist/chunk-O6A5RHWY.js +122 -0
  54. package/dist/chunk-ODUXELPM.js +219 -0
  55. package/dist/chunk-OF5WIOYS.js +129 -0
  56. package/dist/chunk-OP4QAN23.js +99 -0
  57. package/dist/chunk-P4JH2Q7Z.js +102 -0
  58. package/dist/chunk-PMD5JSV3.js +242 -0
  59. package/dist/chunk-PSSHNBEL.js +177 -0
  60. package/dist/chunk-QEPRH7JB.js +315 -0
  61. package/dist/chunk-QRXWPZKN.js +308 -0
  62. package/dist/chunk-QY4L6XHN.js +384 -0
  63. package/dist/chunk-RNWPCELY.js +176 -0
  64. package/dist/chunk-RSHN2AQ7.js +29 -0
  65. package/dist/chunk-RZLVE57X.js +38 -0
  66. package/dist/chunk-SDCIKREA.js +241 -0
  67. package/dist/chunk-SDREQWNI.js +175 -0
  68. package/dist/chunk-SH26ZOHU.js +159 -0
  69. package/dist/chunk-TRLBBLSS.js +176 -0
  70. package/dist/chunk-U6OXZPYC.js +384 -0
  71. package/dist/chunk-UIBTFZUD.js +314 -0
  72. package/dist/chunk-USUCPCUC.js +156 -0
  73. package/dist/chunk-V4GLWPD7.js +174 -0
  74. package/dist/chunk-VC6U3QGF.js +142 -0
  75. package/dist/chunk-VIST7ACL.js +88 -0
  76. package/dist/chunk-VUNL35KE.js +16 -0
  77. package/dist/chunk-VWBNI4SC.js +174 -0
  78. package/dist/chunk-W5KRWUNE.js +262 -0
  79. package/dist/chunk-WCGKLHCL.js +154 -0
  80. package/dist/chunk-WNXGIEX7.js +219 -0
  81. package/dist/chunk-XPVSZIA3.js +315 -0
  82. package/dist/chunk-Y633ZIJF.js +384 -0
  83. package/dist/chunk-YCL4GUFR.js +222 -0
  84. package/dist/chunk-YTMKB44I.js +220 -0
  85. package/dist/chunk-ZWBS3T7Q.js +244 -0
  86. package/dist/pushary-mode-T7XOPI6Z.js +83 -0
  87. package/dist/src/index.js +2 -2
  88. package/package.json +1 -1
@@ -0,0 +1,314 @@
1
+ // src/codex-config.ts
2
+ import { createHash } from "crypto";
3
+ var CODEX_HOOK_BINARY = "pushary-codex-hook";
4
+ var CODEX_HOOK_EVENTS = [
5
+ { event: "PermissionRequest", matcher: "Bash|apply_patch", timeout: 180, statusMessage: "Waiting for your phone" },
6
+ { event: "PreToolUse", matcher: "Bash|apply_patch", timeout: 180, statusMessage: "Checking Pushary policy" },
7
+ { event: "PostToolUse", matcher: "Bash|apply_patch", timeout: 10 },
8
+ { event: "UserPromptSubmit", timeout: 10 },
9
+ { event: "Stop", timeout: 10 },
10
+ { event: "SessionStart", matcher: "startup|resume", timeout: 10 }
11
+ ];
12
+ var CODEX_EVENT_KEY = {
13
+ PermissionRequest: "permission_request",
14
+ PreToolUse: "pre_tool_use",
15
+ PostToolUse: "post_tool_use",
16
+ UserPromptSubmit: "user_prompt_submit",
17
+ Stop: "stop",
18
+ SessionStart: "session_start"
19
+ };
20
+ var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
21
+ var ensureRecord = (target, key) => {
22
+ const existing = asRecord(target[key]);
23
+ if (existing) return existing;
24
+ const created = {};
25
+ target[key] = created;
26
+ return created;
27
+ };
28
+ var isPusharyCodexHook = (entry) => {
29
+ const hooks = asRecord(entry)?.hooks;
30
+ if (!Array.isArray(hooks)) return false;
31
+ return hooks.some((hook) => String(asRecord(hook)?.command ?? "").includes(CODEX_HOOK_BINARY));
32
+ };
33
+ var addCodexHooks = (config, command) => {
34
+ const hooks = ensureRecord(config, "hooks");
35
+ for (const definition of CODEX_HOOK_EVENTS) {
36
+ const existing = Array.isArray(hooks[definition.event]) ? hooks[definition.event] : [];
37
+ const entries = existing.filter((entry) => !isPusharyCodexHook(entry));
38
+ entries.push({
39
+ ...definition.matcher ? { matcher: definition.matcher } : {},
40
+ hooks: [{
41
+ type: "command",
42
+ command,
43
+ timeout: definition.timeout,
44
+ ...definition.statusMessage ? { statusMessage: definition.statusMessage } : {}
45
+ }]
46
+ });
47
+ hooks[definition.event] = entries;
48
+ }
49
+ };
50
+ var removeCodexHooks = (config) => {
51
+ const hooks = asRecord(config.hooks);
52
+ if (!hooks) return false;
53
+ let changed = false;
54
+ for (const definition of CODEX_HOOK_EVENTS) {
55
+ const entries = hooks[definition.event];
56
+ if (!Array.isArray(entries)) continue;
57
+ const filtered = entries.filter((entry) => !isPusharyCodexHook(entry));
58
+ if (filtered.length !== entries.length) {
59
+ if (filtered.length === 0) {
60
+ delete hooks[definition.event];
61
+ } else {
62
+ hooks[definition.event] = filtered;
63
+ }
64
+ changed = true;
65
+ }
66
+ }
67
+ if (Object.keys(hooks).length === 0) delete config.hooks;
68
+ return changed;
69
+ };
70
+ var hasCodexHooks = (config) => {
71
+ const hooks = asRecord(config.hooks);
72
+ if (!hooks) return false;
73
+ return CODEX_HOOK_EVENTS.some((definition) => {
74
+ const entries = hooks[definition.event];
75
+ return Array.isArray(entries) && entries.some(isPusharyCodexHook);
76
+ });
77
+ };
78
+ var missingCodexHookEvents = (config) => {
79
+ const hooks = asRecord(config.hooks);
80
+ return CODEX_HOOK_EVENTS.filter((definition) => {
81
+ const entries = hooks?.[definition.event];
82
+ return !Array.isArray(entries) || !entries.some(isPusharyCodexHook);
83
+ }).map((definition) => definition.event);
84
+ };
85
+ var canonicalJson = (value) => {
86
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
87
+ if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
88
+ const obj = value;
89
+ return "{" + Object.keys(obj).sort().map((key) => JSON.stringify(key) + ":" + canonicalJson(obj[key])).join(",") + "}";
90
+ };
91
+ var codexHookTrustHash = (definition, command) => {
92
+ const hook = { async: false, command, timeout: definition.timeout, type: "command" };
93
+ if (definition.statusMessage) hook.statusMessage = definition.statusMessage;
94
+ const identity = { event_name: CODEX_EVENT_KEY[definition.event], hooks: [hook] };
95
+ if (definition.matcher) identity.matcher = definition.matcher;
96
+ return "sha256:" + createHash("sha256").update(canonicalJson(identity), "utf8").digest("hex");
97
+ };
98
+ var codexHookStateKey = (hooksJsonPath, event) => `${hooksJsonPath}:${CODEX_EVENT_KEY[event]}:0:0`;
99
+ var addCodexHookTrust = (config, hooksJsonPath, command) => {
100
+ const hooks = ensureRecord(config, "hooks");
101
+ const state = ensureRecord(hooks, "state");
102
+ for (const definition of CODEX_HOOK_EVENTS) {
103
+ const key = codexHookStateKey(hooksJsonPath, definition.event);
104
+ const existing = asRecord(state[key]) ?? {};
105
+ state[key] = { ...existing, trusted_hash: codexHookTrustHash(definition, command) };
106
+ }
107
+ };
108
+
109
+ // src/gemini-config.ts
110
+ var GEMINI_HOOK_BINARY = "pushary-gemini-hook";
111
+ var GEMINI_MCP_URL = "https://pushary.com/api/mcp/mcp";
112
+ var GEMINI_HOOK_EVENTS = [
113
+ { event: "BeforeTool", matcher: "run_shell_command|write_file|replace", timeoutMs: 18e4 },
114
+ { event: "AfterTool", matcher: "run_shell_command|write_file|replace", timeoutMs: 1e4 },
115
+ { event: "BeforeAgent", timeoutMs: 1e4 },
116
+ { event: "SessionStart", timeoutMs: 1e4 },
117
+ { event: "SessionEnd", timeoutMs: 1e4 }
118
+ ];
119
+ var asRecord2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
120
+ var ensureRecord2 = (target, key) => {
121
+ const existing = asRecord2(target[key]);
122
+ if (existing) return existing;
123
+ const created = {};
124
+ target[key] = created;
125
+ return created;
126
+ };
127
+ var isPusharyGeminiHook = (entry) => {
128
+ const hooks = asRecord2(entry)?.hooks;
129
+ if (!Array.isArray(hooks)) return false;
130
+ return hooks.some((hook) => String(asRecord2(hook)?.command ?? "").includes(GEMINI_HOOK_BINARY));
131
+ };
132
+ var addGeminiMcpServer = (settings, apiKey) => {
133
+ const mcpServers = ensureRecord2(settings, "mcpServers");
134
+ mcpServers.pushary = {
135
+ httpUrl: GEMINI_MCP_URL,
136
+ headers: { Authorization: `Bearer ${apiKey}` },
137
+ trust: true
138
+ };
139
+ };
140
+ var addGeminiHooks = (settings, command) => {
141
+ const hooks = ensureRecord2(settings, "hooks");
142
+ for (const definition of GEMINI_HOOK_EVENTS) {
143
+ const existing = Array.isArray(hooks[definition.event]) ? hooks[definition.event] : [];
144
+ const entries = existing.filter((entry) => !isPusharyGeminiHook(entry));
145
+ entries.push({
146
+ ...definition.matcher ? { matcher: definition.matcher } : {},
147
+ hooks: [{
148
+ name: "pushary",
149
+ type: "command",
150
+ command,
151
+ timeout: definition.timeoutMs
152
+ }]
153
+ });
154
+ hooks[definition.event] = entries;
155
+ }
156
+ };
157
+ var removeGeminiHooks = (settings) => {
158
+ const hooks = asRecord2(settings.hooks);
159
+ if (!hooks) return false;
160
+ let changed = false;
161
+ for (const definition of GEMINI_HOOK_EVENTS) {
162
+ const entries = hooks[definition.event];
163
+ if (!Array.isArray(entries)) continue;
164
+ const filtered = entries.filter((entry) => !isPusharyGeminiHook(entry));
165
+ if (filtered.length !== entries.length) {
166
+ if (filtered.length === 0) {
167
+ delete hooks[definition.event];
168
+ } else {
169
+ hooks[definition.event] = filtered;
170
+ }
171
+ changed = true;
172
+ }
173
+ }
174
+ if (Object.keys(hooks).length === 0) delete settings.hooks;
175
+ return changed;
176
+ };
177
+ var removeGeminiMcpServer = (settings) => {
178
+ const mcpServers = asRecord2(settings.mcpServers);
179
+ if (!mcpServers?.pushary) return false;
180
+ delete mcpServers.pushary;
181
+ if (Object.keys(mcpServers).length === 0) delete settings.mcpServers;
182
+ return true;
183
+ };
184
+ var removeGeminiSettings = (settings) => {
185
+ const mcpRemoved = removeGeminiMcpServer(settings);
186
+ const hooksRemoved = removeGeminiHooks(settings);
187
+ return mcpRemoved || hooksRemoved;
188
+ };
189
+ var hasGeminiHooks = (settings) => {
190
+ const hooks = asRecord2(settings.hooks);
191
+ if (!hooks) return false;
192
+ return GEMINI_HOOK_EVENTS.some((definition) => {
193
+ const entries = hooks[definition.event];
194
+ return Array.isArray(entries) && entries.some(isPusharyGeminiHook);
195
+ });
196
+ };
197
+ var missingGeminiHookEvents = (settings) => {
198
+ const hooks = asRecord2(settings.hooks);
199
+ return GEMINI_HOOK_EVENTS.filter((definition) => {
200
+ const entries = hooks?.[definition.event];
201
+ return !Array.isArray(entries) || !entries.some(isPusharyGeminiHook);
202
+ }).map((definition) => definition.event);
203
+ };
204
+
205
+ // src/instruction-file.ts
206
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "fs";
207
+ import { dirname } from "path";
208
+ var PUSHARY_BEGIN = "<!-- BEGIN PUSHARY (managed by @pushary/agent-hooks; do not edit this block) -->";
209
+ var PUSHARY_END = "<!-- END PUSHARY -->";
210
+ var instructionBody = (label) => `## Pushary notifications and approvals
211
+
212
+ You have Pushary MCP tools that reach the user on their phone. Use them proactively. Do not wait for the user to ask.
213
+
214
+ - When you need the user to make a decision or answer a clarifying question, call \`ask_user\` instead of guessing or stalling. Use type "confirm" for yes/no, "select" for a fixed set of options, and "input" for free text. \`ask_user\` blocks until the user replies or it times out, so you do not need a separate wait step.
215
+ - Before any risky or irreversible step (deleting files, force pushing, spending money, sending external messages), call \`ask_user\` with type "confirm" and wait for approval.
216
+ - When you are blocked, stuck, or hit an error you cannot resolve on your own, call \`send_notification\` so the user knows, and call \`ask_user\` if you need a decision to continue.
217
+ - When a task that took several steps finishes, call \`send_notification\` so the user knows it is done.
218
+ - Use \`cancel_question\` to retract a pending question once it is no longer needed.
219
+
220
+ Pass \`agentName\` as "${label} - <project folder name>" so the user knows which session is asking. If a question times out with no answer, retry once with a longer timeout before falling back to asking in the terminal.`;
221
+ var renderAgentInstructions = (label) => instructionBody(label);
222
+ var wrap = (body) => `${PUSHARY_BEGIN}
223
+ ${body}
224
+ ${PUSHARY_END}`;
225
+ var writeInstructionBlock = (filePath, body) => {
226
+ const dir = dirname(filePath);
227
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
228
+ let existing = "";
229
+ try {
230
+ existing = readFileSync(filePath, "utf-8");
231
+ } catch {
232
+ }
233
+ const block = wrap(body);
234
+ const start = existing.indexOf(PUSHARY_BEGIN);
235
+ const end = existing.indexOf(PUSHARY_END);
236
+ let next;
237
+ if (start !== -1 && end !== -1 && end > start) {
238
+ next = existing.slice(0, start) + block + existing.slice(end + PUSHARY_END.length);
239
+ } else {
240
+ const prefix = existing.trim() ? existing.replace(/\s*$/, "") + "\n\n" : "";
241
+ next = prefix + block + "\n";
242
+ }
243
+ writeFileSync(filePath, next, "utf-8");
244
+ };
245
+ var removeInstructionBlock = (filePath) => {
246
+ let existing = "";
247
+ try {
248
+ existing = readFileSync(filePath, "utf-8");
249
+ } catch {
250
+ return false;
251
+ }
252
+ const start = existing.indexOf(PUSHARY_BEGIN);
253
+ const end = existing.indexOf(PUSHARY_END);
254
+ if (start === -1 || end === -1 || end < start) return false;
255
+ const remaining = (existing.slice(0, start) + existing.slice(end + PUSHARY_END.length)).trim();
256
+ if (remaining === "") {
257
+ rmSync(filePath, { force: true });
258
+ } else {
259
+ writeFileSync(filePath, remaining + "\n", "utf-8");
260
+ }
261
+ return true;
262
+ };
263
+ var hasInstructionBlock = (filePath) => {
264
+ try {
265
+ return readFileSync(filePath, "utf-8").includes(PUSHARY_BEGIN);
266
+ } catch {
267
+ return false;
268
+ }
269
+ };
270
+
271
+ // src/npm.ts
272
+ import { execSync } from "child_process";
273
+ var cleanNpmEnv = () => {
274
+ const env = {};
275
+ for (const [key, value] of Object.entries(process.env)) {
276
+ if (key.toLowerCase().startsWith("npm_config_workspace")) continue;
277
+ env[key] = value;
278
+ }
279
+ return env;
280
+ };
281
+ var npmErrorMessage = (err) => {
282
+ const e = err;
283
+ const text = [e?.stderr, e?.stdout].map((part) => part ? part.toString() : "").join("\n");
284
+ 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));
285
+ return line || e?.message || String(err);
286
+ };
287
+ var execNpm = (args, options = {}) => {
288
+ return execSync(`npm ${args}`, {
289
+ timeout: 12e4,
290
+ stdio: "pipe",
291
+ ...options,
292
+ env: { ...cleanNpmEnv(), ...options.env ?? {} }
293
+ });
294
+ };
295
+
296
+ export {
297
+ addCodexHooks,
298
+ removeCodexHooks,
299
+ hasCodexHooks,
300
+ missingCodexHookEvents,
301
+ addCodexHookTrust,
302
+ GEMINI_HOOK_BINARY,
303
+ addGeminiMcpServer,
304
+ addGeminiHooks,
305
+ removeGeminiSettings,
306
+ hasGeminiHooks,
307
+ missingGeminiHookEvents,
308
+ renderAgentInstructions,
309
+ writeInstructionBlock,
310
+ removeInstructionBlock,
311
+ hasInstructionBlock,
312
+ npmErrorMessage,
313
+ execNpm
314
+ };
@@ -0,0 +1,156 @@
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 SAFE_SHELL_COMMANDS = /* @__PURE__ */ new Set([
30
+ "ls",
31
+ "pwd",
32
+ "cd",
33
+ "cat",
34
+ "head",
35
+ "tail",
36
+ "wc",
37
+ "echo",
38
+ "printf",
39
+ "which",
40
+ "type",
41
+ "whoami",
42
+ "id",
43
+ "uname",
44
+ "arch",
45
+ "printenv",
46
+ "locale",
47
+ "tty",
48
+ "dirname",
49
+ "basename",
50
+ "realpath",
51
+ "readlink",
52
+ "stat",
53
+ "cut",
54
+ "nl",
55
+ "tr",
56
+ "comm",
57
+ "diff",
58
+ "cmp",
59
+ "grep",
60
+ "egrep",
61
+ "fgrep",
62
+ "jq",
63
+ "cksum",
64
+ "md5sum",
65
+ "sha1sum",
66
+ "sha256sum",
67
+ "du",
68
+ "df",
69
+ "ps",
70
+ "true"
71
+ ]);
72
+ var SAFE_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
73
+ "status",
74
+ "log",
75
+ "diff",
76
+ "show",
77
+ "rev-parse",
78
+ "describe",
79
+ "blame",
80
+ "shortlog",
81
+ "ls-files",
82
+ "ls-tree",
83
+ "cat-file",
84
+ "whatchanged",
85
+ "rev-list",
86
+ "name-rev",
87
+ "for-each-ref",
88
+ "var",
89
+ "count-objects"
90
+ ]);
91
+ var GIT_WRITE_FLAGS = (token) => token === "--output" || token.startsWith("--output=");
92
+ var UNSAFE_SHELL_CHARS = /[;&|<>(){}`\\\n\r]/;
93
+ var basenameOf = (token) => {
94
+ const slash = Math.max(token.lastIndexOf("/"), token.lastIndexOf("\\"));
95
+ return slash === -1 ? token : token.slice(slash + 1);
96
+ };
97
+ var tokenizeShellCommand = (command) => {
98
+ const tokens = [];
99
+ let current = "";
100
+ let quote = null;
101
+ let started = false;
102
+ for (const ch of command) {
103
+ if (quote) {
104
+ if (ch === quote) quote = null;
105
+ else current += ch;
106
+ started = true;
107
+ continue;
108
+ }
109
+ if (ch === '"' || ch === "'") {
110
+ quote = ch;
111
+ started = true;
112
+ continue;
113
+ }
114
+ if (ch === " " || ch === " ") {
115
+ if (started) {
116
+ tokens.push(current);
117
+ current = "";
118
+ started = false;
119
+ }
120
+ continue;
121
+ }
122
+ current += ch;
123
+ started = true;
124
+ }
125
+ if (quote) return null;
126
+ if (started) tokens.push(current);
127
+ return tokens;
128
+ };
129
+ var isSafeReadOnlyCommand = (command) => {
130
+ const trimmed = command.trim();
131
+ if (!trimmed || trimmed.length > 2e3) return false;
132
+ if (UNSAFE_SHELL_CHARS.test(trimmed)) return false;
133
+ const tokens = tokenizeShellCommand(trimmed);
134
+ if (!tokens || tokens.length === 0) return false;
135
+ const first = tokens[0];
136
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first) || first.includes("$")) return false;
137
+ const exe = basenameOf(first);
138
+ if (exe === "git") {
139
+ const sub = tokens[1];
140
+ if (!sub || sub.startsWith("-")) return false;
141
+ if (!SAFE_GIT_SUBCOMMANDS.has(sub)) return false;
142
+ return !tokens.some(GIT_WRITE_FLAGS);
143
+ }
144
+ return SAFE_SHELL_COMMANDS.has(exe);
145
+ };
146
+ var API_KEY_PATTERN = /^pk_[a-f0-9]+\.[a-f0-9]+$/;
147
+ var isValidApiKey = (value) => API_KEY_PATTERN.test(value);
148
+
149
+ export {
150
+ isApprovalMode,
151
+ matchRankWeight,
152
+ matchToolPattern,
153
+ extractPolicyArg,
154
+ isSafeReadOnlyCommand,
155
+ isValidApiKey
156
+ };
@@ -0,0 +1,174 @@
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-XPVSZIA3.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 modeState = await fetchModeState(apiKey, input.session_id);
139
+ const policy = await getPolicy(apiKey, modeState.policyVersion);
140
+ if (modeState.kill) {
141
+ return deny("Stopped by user \u2014 this agent was halted from Pushary");
142
+ }
143
+ const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
144
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
145
+ return allow();
146
+ }
147
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
148
+ return deny(`Denied by policy for ${toolPolicy.tool}`);
149
+ }
150
+ const description = describeToolCall(input.tool_name, input.tool_input, "hook");
151
+ const projectName = basename(input.cwd ?? process.cwd());
152
+ const sessionId = input.session_id;
153
+ const machineId = getMachineId();
154
+ const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
155
+ switch (toolPolicy.mode) {
156
+ case "push_only":
157
+ return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
158
+ case "terminal_only":
159
+ return handleTerminalOnly();
160
+ case "push_first":
161
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
162
+ case "notify_only":
163
+ return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
164
+ default:
165
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
166
+ }
167
+ } catch {
168
+ return ask("Pushary unavailable, falling back to terminal approval");
169
+ }
170
+ };
171
+
172
+ export {
173
+ handlePreToolUse
174
+ };