@pushary/agent-hooks 0.20.0 → 0.21.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.
@@ -8,7 +8,7 @@ import {
8
8
  removeCodexHooks,
9
9
  removeGeminiSettings,
10
10
  removeInstructionBlock
11
- } from "../chunk-UIBTFZUD.js";
11
+ } from "../chunk-BHAMEPOP.js";
12
12
 
13
13
  // bin/pushary-clean.ts
14
14
  import { existsSync, readFileSync, writeFileSync, rmSync } from "fs";
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ denyReasonFrom
4
+ } from "../chunk-N7VXDBQU.js";
2
5
  import {
3
6
  CODEX_AGENT,
4
7
  codexAllow,
@@ -69,6 +72,19 @@ var consumeApproval = (toolUseId) => {
69
72
  return false;
70
73
  }
71
74
  };
75
+ var NOTIFY_TTL_MS = 60 * 1e3;
76
+ var claimNotify = (toolUseId) => {
77
+ if (!toolUseId) return true;
78
+ const path = join(APPROVAL_DIR, `notify-${sanitizeId(toolUseId)}`);
79
+ try {
80
+ if (existsSync(path) && Date.now() - statSync(path).mtimeMs < NOTIFY_TTL_MS) return false;
81
+ if (!existsSync(APPROVAL_DIR)) mkdirSync(APPROVAL_DIR, { recursive: true, mode: 448 });
82
+ writeFileSync(path, "", { encoding: "utf-8", mode: 384 });
83
+ return true;
84
+ } catch {
85
+ return true;
86
+ }
87
+ };
72
88
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
73
89
  var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
74
90
  while (Date.now() < deadlineMs) {
@@ -133,7 +149,7 @@ var decidePermissionRequest = async (input) => {
133
149
  }
134
150
  if (toolPolicy.mode === "terminal_only") return codexPass();
135
151
  if (toolPolicy.mode === "notify_only") {
136
- await notifyApprovalNeeded(apiKey, input);
152
+ if (claimNotify(input.tool_use_id)) await notifyApprovalNeeded(apiKey, input);
137
153
  return codexPass();
138
154
  }
139
155
  const waitSeconds = toolPolicy.mode === "push_first" ? toolPolicy.pushFirstSeconds : toolPolicy.timeoutSeconds;
@@ -143,7 +159,7 @@ var decidePermissionRequest = async (input) => {
143
159
  if (toolPolicy.mode === "push_only") markApproved(input.tool_use_id);
144
160
  return codexAllow();
145
161
  }
146
- return codexDeny("Denied via push notification");
162
+ return codexDeny(denyReasonFrom(answer.value));
147
163
  }
148
164
  savePendingQuestion(input.session_id || DEFAULT_SESSION, correlationId);
149
165
  if (toolPolicy.mode === "push_first") return codexPass();
@@ -176,13 +192,13 @@ var decidePreToolUse = async (input) => {
176
192
  }
177
193
  const { answer, correlationId } = pushed;
178
194
  if (answer.answered) {
179
- return answer.value === "yes" ? codexPass() : codexDeny("Denied via push notification");
195
+ return answer.value === "yes" ? codexPass() : codexDeny(denyReasonFrom(answer.value));
180
196
  }
181
197
  savePendingQuestion(input.session_id || DEFAULT_SESSION, correlationId);
182
198
  return preToolUseTimeoutDecision(toolPolicy.timeoutAction);
183
199
  }
184
200
  if (toolPolicy.mode === "notify_only") {
185
- await notifyApprovalNeeded(apiKey, input);
201
+ if (claimNotify(input.tool_use_id)) await notifyApprovalNeeded(apiKey, input);
186
202
  return codexPass();
187
203
  }
188
204
  return codexPass();
@@ -6,8 +6,9 @@ import {
6
6
  hasGeminiHooks,
7
7
  hasInstructionBlock,
8
8
  missingCodexHookEvents,
9
- missingGeminiHookEvents
10
- } from "../chunk-UIBTFZUD.js";
9
+ missingGeminiHookEvents,
10
+ untrustedCodexHookEvents
11
+ } from "../chunk-BHAMEPOP.js";
11
12
  import {
12
13
  callMcpTool,
13
14
  sendMcpRequest
@@ -62,6 +63,20 @@ var extractHookCommand = (entries, needle) => {
62
63
  }
63
64
  return null;
64
65
  };
