@pushary/agent-hooks 0.19.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.
@@ -6,8 +6,9 @@ import {
6
6
  import {
7
7
  execNpm,
8
8
  removeCodexHooks,
9
- removeGeminiSettings
10
- } from "../chunk-ZWBS3T7Q.js";
9
+ removeGeminiSettings,
10
+ removeInstructionBlock
11
+ } from "../chunk-BHAMEPOP.js";
11
12
 
12
13
  // bin/pushary-clean.ts
13
14
  import { existsSync, readFileSync, writeFileSync, rmSync } from "fs";
@@ -135,6 +136,19 @@ var main = async () => {
135
136
  } else {
136
137
  console.log(` ${skip} Codex hooks ${dim("(not found)")}`);
137
138
  }
139
+ const codexAgentsMd = join(homedir(), ".codex", "AGENTS.md");
140
+ if (removeInstructionBlock(codexAgentsMd)) {
141
+ console.log(` ${check} Codex AGENTS.md ${dim("(removed Pushary block)")}`);
142
+ } else {
143
+ console.log(` ${skip} Codex AGENTS.md ${dim("(no pushary block)")}`);
144
+ }
145
+ const codexSkillDir = join(homedir(), ".codex", "skills", "pushary");
146
+ if (existsSync(codexSkillDir)) {
147
+ rmSync(codexSkillDir, { recursive: true });
148
+ console.log(` ${check} Codex skill directory ${dim("(removed)")}`);
149
+ } else {
150
+ console.log(` ${skip} Codex skill directory ${dim("(not found)")}`);
151
+ }
138
152
  const geminiSettingsPath = join(homedir(), ".gemini", "settings.json");
139
153
  const geminiSettings = readJson(geminiSettingsPath);
140
154
  if (geminiSettings) {
@@ -147,6 +161,12 @@ var main = async () => {
147
161
  } else {
148
162
  console.log(` ${skip} Gemini CLI settings ${dim("(not found)")}`);
149
163
  }
164
+ const geminiMd = join(homedir(), ".gemini", "GEMINI.md");
165
+ if (removeInstructionBlock(geminiMd)) {
166
+ console.log(` ${check} Gemini GEMINI.md ${dim("(removed Pushary block)")}`);
167
+ } else {
168
+ console.log(` ${skip} Gemini GEMINI.md ${dim("(no pushary block)")}`);
169
+ }
150
170
  for (const shellFile of SHELL_FILES) {
151
171
  try {
152
172
  const content = readFileSync(shellFile, "utf-8");
@@ -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();
@@ -4,9 +4,11 @@ import {
4
4
  execNpm,
5
5
  hasCodexHooks,
6
6
  hasGeminiHooks,
7
+ hasInstructionBlock,
7
8
  missingCodexHookEvents,
8
- missingGeminiHookEvents
9
- } from "../chunk-ZWBS3T7Q.js";
9
+ missingGeminiHookEvents,
10
+ untrustedCodexHookEvents
11
+ } from "../chunk-BHAMEPOP.js";
10
12
  import {
11
13
  callMcpTool,
12
14
  sendMcpRequest
@@ -61,6 +63,20 @@ var extractHookCommand = (entries, needle) => {
61
63
  }
62
64
  return null;
63
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
+ };
64
80
  var results = [];
65
81
  var check = (passed, label, detail) => {
66
82
  results.push({ passed, label, detail });
@@ -148,15 +164,30 @@ var main = async () => {
148
164
  const codexHooksJson = readJson(codexHooksPath);
149
165
  if (existsSync(codexConfigPath) || codexHooksJson) {
150
166
  const codexConfig = existsSync(codexConfigPath) ? readFileSync(codexConfigPath, "utf-8") : "";
151
- const hasPusharyMcp = codexConfig.includes("[mcp_servers.pushary]");
152
- check(hasPusharyMcp, "Codex: MCP server configured");
153
- if (hasPusharyMcp) {
154
- const hasAutoApprove = codexConfig.includes('default_tools_approval_mode = "approve"');
155
- check(hasAutoApprove, "Codex: tools auto-allowed", hasAutoApprove ? 'default_tools_approval_mode = "approve"' : "missing \u2014 MCP calls will prompt for approval");
156
- const hasPerToolOverrides = /\[mcp_servers\.pushary\.tools\./.test(codexConfig);
157
- 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") {
158
182
  console.log(` ${warn} Codex: per-tool approval overrides detected ${dim("(redundant with default_tools_approval_mode)")}`);
159
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
+ }
160
191
  }
161
192
  const codexNotifyPath = codexConfig.match(/["']([^"']*pushary-codex[^"']*)["']/)?.[1] ?? null;
162
193
  const hooksInstalled = !!codexHooksJson && hasCodexHooks(codexHooksJson);
@@ -168,18 +199,16 @@ var main = async () => {
168
199
  const resolves = commandResolves(hookCommand);
169
200
  check(resolves, "Codex: hook command resolves", resolves ? hookCommand : `not on PATH: ${hookCommand}`);
170
201
  }
171
- let hooksFeatureDisabled = false;
172
- try {
173
- const parsed = parseTOML(codexConfig);
174
- const features = parsed.features;
175
- hooksFeatureDisabled = !!features && typeof features === "object" && features.hooks === false;
176
- } catch {
177
- }
202
+ const features = codexParsed.features;
203
+ const hooksFeatureDisabled = !!features && typeof features === "object" && features.hooks === false;
178
204
  check(!hooksFeatureDisabled, "Codex: hooks feature enabled", hooksFeatureDisabled ? "[features].hooks = false in config.toml" : void 0);
179
205
  if (codexNotifyPath) {
180
206
  console.log(` ${warn} Codex: stale legacy notify entry ${dim("(double-push risk, re-run setup to remove it)")}`);
181
207
  }
182
- 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
+ }
183
212
  } else {
184
213
  check(!!codexNotifyPath, "Codex: notify handler configured (deprecated)", codexNotifyPath ? "upgrade Codex and re-run setup for native hooks" : "missing, re-run setup");
185
214
  if (codexNotifyPath) {
@@ -189,6 +218,9 @@ var main = async () => {
189
218
  }
190
219
  const codexSkillPath = join(homedir(), ".codex", "skills", "pushary", "SKILL.md");
191
220
  check(existsSync(codexSkillPath), "Codex: skill installed");
221
+ const codexAgentsMd = join(homedir(), ".codex", "AGENTS.md");
222
+ const hasCodexInstructions = hasInstructionBlock(codexAgentsMd);
223
+ check(hasCodexInstructions, "Codex: proactive instructions (AGENTS.md)", hasCodexInstructions ? codexAgentsMd : "missing \u2014 re-run setup so Codex asks via push, not the terminal");
192
224
  }
193
225
  const geminiSettingsPath = join(homedir(), ".gemini", "settings.json");
194
226
  const geminiSettings = readJson(geminiSettingsPath);
@@ -199,20 +231,38 @@ var main = async () => {
199
231
  if (geminiPushary) {
200
232
  check(typeof geminiPushary.httpUrl === "string", "Gemini CLI: MCP transport", geminiPushary.httpUrl ? String(geminiPushary.httpUrl) : "missing \u2014 add httpUrl");
201
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
+ }
202
244
  }
203
245
  const geminiHooksInstalled = hasGeminiHooks(geminiSettings);
204
246
  if (geminiHooksInstalled) {
205
247
  const missingEvents = missingGeminiHookEvents(geminiSettings);
206
248
  check(missingEvents.length === 0, "Gemini CLI: native hooks installed", missingEvents.length === 0 ? "all 5 events" : `missing ${missingEvents.join(", ")}, re-run setup`);
207
249
  const geminiHooks = geminiSettings.hooks;
208
- 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);
209
251
  if (hookCommand) {
210
252
  const resolves = commandResolves(hookCommand);
211
253
  check(resolves, "Gemini CLI: hook command resolves", resolves ? hookCommand : `not on PATH: ${hookCommand}`);
212
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
+ }
213
260
  } else {
214
261
  check(false, "Gemini CLI: native hooks installed", "no Pushary hooks in ~/.gemini/settings.json \u2014 re-run setup");
215
262
  }
263
+ const geminiMd = join(homedir(), ".gemini", "GEMINI.md");
264
+ const hasGeminiInstructions = hasInstructionBlock(geminiMd);
265
+ check(hasGeminiInstructions, "Gemini CLI: proactive instructions (GEMINI.md)", hasGeminiInstructions ? geminiMd : "missing \u2014 re-run setup so Gemini asks via push, not the terminal");
216
266
  }
217
267
  const cursorPluginDir = join(homedir(), ".cursor", "plugins", "local", "pushary");
218
268
  if (existsSync(cursorPluginDir)) {
@@ -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";
@@ -11,8 +11,10 @@ import {
11
11
  addGeminiHooks,
12
12
  addGeminiMcpServer,
13
13
  execNpm,
14
- npmErrorMessage
15
- } from "../chunk-ZWBS3T7Q.js";
14
+ npmErrorMessage,
15
+ renderAgentInstructions,
16
+ writeInstructionBlock
17
+ } from "../chunk-BHAMEPOP.js";
16
18
  import {
17
19
  isValidApiKey
18
20
  } from "../chunk-USUCPCUC.js";
@@ -303,7 +305,9 @@ var CURSOR_USER_HOOKS = join(homedir(), ".cursor", "hooks.json");
303
305
  var CLAUDE_SKILL_DIR = join(homedir(), ".claude", "skills", "pushary");
304
306
  var CODEX_HOME = process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
305
307
  var CODEX_SKILL_DIR = join(CODEX_HOME, "skills", "pushary");
308
+ var CODEX_AGENTS_MD = join(CODEX_HOME, "AGENTS.md");
306
309
  var GEMINI_SETTINGS = join(homedir(), ".gemini", "settings.json");
310
+ var GEMINI_MD = join(homedir(), ".gemini", "GEMINI.md");
307
311
  var PUSHARY_CONFIG_DIR = join(homedir(), ".pushary");
308
312
  var PUSHARY_CONFIG_FILE = join(PUSHARY_CONFIG_DIR, "config.json");
309
313
  var SHELL_FILES = [".zshrc", ".zprofile", ".bashrc", ".bash_profile"].map((f) => join(homedir(), f));
@@ -537,7 +541,7 @@ var setupHermes = async (_apiKey) => {
537
541
  };
538
542
  var CODEX_HOOKS_JSON = join(CODEX_HOME, "hooks.json");
539
543
  var CODEX_HOOKS_MIN_VERSION = [0, 122, 0];
540
- var CODEX_TRUST_VERIFIED_MAX = [0, 138, 0];
544
+ var CODEX_TRUST_VERIFIED_MAX = [0, 142, 2];
541
545
  var parseCodexVersion = (raw) => {
542
546
  const match = raw.match(/(\d+)\.(\d+)\.(\d+)/);
543
547
  if (!match) return null;
@@ -667,9 +671,13 @@ var setupCodex = async (_apiKey) => {
667
671
  });
668
672
  }
669
673
  await installSkillToDir(CODEX_SKILL_DIR, "Installing Pushary skill");
674
+ await spinner("Teaching Codex to ask via push (~/.codex/AGENTS.md)", async () => {
675
+ writeInstructionBlock(CODEX_AGENTS_MD, renderAgentInstructions("Codex"));
676
+ });
670
677
  console.log();
671
678
  console.log(` ${dim2("What this configured:")}`);
672
679
  console.log(` ${dim2("\u2022")} MCP server: Codex can send notifications and ask questions`);
680
+ console.log(` ${dim2("\u2022")} Proactive instructions: ~/.codex/AGENTS.md tells Codex to ask via push, not the terminal`);
673
681
  console.log(` ${dim2("\u2022")} Auto-allowed tools: no permission prompts for Pushary MCP calls`);
674
682
  if (hooksSupported) {
675
683
  console.log(` ${dim2("\u2022")} Native hooks: phone approvals, policy enforcement, kill switch, session tracking`);
@@ -829,9 +837,13 @@ var setupGemini = async (apiKey) => {
829
837
  await spinner(`Writing ${GEMINI_SETTINGS}`, async () => {
830
838
  writeJson(GEMINI_SETTINGS, settings);
831
839
  });
840
+ await spinner("Teaching Gemini to ask via push (~/.gemini/GEMINI.md)", async () => {
841
+ writeInstructionBlock(GEMINI_MD, renderAgentInstructions("Gemini"));
842
+ });
832
843
  console.log();
833
844
  console.log(` ${dim2("What this configured:")}`);
834
845
  console.log(` ${dim2("\u2022")} MCP server: Gemini can send notifications and ask questions`);
846
+ console.log(` ${dim2("\u2022")} Proactive instructions: ~/.gemini/GEMINI.md tells Gemini to ask via push, not the terminal`);
835
847
  console.log(` ${dim2("\u2022")} Hooks: phone approvals, policy enforcement, kill switch, session tracking`);
836
848
  console.log(` ${dim2("\u2022")} Gate covers ${bold2("run_shell_command")}, ${bold2("write_file")}, and ${bold2("replace")}`);
837
849
  console.log(` ${dim2("\u2022")} Auto-allowed tools: Pushary MCP calls run without a confirmation prompt`);
@@ -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
+ };
@@ -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
+ };
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.19.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",
@@ -38,7 +38,7 @@
38
38
  "scripts": {
39
39
  "build": "node scripts/bundle-plugin.mjs && tsup",
40
40
  "dev": "tsup --watch",
41
- "test": "bun test src/api.test.ts && bun test src/claude-config.test.ts && bun test src/config.test.ts && bun test src/mcp-http.test.ts && bun test src/retry.test.ts && bun test src/usage.test.ts && bun test src/validate.test.ts && bun test src/policy.test.ts && bun test src/npm.test.ts && bun test src/identity.test.ts && bun test src/pending.test.ts && bun test src/events.test.ts && bun test src/describe.test.ts && bun test src/suggestions.test.ts && bun test src/safe-commands.test.ts && bun test src/hook.test.ts && bun test src/codex-adapter.test.ts && bun test src/codex-config.test.ts && bun test src/gemini-adapter.test.ts && bun test src/gemini-config.test.ts && bun test src/pairing.test.ts"
41
+ "test": "bun test src/api.test.ts && bun test src/claude-config.test.ts && bun test src/config.test.ts && bun test src/mcp-http.test.ts && bun test src/retry.test.ts && bun test src/usage.test.ts && bun test src/validate.test.ts && bun test src/policy.test.ts && bun test src/npm.test.ts && bun test src/identity.test.ts && bun test src/pending.test.ts && bun test src/events.test.ts && bun test src/describe.test.ts && bun test src/suggestions.test.ts && bun test src/safe-commands.test.ts && bun test src/hook.test.ts && bun test src/codex-adapter.test.ts && bun test src/codex-config.test.ts && bun test src/gemini-adapter.test.ts && bun test src/gemini-config.test.ts && bun test src/instruction-file.test.ts && bun test src/pairing.test.ts"
42
42
  },
43
43
  "dependencies": {
44
44
  "@inquirer/prompts": "^8.4.2",