66
+ var extractHookTimeout = (entries, needle) => {
67
+ if (!Array.isArray(entries)) return null;
68
+ for (const entry of entries) {
69
+ const hookList = entry.hooks;
70
+ if (!Array.isArray(hookList)) continue;
71
+ for (const candidate of hookList) {
72
+ const hook = candidate;
73
+ if (typeof hook.command === "string" && hook.command.includes(needle) && typeof hook.timeout === "number") {
74
+ return hook.timeout;
75
+ }
76
+ }
77
+ }
78
+ return null;
79
+ };
65
80
  var results = [];
66
81
  var check = (passed, label, detail) => {
67
82
  results.push({ passed, label, detail });
@@ -149,15 +164,30 @@ var main = async () => {
149
164
  const codexHooksJson = readJson(codexHooksPath);
150
165
  if (existsSync(codexConfigPath) || codexHooksJson) {
151
166
  const codexConfig = existsSync(codexConfigPath) ? readFileSync(codexConfigPath, "utf-8") : "";
152
- const hasPusharyMcp = codexConfig.includes("[mcp_servers.pushary]");
153
- check(hasPusharyMcp, "Codex: MCP server configured");
154
- if (hasPusharyMcp) {
155
- const hasAutoApprove = codexConfig.includes('default_tools_approval_mode = "approve"');
156
- check(hasAutoApprove, "Codex: tools auto-allowed", hasAutoApprove ? 'default_tools_approval_mode = "approve"' : "missing \u2014 MCP calls will prompt for approval");
157
- const hasPerToolOverrides = /\[mcp_servers\.pushary\.tools\./.test(codexConfig);
158
- if (hasPerToolOverrides) {
167
+ let codexParsed = {};
168
+ try {
169
+ codexParsed = parseTOML(codexConfig);
170
+ } catch {
171
+ }
172
+ const codexMcp = codexParsed.mcp_servers?.pushary;
173
+ const codexTransport = !!codexMcp && (typeof codexMcp.url === "string" || typeof codexMcp.command === "string");
174
+ const codexEnvVar = codexMcp && typeof codexMcp.bearer_token_env_var === "string" ? codexMcp.bearer_token_env_var : void 0;
175
+ const codexHasCred = !!codexEnvVar || !!codexMcp && typeof codexMcp.bearer_token === "string";
176
+ const codexMcpOk = !!codexMcp && codexTransport && codexHasCred;
177
+ check(codexMcpOk, "Codex: MCP server configured", codexMcpOk ? void 0 : !codexMcp ? "no [mcp_servers.pushary] \u2014 re-run setup" : !codexTransport ? "entry has no url \u2014 `codex mcp add` likely failed, re-run setup" : "entry has no bearer_token/_env_var \u2014 re-run setup");
178
+ if (codexMcp) {
179
+ const hasAutoApprove = codexMcp.default_tools_approval_mode === "approve";
180
+ check(hasAutoApprove, "Codex: tools auto-allowed", hasAutoApprove ? "default_tools_approval_mode = approve" : "missing \u2014 MCP calls will prompt for approval");
181
+ if (codexMcp.tools && typeof codexMcp.tools === "object") {
159
182
  console.log(` ${warn} Codex: per-tool approval overrides detected ${dim("(redundant with default_tools_approval_mode)")}`);
160
183
  }
184
+ if (codexEnvVar) {
185
+ const envValue = process.env[codexEnvVar]?.trim();
186
+ check(!!envValue, `Codex: MCP key available in shell ($${codexEnvVar})`, envValue ? "set" : `not set \u2014 Codex reads its key from your shell; the ~/.pushary/config.json fallback only covers hooks. Add the export to your profile or re-run setup`);
187
+ if (envValue && apiKey && envValue !== apiKey) {
188
+ console.log(` ${warn} Codex: $${codexEnvVar} differs from your active key ${dim("(rotate or re-run setup so hooks and MCP match)")}`);
189
+ }
190
+ }
161
191
  }
162
192
  const codexNotifyPath = codexConfig.match(/["']([^"']*pushary-codex[^"']*)["']/)?.[1] ?? null;
163
193
  const hooksInstalled = !!codexHooksJson && hasCodexHooks(codexHooksJson);
@@ -169,18 +199,16 @@ var main = async () => {
169
199
  const resolves = commandResolves(hookCommand);
170
200
  check(resolves, "Codex: hook command resolves", resolves ? hookCommand : `not on PATH: ${hookCommand}`);
171
201
  }
172
- let hooksFeatureDisabled = false;
173
- try {
174
- const parsed = parseTOML(codexConfig);
175
- const features = parsed.features;
176
- hooksFeatureDisabled = !!features && typeof features === "object" && features.hooks === false;
177
- } catch {
178
- }
202
+ const features = codexParsed.features;
203
+ const hooksFeatureDisabled = !!features && typeof features === "object" && features.hooks === false;
179
204
  check(!hooksFeatureDisabled, "Codex: hooks feature enabled", hooksFeatureDisabled ? "[features].hooks = false in config.toml" : void 0);
180
205
  if (codexNotifyPath) {
181
206
  console.log(` ${warn} Codex: stale legacy notify entry ${dim("(double-push risk, re-run setup to remove it)")}`);
182
207
  }
183
- console.log(` ${warn} Codex: trust the hooks inside Codex ${dim("(type /hooks in Codex and trust them, once; cannot be checked from here)")}`);
208
+ if (hookCommand) {
209
+ const untrusted = untrustedCodexHookEvents(codexParsed, codexHooksPath, hookCommand);
210
+ check(untrusted.length === 0, "Codex: hooks trusted", untrusted.length === 0 ? "all events trusted" : `untrusted (${untrusted.join(", ")}) \u2014 type /hooks in Codex and trust them, once`);
211
+ }
184
212
  } else {
185
213
  check(!!codexNotifyPath, "Codex: notify handler configured (deprecated)", codexNotifyPath ? "upgrade Codex and re-run setup for native hooks" : "missing, re-run setup");
186
214
  if (codexNotifyPath) {
@@ -203,17 +231,32 @@ var main = async () => {
203
231
  if (geminiPushary) {
204
232
  check(typeof geminiPushary.httpUrl === "string", "Gemini CLI: MCP transport", geminiPushary.httpUrl ? String(geminiPushary.httpUrl) : "missing \u2014 add httpUrl");
205
233
  check(geminiPushary.trust === true, "Gemini CLI: tools auto-allowed", geminiPushary.trust === true ? "trust: true" : "missing \u2014 MCP calls will prompt for confirmation");
234
+ const geminiAuth = geminiPushary.headers?.Authorization;
235
+ if (typeof geminiAuth === "string") {
236
+ if (geminiAuth.includes("${PUSHARY_API_KEY}")) {
237
+ check(false, "Gemini CLI: API key embedded", "header has an unexpanded ${PUSHARY_API_KEY} \u2014 re-run setup to embed the key");
238
+ } else if (apiKey && geminiAuth !== `Bearer ${apiKey}`) {
239
+ check(false, "Gemini CLI: API key matches active key", "embedded key differs from your active key (rotated?) \u2014 re-run setup");
240
+ } else {
241
+ check(true, "Gemini CLI: API key embedded");
242
+ }
243
+ }
206
244
  }
207
245
  const geminiHooksInstalled = hasGeminiHooks(geminiSettings);
208
246
  if (geminiHooksInstalled) {
209
247
  const missingEvents = missingGeminiHookEvents(geminiSettings);
210
248
  check(missingEvents.length === 0, "Gemini CLI: native hooks installed", missingEvents.length === 0 ? "all 5 events" : `missing ${missingEvents.join(", ")}, re-run setup`);
211
249
  const geminiHooks = geminiSettings.hooks;
212
- const hookCommand = extractHookCommand(geminiHooks?.BeforeTool, GEMINI_HOOK_BINARY);
250
+ const hookCommand = extractHookCommand(geminiHooks?.BeforeTool, GEMINI_HOOK_BINARY) ?? extractHookCommand(geminiHooks?.AfterTool, GEMINI_HOOK_BINARY) ?? extractHookCommand(geminiHooks?.SessionStart, GEMINI_HOOK_BINARY);
213
251
  if (hookCommand) {
214
252
  const resolves = commandResolves(hookCommand);
215
253
  check(resolves, "Gemini CLI: hook command resolves", resolves ? hookCommand : `not on PATH: ${hookCommand}`);
216
254
  }
255
+ const geminiTimeout = extractHookTimeout(geminiHooks?.BeforeTool, GEMINI_HOOK_BINARY);
256
+ if (typeof geminiTimeout === "number") {
257
+ const ok = geminiTimeout >= 3e4;
258
+ check(ok, "Gemini CLI: hook timeout", ok ? `${geminiTimeout}ms` : `${geminiTimeout}ms too short (Gemini timeouts are milliseconds) \u2014 re-run setup`);
259
+ }
217
260
  } else {
218
261
  check(false, "Gemini CLI: native hooks installed", "no Pushary hooks in ~/.gemini/settings.json \u2014 re-run setup");
219
262
  }
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ denyReasonFrom
4
+ } from "../chunk-N7VXDBQU.js";
2
5
  import {
3
6
  handlePostToolUse,
4
7
  handleStop,
@@ -64,7 +67,6 @@ var geminiTimeoutDecision = (timeoutAction, denyReason = "No response within tim
64
67
  var KILL_REASON = "Stopped by user: this agent was halted from Pushary";
65
68
  var MAX_WAIT_SECONDS = 170;
66
69
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
67
- var denyReasonFrom = (value) => value && value !== "no" && value !== "yes" ? `Denied from your phone: ${value}` : "Denied via push notification";
68
70
  var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
69
71
  while (Date.now() < deadlineMs) {
70
72
  const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handlePreToolUse
4
- } from "../chunk-SDREQWNI.js";
4
+ } from "../chunk-FXYTRZHC.js";
5
+ import "../chunk-N7VXDBQU.js";
5
6
  import "../chunk-ACE77TKQ.js";
6
7
  import "../chunk-USUCPCUC.js";
7
8
  import "../chunk-DWED7BS3.js";
@@ -14,7 +14,7 @@ import {
14
14
  npmErrorMessage,
15
15
  renderAgentInstructions,
16
16
  writeInstructionBlock
17
- } from "../chunk-UIBTFZUD.js";
17
+ } from "../chunk-BHAMEPOP.js";
18
18
  import {
19
19
  isValidApiKey
20
20
  } from "../chunk-USUCPCUC.js";
@@ -541,7 +541,7 @@ var setupHermes = async (_apiKey) => {
541
541
  };
542
542
  var CODEX_HOOKS_JSON = join(CODEX_HOME, "hooks.json");
543
543
  var CODEX_HOOKS_MIN_VERSION = [0, 122, 0];
544
- var CODEX_TRUST_VERIFIED_MAX = [0, 138, 0];
544
+ var CODEX_TRUST_VERIFIED_MAX = [0, 142, 2];
545
545
  var parseCodexVersion = (raw) => {
546
546
  const match = raw.match(/(\d+)\.(\d+)\.(\d+)/);
547
547
  if (!match) return null;
@@ -0,0 +1,323 @@
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 untrustedCodexHookEvents = (config, hooksJsonPath, command) => {
100
+ const state = asRecord(asRecord(config.hooks)?.state);
101
+ return CODEX_HOOK_EVENTS.filter((definition) => {
102
+ const entry = asRecord(state?.[codexHookStateKey(hooksJsonPath, definition.event)]);
103
+ const stored = entry?.trusted_hash;
104
+ return stored !== codexHookTrustHash(definition, command);
105
+ }).map((definition) => definition.event);
106
+ };
107
+ var addCodexHookTrust = (config, hooksJsonPath, command) => {
108
+ const hooks = ensureRecord(config, "hooks");
109
+ const state = ensureRecord(hooks, "state");
110
+ for (const definition of CODEX_HOOK_EVENTS) {
111
+ const key = codexHookStateKey(hooksJsonPath, definition.event);
112
+ const existing = asRecord(state[key]) ?? {};
113
+ state[key] = { ...existing, trusted_hash: codexHookTrustHash(definition, command) };
114
+ }
115
+ };
116
+
117
+ // src/gemini-config.ts
118
+ var GEMINI_HOOK_BINARY = "pushary-gemini-hook";
119
+ var GEMINI_MCP_URL = "https://pushary.com/api/mcp/mcp";
120
+ var GEMINI_HOOK_EVENTS = [
121
+ { event: "BeforeTool", matcher: "run_shell_command|write_file|replace", timeoutMs: 18e4 },
122
+ { event: "AfterTool", matcher: "run_shell_command|write_file|replace", timeoutMs: 1e4 },
123
+ { event: "BeforeAgent", timeoutMs: 1e4 },
124
+ { event: "SessionStart", timeoutMs: 1e4 },
125
+ { event: "SessionEnd", timeoutMs: 1e4 }
126
+ ];
127
+ var asRecord2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
128
+ var ensureRecord2 = (target, key) => {
129
+ const existing = asRecord2(target[key]);
130
+ if (existing) return existing;
131
+ const created = {};
132
+ target[key] = created;
133
+ return created;
134
+ };
135
+ var isPusharyGeminiHook = (entry) => {
136
+ const hooks = asRecord2(entry)?.hooks;
137
+ if (!Array.isArray(hooks)) return false;
138
+ return hooks.some((hook) => String(asRecord2(hook)?.command ?? "").includes(GEMINI_HOOK_BINARY));
139
+ };
140
+ var addGeminiMcpServer = (settings, apiKey) => {
141
+ const mcpServers = ensureRecord2(settings, "mcpServers");
142
+ mcpServers.pushary = {
143
+ httpUrl: GEMINI_MCP_URL,
144
+ headers: { Authorization: `Bearer ${apiKey}` },
145
+ trust: true
146
+ };
147
+ };
148
+ var addGeminiHooks = (settings, command) => {
149
+ const hooks = ensureRecord2(settings, "hooks");
150
+ for (const definition of GEMINI_HOOK_EVENTS) {
151
+ const existing = Array.isArray(hooks[definition.event]) ? hooks[definition.event] : [];
152
+ const entries = existing.filter((entry) => !isPusharyGeminiHook(entry));
153
+ entries.push({
154
+ ...definition.matcher ? { matcher: definition.matcher } : {},
155
+ hooks: [{
156
+ name: "pushary",
157
+ type: "command",
158
+ command,
159
+ timeout: definition.timeoutMs
160
+ }]
161
+ });
162
+ hooks[definition.event] = entries;
163
+ }
164
+ };
165
+ var removeGeminiHooks = (settings) => {
166
+ const hooks = asRecord2(settings.hooks);
167
+ if (!hooks) return false;
168
+ let changed = false;
169
+ for (const definition of GEMINI_HOOK_EVENTS) {
170
+ const entries = hooks[definition.event];
171
+ if (!Array.isArray(entries)) continue;
172
+ const filtered = entries.filter((entry) => !isPusharyGeminiHook(entry));
173
+ if (filtered.length !== entries.length) {
174
+ if (filtered.length === 0) {
175
+ delete hooks[definition.event];
176
+ } else {
177
+ hooks[definition.event] = filtered;
178
+ }
179
+ changed = true;
180
+ }
181
+ }
182
+ if (Object.keys(hooks).length === 0) delete settings.hooks;
183
+ return changed;
184
+ };
185
+ var removeGeminiMcpServer = (settings) => {
186
+ const mcpServers = asRecord2(settings.mcpServers);
187
+ if (!mcpServers?.pushary) return false;
188
+ delete mcpServers.pushary;
189
+ if (Object.keys(mcpServers).length === 0) delete settings.mcpServers;
190
+ return true;
191
+ };
192
+ var removeGeminiSettings = (settings) => {
193
+ const mcpRemoved = removeGeminiMcpServer(settings);
194
+ const hooksRemoved = removeGeminiHooks(settings);
195
+ return mcpRemoved || hooksRemoved;
196
+ };
197
+ var hasGeminiHooks = (settings) => {
198
+ const hooks = asRecord2(settings.hooks);
199
+ if (!hooks) return false;
200
+ return GEMINI_HOOK_EVENTS.some((definition) => {
201
+ const entries = hooks[definition.event];
202
+ return Array.isArray(entries) && entries.some(isPusharyGeminiHook);
203
+ });
204
+ };
205
+ var missingGeminiHookEvents = (settings) => {
206
+ const hooks = asRecord2(settings.hooks);
207
+ return GEMINI_HOOK_EVENTS.filter((definition) => {
208
+ const entries = hooks?.[definition.event];
209
+ return !Array.isArray(entries) || !entries.some(isPusharyGeminiHook);
210
+ }).map((definition) => definition.event);
211
+ };
212
+
213
+ // src/instruction-file.ts
214
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "fs";
215
+ import { dirname } from "path";
216
+ var PUSHARY_BEGIN = "<!-- BEGIN PUSHARY (managed by @pushary/agent-hooks; do not edit this block) -->";
217
+ var PUSHARY_END = "<!-- END PUSHARY -->";
218
+ var instructionBody = (label) => `## Pushary notifications and approvals
219
+
220
+ You have Pushary MCP tools that reach the user on their phone. Use them proactively. Do not wait for the user to ask.
221
+
222
+ - 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.
223
+ - 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.
224
+ - 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.
225
+ - When a task that took several steps finishes, call \`send_notification\` so the user knows it is done.
226
+ - Use \`cancel_question\` to retract a pending question once it is no longer needed.
227
+
228
+ 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.`;
229
+ var renderAgentInstructions = (label) => instructionBody(label);
230
+ var wrap = (body) => `${PUSHARY_BEGIN}
231
+ ${body}
232
+ ${PUSHARY_END}`;
233
+ var writeInstructionBlock = (filePath, body) => {
234
+ const dir = dirname(filePath);
235
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
236
+ let existing = "";
237
+ try {
238
+ existing = readFileSync(filePath, "utf-8");
239
+ } catch {
240
+ }
241
+ const block = wrap(body);
242
+ const start = existing.indexOf(PUSHARY_BEGIN);
243
+ const end = existing.indexOf(PUSHARY_END);
244
+ let next;
245
+ if (start !== -1 && end !== -1 && end > start) {
246
+ next = existing.slice(0, start) + block + existing.slice(end + PUSHARY_END.length);
247
+ } else {
248
+ const prefix = existing.trim() ? existing.replace(/\s*$/, "") + "\n\n" : "";
249
+ next = prefix + block + "\n";
250
+ }
251
+ writeFileSync(filePath, next, "utf-8");
252
+ };
253
+ var removeInstructionBlock = (filePath) => {
254
+ let existing = "";
255
+ try {
256
+ existing = readFileSync(filePath, "utf-8");
257
+ } catch {
258
+ return false;
259
+ }
260
+ const start = existing.indexOf(PUSHARY_BEGIN);
261
+ const end = existing.indexOf(PUSHARY_END);
262
+ if (start === -1 || end === -1 || end < start) return false;
263
+ const remaining = (existing.slice(0, start) + existing.slice(end + PUSHARY_END.length)).trim();
264
+ if (remaining === "") {
265
+ rmSync(filePath, { force: true });
266
+ } else {
267
+ writeFileSync(filePath, remaining + "\n", "utf-8");
268
+ }
269
+ return true;
270
+ };
271
+ var hasInstructionBlock = (filePath) => {
272
+ try {
273
+ return readFileSync(filePath, "utf-8").includes(PUSHARY_BEGIN);
274
+ } catch {
275
+ return false;
276
+ }
277
+ };
278
+
279
+ // src/npm.ts
280
+ import { execSync } from "child_process";
281
+ var cleanNpmEnv = () => {
282
+ const env = {};
283
+ for (const [key, value] of Object.entries(process.env)) {
284
+ if (key.toLowerCase().startsWith("npm_config_workspace")) continue;
285
+ env[key] = value;
286
+ }
287
+ return env;
288
+ };
289
+ var npmErrorMessage = (err) => {
290
+ const e = err;
291
+ const text = [e?.stderr, e?.stdout].map((part) => part ? part.toString() : "").join("\n");
292
+ 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));
293
+ return line || e?.message || String(err);
294
+ };
295
+ var execNpm = (args, options = {}) => {
296
+ return execSync(`npm ${args}`, {
297
+ timeout: 12e4,
298
+ stdio: "pipe",
299
+ ...options,
300
+ env: { ...cleanNpmEnv(), ...options.env ?? {} }
301
+ });
302
+ };
303
+
304
+ export {
305
+ addCodexHooks,
306
+ removeCodexHooks,
307
+ hasCodexHooks,
308
+ missingCodexHookEvents,
309
+ untrustedCodexHookEvents,
310
+ addCodexHookTrust,
311
+ GEMINI_HOOK_BINARY,
312
+ addGeminiMcpServer,
313
+ addGeminiHooks,
314
+ removeGeminiSettings,
315
+ hasGeminiHooks,
316
+ missingGeminiHookEvents,
317
+ renderAgentInstructions,
318
+ writeInstructionBlock,
319
+ removeInstructionBlock,
320
+ hasInstructionBlock,
321
+ npmErrorMessage,
322
+ execNpm
323
+ };
@@ -0,0 +1,177 @@
1
+ import {
2
+ denyReasonFrom
3
+ } from "./chunk-N7VXDBQU.js";
4
+ import {
5
+ DEFAULT_SESSION,
6
+ askUser,
7
+ deriveToolTarget,
8
+ describeToolCall,
9
+ fetchModeState,
10
+ getMachineId,
11
+ getPolicy,
12
+ resolvePolicy,
13
+ savePendingQuestion,
14
+ sendNotification,
15
+ waitForAnswer
16
+ } from "./chunk-ACE77TKQ.js";
17
+ import {
18
+ getApiKey
19
+ } from "./chunk-NKXSILEW.js";
20
+
21
+ // src/hook.ts
22
+ import { basename } from "path";
23
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ var allow = () => ({
25
+ hookSpecificOutput: {
26
+ hookEventName: "PreToolUse",
27
+ permissionDecision: "allow"
28
+ }
29
+ });
30
+ var deny = (reason) => ({
31
+ hookSpecificOutput: {
32
+ hookEventName: "PreToolUse",
33
+ permissionDecision: "deny",
34
+ permissionDecisionReason: reason
35
+ }
36
+ });
37
+ var ask = (reason) => ({
38
+ hookSpecificOutput: {
39
+ hookEventName: "PreToolUse",
40
+ permissionDecision: "ask",
41
+ ...reason ? { permissionDecisionReason: reason } : {}
42
+ }
43
+ });
44
+ var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
45
+ while (Date.now() < deadlineMs) {
46
+ const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
47
+ let answer;
48
+ try {
49
+ answer = await waitForAnswer(apiKey, correlationId, remaining);
50
+ } catch {
51
+ if (Date.now() + pollInterval >= deadlineMs) break;
52
+ await sleep(pollInterval);
53
+ continue;
54
+ }
55
+ if (answer.answered) return answer;
56
+ if (Date.now() + pollInterval >= deadlineMs) break;
57
+ await sleep(pollInterval);
58
+ }
59
+ return { answered: false };
60
+ };
61
+ var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
62
+ let result;
63
+ try {
64
+ result = await askUser(apiKey, {
65
+ question: `Allow ${description}?`,
66
+ type: "confirm",
67
+ context: `Agent wants to run this in ${projectName}`,
68
+ agentName: `Claude Code - ${projectName}`,
69
+ sessionId,
70
+ machineId,
71
+ toolName,
72
+ toolTarget
73
+ });
74
+ } catch {
75
+ switch (timeoutAction) {
76
+ case "approve":
77
+ return allow();
78
+ case "deny":
79
+ return deny("Push notification failed, denying per policy");
80
+ default:
81
+ return ask("Push notification failed, asking in terminal");
82
+ }
83
+ }
84
+ const deadline = Date.now() + timeoutSeconds * 1e3;
85
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
86
+ if (answer.answered) {
87
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
88
+ }
89
+ switch (timeoutAction) {
90
+ case "approve":
91
+ return allow();
92
+ case "deny":
93
+ return deny("No response within timeout");
94
+ default:
95
+ return ask("No push response, asking in terminal");
96
+ }
97
+ };
98
+ var handleTerminalOnly = () => {
99
+ return ask();
100
+ };
101
+ var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
102
+ let result;
103
+ try {
104
+ result = await askUser(apiKey, {
105
+ question: `Allow ${description}?`,
106
+ type: "confirm",
107
+ context: `Agent wants to run this in ${projectName}`,
108
+ agentName: `Claude Code - ${projectName}`,
109
+ sessionId,
110
+ machineId,
111
+ toolName,
112
+ toolTarget
113
+ });
114
+ } catch {
115
+ return ask("Push notification failed, asking in terminal");
116
+ }
117
+ const deadline = Date.now() + pushFirstSeconds * 1e3;
118
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
119
+ if (answer.answered) {
120
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
121
+ }
122
+ savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
123
+ return ask("Sent as push notification. You can also approve here.");
124
+ };
125
+ var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
126
+ try {
127
+ await sendNotification(apiKey, {
128
+ title: "Agent needs approval",
129
+ body: description,
130
+ agentName: `Claude Code - ${projectName}`,
131
+ sessionId,
132
+ machineId
133
+ });
134
+ } catch {
135
+ }
136
+ return ask();
137
+ };
138
+ var handlePreToolUse = async (input) => {
139
+ try {
140
+ const apiKey = getApiKey();
141
+ const modeState = await fetchModeState(apiKey, input.session_id);
142
+ const policy = await getPolicy(apiKey, modeState.policyVersion);
143
+ if (modeState.kill) {
144
+ return deny("Stopped by user \u2014 this agent was halted from Pushary");
145
+ }
146
+ const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
147
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
148
+ return allow();
149
+ }
150
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
151
+ return deny(`Denied by policy for ${toolPolicy.tool}`);
152
+ }
153
+ const description = describeToolCall(input.tool_name, input.tool_input, "hook");
154
+ const projectName = basename(input.cwd ?? process.cwd());
155
+ const sessionId = input.session_id;
156
+ const machineId = getMachineId();
157
+ const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
158
+ switch (toolPolicy.mode) {
159
+ case "push_only":
160
+ return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
161
+ case "terminal_only":
162
+ return handleTerminalOnly();
163
+ case "push_first":
164
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
165
+ case "notify_only":
166
+ return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
167
+ default:
168
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
169
+ }
170
+ } catch {
171
+ return ask("Pushary unavailable, falling back to terminal approval");
172
+ }
173
+ };
174
+
175
+ export {
176
+ handlePreToolUse
177
+ };
@@ -0,0 +1,6 @@
1
+ // src/answer.ts
2
+ var denyReasonFrom = (value) => value && value !== "no" && value !== "yes" ? `Denied from your phone: ${value}` : "Denied via push notification";
3
+
4
+ export {
5
+ denyReasonFrom
6
+ };
package/dist/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  handlePreToolUse
3
- } from "../chunk-SDREQWNI.js";
3
+ } from "../chunk-FXYTRZHC.js";
4
+ import "../chunk-N7VXDBQU.js";
4
5
  import {
5
6
  handleNotification,
6
7
  handlePostToolUse,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/agent-hooks",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Permission hooks for AI coding agents: route tool approvals through Pushary push notifications",
5
5
  "author": "Pushary <business@pushary.com>",
6
6
  "homepage": "https://pushary.com",