@pushary/agent-hooks 0.25.0 → 0.26.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 (94) hide show
  1. package/dist/bin/pushary-clean.js +1 -1
  2. package/dist/bin/pushary-codex-hook.js +1 -1
  3. package/dist/bin/pushary-codex.js +1 -1
  4. package/dist/bin/pushary-doctor.js +21 -9
  5. package/dist/bin/pushary-gemini-hook.js +1 -1
  6. package/dist/bin/pushary-hook.js +2 -2
  7. package/dist/bin/pushary-post-hook.js +1 -1
  8. package/dist/bin/pushary-prompt-hook.js +1 -1
  9. package/dist/bin/pushary-setup.js +7 -19
  10. package/dist/bin/pushary-stop-hook.js +1 -1
  11. package/dist/{chunk-GYPPVD3P.js → chunk-A7DQCA2N.js} +1 -1
  12. package/dist/{chunk-O2QL6U6G.js → chunk-SA4BDS7T.js} +1 -1
  13. package/dist/{chunk-JPRRYC5X.js → chunk-SLX4AONG.js} +25 -0
  14. package/dist/src/index.js +2 -2
  15. package/package.json +1 -1
  16. package/dist/chunk-22CV7V7A.js +0 -38
  17. package/dist/chunk-2BE2IPMO.js +0 -315
  18. package/dist/chunk-2CRLBMOX.js +0 -244
  19. package/dist/chunk-2HMNOZPY.js +0 -109
  20. package/dist/chunk-2I6DLXJN.js +0 -219
  21. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  22. package/dist/chunk-3LC4YUMA.js +0 -194
  23. package/dist/chunk-3MIR7ODJ.js +0 -112
  24. package/dist/chunk-3QZESA66.js +0 -222
  25. package/dist/chunk-4Z4MB37G.js +0 -96
  26. package/dist/chunk-5GFUI5N6.js +0 -132
  27. package/dist/chunk-5JEDLXEC.js +0 -99
  28. package/dist/chunk-5LTQNC7R.js +0 -824
  29. package/dist/chunk-5QHQVXWN.js +0 -174
  30. package/dist/chunk-6A3WCJO2.js +0 -416
  31. package/dist/chunk-6QWFMVCD.js +0 -328
  32. package/dist/chunk-6SRXMZAN.js +0 -99
  33. package/dist/chunk-7PTU7TGE.js +0 -96
  34. package/dist/chunk-AB4KX4XT.js +0 -109
  35. package/dist/chunk-AC4UYAGX.js +0 -136
  36. package/dist/chunk-ACE77TKQ.js +0 -328
  37. package/dist/chunk-BHAMEPOP.js +0 -323
  38. package/dist/chunk-BYNYYZWW.js +0 -412
  39. package/dist/chunk-C5TFTNHG.js +0 -244
  40. package/dist/chunk-CH53PBQN.js +0 -265
  41. package/dist/chunk-DF3BM6BF.js +0 -195
  42. package/dist/chunk-DKZVKEOW.js +0 -175
  43. package/dist/chunk-EMPL27ZV.js +0 -96
  44. package/dist/chunk-EQJXMEIR.js +0 -175
  45. package/dist/chunk-FGZZRCOG.js +0 -194
  46. package/dist/chunk-FXYTRZHC.js +0 -177
  47. package/dist/chunk-GTJGZBTQ.js +0 -328
  48. package/dist/chunk-HJMFYDWY.js +0 -222
  49. package/dist/chunk-HRQEECB6.js +0 -315
  50. package/dist/chunk-HWEMAAOY.js +0 -370
  51. package/dist/chunk-IBWCHA5M.js +0 -10
  52. package/dist/chunk-KTM4ZQ3W.js +0 -96
  53. package/dist/chunk-KTP2EPVB.js +0 -27
  54. package/dist/chunk-KYARP7KP.js +0 -97
  55. package/dist/chunk-M2N5DYWN.js +0 -247
  56. package/dist/chunk-M4GDBGXF.js +0 -824
  57. package/dist/chunk-M5F2L4KF.js +0 -177
  58. package/dist/chunk-M6S3M6E3.js +0 -244
  59. package/dist/chunk-N7VXDBQU.js +0 -6
  60. package/dist/chunk-O6A5RHWY.js +0 -122
  61. package/dist/chunk-ODUXELPM.js +0 -219
  62. package/dist/chunk-OF5WIOYS.js +0 -129
  63. package/dist/chunk-OP4QAN23.js +0 -99
  64. package/dist/chunk-P4JH2Q7Z.js +0 -102
  65. package/dist/chunk-PMD5JSV3.js +0 -242
  66. package/dist/chunk-PSSHNBEL.js +0 -177
  67. package/dist/chunk-QEPRH7JB.js +0 -315
  68. package/dist/chunk-QRXWPZKN.js +0 -308
  69. package/dist/chunk-QY4L6XHN.js +0 -384
  70. package/dist/chunk-RNWPCELY.js +0 -176
  71. package/dist/chunk-RSHN2AQ7.js +0 -29
  72. package/dist/chunk-RZLVE57X.js +0 -38
  73. package/dist/chunk-SDCIKREA.js +0 -241
  74. package/dist/chunk-SDREQWNI.js +0 -175
  75. package/dist/chunk-SH26ZOHU.js +0 -159
  76. package/dist/chunk-TRLBBLSS.js +0 -176
  77. package/dist/chunk-U6OXZPYC.js +0 -384
  78. package/dist/chunk-UIBTFZUD.js +0 -314
  79. package/dist/chunk-USUCPCUC.js +0 -156
  80. package/dist/chunk-V4GLWPD7.js +0 -174
  81. package/dist/chunk-VC6U3QGF.js +0 -142
  82. package/dist/chunk-VIST7ACL.js +0 -88
  83. package/dist/chunk-VUNL35KE.js +0 -16
  84. package/dist/chunk-VWBNI4SC.js +0 -174
  85. package/dist/chunk-W5KRWUNE.js +0 -262
  86. package/dist/chunk-WCGKLHCL.js +0 -154
  87. package/dist/chunk-WNXGIEX7.js +0 -219
  88. package/dist/chunk-WPVL6VIT.js +0 -160
  89. package/dist/chunk-XPVSZIA3.js +0 -315
  90. package/dist/chunk-Y633ZIJF.js +0 -384
  91. package/dist/chunk-YCL4GUFR.js +0 -222
  92. package/dist/chunk-YTMKB44I.js +0 -220
  93. package/dist/chunk-ZWBS3T7Q.js +0 -244
  94. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
@@ -1,222 +0,0 @@
1
- import {
2
- DEFAULT_SESSION,
3
- cancelQuestion,
4
- deriveReceiptMeta,
5
- describeToolCall,
6
- fetchModeState,
7
- getMachineId,
8
- isDefaultSession,
9
- isPolicyConfig,
10
- isToolResultError,
11
- listPendingQuestions,
12
- removePendingQuestion,
13
- removePendingSession,
14
- resolvePolicy
15
- } from "./chunk-QEPRH7JB.js";
16
- import {
17
- withRetry
18
- } from "./chunk-3MIR7ODJ.js";
19
- import {
20
- getApiKey,
21
- getBaseUrl
22
- } from "./chunk-VUNL35KE.js";
23
-
24
- // src/codex-adapter.ts
25
- var CODEX_AGENT = { type: "codex", label: "Codex" };
26
- var codexAllow = () => ({ kind: "allow" });
27
- var codexDeny = (reason) => ({ kind: "deny", reason });
28
- var codexPass = () => ({ kind: "pass" });
29
- var toCodexWire = (event, decision) => {
30
- if (event === "PermissionRequest") {
31
- if (decision.kind === "allow") {
32
- return {
33
- hookSpecificOutput: {
34
- hookEventName: "PermissionRequest",
35
- decision: { behavior: "allow" }
36
- }
37
- };
38
- }
39
- if (decision.kind === "deny") {
40
- return {
41
- hookSpecificOutput: {
42
- hookEventName: "PermissionRequest",
43
- decision: { behavior: "deny", message: decision.reason }
44
- }
45
- };
46
- }
47
- return null;
48
- }
49
- if (event === "PreToolUse" && decision.kind === "deny") {
50
- return {
51
- hookSpecificOutput: {
52
- hookEventName: "PreToolUse",
53
- permissionDecision: "deny",
54
- permissionDecisionReason: decision.reason
55
- }
56
- };
57
- }
58
- return null;
59
- };
60
- var toPolicyLookup = (toolName, toolInput) => {
61
- if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
62
- const command = toolInput.command;
63
- return {
64
- tool: "Edit",
65
- input: typeof command === "string" ? { file_path: command } : {}
66
- };
67
- };
68
- var permissionTimeoutDecision = (timeoutAction) => {
69
- if (timeoutAction === "approve") return codexAllow();
70
- if (timeoutAction === "deny") return codexDeny("No response within timeout");
71
- return codexPass();
72
- };
73
- var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
74
-
75
- // src/events.ts
76
- import { basename, join } from "path";
77
- import { createHash } from "crypto";
78
- import { existsSync, readFileSync } from "fs";
79
- import { tmpdir } from "os";
80
- var cleanupPendingQuestions = async (sessionId) => {
81
- try {
82
- const files = listPendingQuestions(sessionId);
83
- const apiKey = getApiKey();
84
- for (const correlationId of files) {
85
- try {
86
- await cancelQuestion(apiKey, correlationId);
87
- } catch {
88
- }
89
- removePendingQuestion(sessionId, correlationId);
90
- }
91
- if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
92
- } catch {
93
- }
94
- };
95
- var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
96
- var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
97
- var readFreshCachedPolicy = (apiKey) => {
98
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
99
- const path = join(tmpdir(), `pushary-policy-${hash}.json`);
100
- if (!existsSync(path)) return null;
101
- const cached = JSON.parse(readFileSync(path, "utf-8"));
102
- if (!isPolicyConfig(cached)) return null;
103
- if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
104
- return cached;
105
- };
106
- var deriveDecisionSource = (toolName, toolInput, liveMode) => {
107
- try {
108
- if (liveMode.kill) return "terminal";
109
- const policy = readFreshCachedPolicy(getApiKey());
110
- if (!policy) return void 0;
111
- const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
112
- if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
113
- if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
114
- return "terminal";
115
- } catch {
116
- return void 0;
117
- }
118
- };
119
- var reportEvent = async (event, options = {}) => {
120
- const apiKey = getApiKey();
121
- const baseUrl = getBaseUrl();
122
- await withRetry(async () => {
123
- await fetch(`${baseUrl}/api/agent/event`, {
124
- method: "POST",
125
- headers: {
126
- "Content-Type": "application/json",
127
- "Authorization": `Bearer ${apiKey}`
128
- },
129
- body: JSON.stringify({
130
- ...event,
131
- machineId: event.machineId ?? getMachineId()
132
- }),
133
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
134
- });
135
- }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
136
- };
137
- var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
138
- try {
139
- const projectName = basename(input.cwd ?? process.cwd());
140
- const action = describeToolCall(input.tool_name, input.tool_input, "event");
141
- const lookup = toPolicyLookup(input.tool_name, input.tool_input);
142
- const isError = isToolResultError(input.tool_result);
143
- const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
144
- const liveMode = await fetchModeState(getApiKey(), input.session_id);
145
- await Promise.allSettled([
146
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
147
- reportEvent({
148
- event: isError ? "tool_error" : "tool_complete",
149
- agentType: agent.type,
150
- agentName: `${agent.label} - ${projectName}`,
151
- action,
152
- sessionId: input.session_id,
153
- error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
154
- decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
155
- meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0
156
- })
157
- ]);
158
- } catch {
159
- }
160
- };
161
- var TASK_TITLE_MAX_LENGTH = 120;
162
- var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
163
- try {
164
- const projectName = basename(input.cwd ?? process.cwd());
165
- const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
166
- const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
167
- await reportEvent({
168
- event: "user_prompt",
169
- agentType: agent.type,
170
- agentName: `${agent.label} - ${projectName}`,
171
- sessionId: input.session_id,
172
- taskTitle
173
- }, { maxAttempts: 1, timeoutMs: 800 });
174
- } catch {
175
- }
176
- };
177
- var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
178
- try {
179
- const projectName = basename(input.cwd ?? process.cwd());
180
- await Promise.allSettled([
181
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
182
- reportEvent({
183
- event: "session_end",
184
- agentType: agent.type,
185
- agentName: `${agent.label} - ${projectName}`,
186
- action: "Session ended",
187
- sessionId: input.session_id
188
- })
189
- ]);
190
- } catch {
191
- }
192
- };
193
- var handleNotification = async (input) => {
194
- try {
195
- const projectName = basename(input.cwd ?? process.cwd());
196
- await reportEvent({
197
- event: input.type === "error" ? "error" : "notification",
198
- agentType: "claude_code",
199
- agentName: `Claude Code - ${projectName}`,
200
- action: input.title ?? input.message ?? "Notification",
201
- sessionId: input.session_id,
202
- error: input.type === "error" ? input.message : void 0
203
- });
204
- } catch {
205
- }
206
- };
207
-
208
- export {
209
- CODEX_AGENT,
210
- codexAllow,
211
- codexDeny,
212
- codexPass,
213
- toCodexWire,
214
- toPolicyLookup,
215
- permissionTimeoutDecision,
216
- preToolUseTimeoutDecision,
217
- reportEvent,
218
- handlePostToolUse,
219
- handleUserPrompt,
220
- handleStop,
221
- handleNotification
222
- };
@@ -1,220 +0,0 @@
1
- import {
2
- askUser,
3
- describeToolCall,
4
- isPolicyConfig,
5
- savePendingQuestion,
6
- sendNotification,
7
- waitForAnswer
8
- } from "./chunk-4Z4MB37G.js";
9
- import {
10
- getApiKey,
11
- getBaseUrl,
12
- withRetry
13
- } from "./chunk-O6A5RHWY.js";
14
-
15
- // src/policy.ts
16
- import { createHash } from "crypto";
17
- import { existsSync, readFileSync, writeFileSync } from "fs";
18
- import { join } from "path";
19
- import { tmpdir } from "os";
20
- var CACHE_TTL_MS = 5 * 60 * 1e3;
21
- var cacheFile = (apiKey) => {
22
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
23
- return join(tmpdir(), `pushary-policy-${hash}.json`);
24
- };
25
- var fetchPolicy = async (apiKey) => {
26
- return withRetry(async () => {
27
- const baseUrl = getBaseUrl();
28
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
29
- headers: { "Authorization": `Bearer ${apiKey}` },
30
- signal: AbortSignal.timeout(1e4)
31
- });
32
- if (!response.ok) {
33
- throw new Error(`Failed to fetch policy: ${response.status}`);
34
- }
35
- const raw = await response.json();
36
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
37
- return raw;
38
- }, { maxAttempts: 2 });
39
- };
40
- var getPolicy = async (apiKey) => {
41
- const path = cacheFile(apiKey);
42
- let staleCache = null;
43
- if (existsSync(path)) {
44
- try {
45
- const stat = readFileSync(path, "utf-8");
46
- const cached = JSON.parse(stat);
47
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
48
- if (!cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS) {
49
- return cached;
50
- }
51
- staleCache = cached;
52
- } catch {
53
- }
54
- }
55
- try {
56
- const policy = await fetchPolicy(apiKey);
57
- try {
58
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now() }), "utf-8");
59
- } catch {
60
- }
61
- return policy;
62
- } catch {
63
- if (staleCache) return staleCache;
64
- throw new Error("Failed to fetch policy and no cached policy available");
65
- }
66
- };
67
- var resolvePolicy = (config, toolName, modeOverride) => {
68
- const base = config.policies.find((p) => p.tool === toolName) ?? config.policies.find((p) => p.tool === "*") ?? {
69
- tool: toolName,
70
- timeoutSeconds: config.defaultTimeoutSeconds,
71
- timeoutAction: config.defaultTimeoutAction,
72
- mode: config.defaultMode ?? "push_first",
73
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
74
- };
75
- const effectiveOverride = modeOverride ?? config.modeOverride;
76
- if (effectiveOverride) {
77
- return { ...base, mode: effectiveOverride };
78
- }
79
- return base;
80
- };
81
-
82
- // src/hook.ts
83
- import { basename } from "path";
84
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
85
- var allow = () => ({
86
- hookSpecificOutput: {
87
- hookEventName: "PreToolUse",
88
- permissionDecision: "allow"
89
- }
90
- });
91
- var deny = (reason) => ({
92
- hookSpecificOutput: {
93
- hookEventName: "PreToolUse",
94
- permissionDecision: "deny",
95
- permissionDecisionReason: reason
96
- }
97
- });
98
- var ask = (reason) => ({
99
- hookSpecificOutput: {
100
- hookEventName: "PreToolUse",
101
- permissionDecision: "ask",
102
- ...reason ? { permissionDecisionReason: reason } : {}
103
- }
104
- });
105
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
106
- while (Date.now() < deadlineMs) {
107
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
108
- let answer;
109
- try {
110
- answer = await waitForAnswer(apiKey, correlationId, remaining);
111
- } catch {
112
- if (Date.now() + pollInterval >= deadlineMs) break;
113
- await sleep(pollInterval);
114
- continue;
115
- }
116
- if (answer.answered) return answer;
117
- if (Date.now() + pollInterval >= deadlineMs) break;
118
- await sleep(pollInterval);
119
- }
120
- return { answered: false };
121
- };
122
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction) => {
123
- let result;
124
- try {
125
- result = await askUser(apiKey, {
126
- question: `Allow ${description}?`,
127
- type: "confirm",
128
- context: `Agent wants to run this in ${projectName}`,
129
- agentName: `Claude Code - ${projectName}`
130
- });
131
- } catch {
132
- switch (timeoutAction) {
133
- case "approve":
134
- return allow();
135
- case "deny":
136
- return deny("Push notification failed, denying per policy");
137
- default:
138
- return ask("Push notification failed, asking in terminal");
139
- }
140
- }
141
- const deadline = Date.now() + timeoutSeconds * 1e3;
142
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
143
- if (answer.answered) {
144
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
145
- }
146
- switch (timeoutAction) {
147
- case "approve":
148
- return allow();
149
- case "deny":
150
- return deny("No response within timeout");
151
- default:
152
- return ask("No push response, asking in terminal");
153
- }
154
- };
155
- var handleTerminalOnly = () => {
156
- return ask();
157
- };
158
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds) => {
159
- let result;
160
- try {
161
- result = await askUser(apiKey, {
162
- question: `Allow ${description}?`,
163
- type: "confirm",
164
- context: `Agent wants to run this in ${projectName}`,
165
- agentName: `Claude Code - ${projectName}`
166
- });
167
- } catch {
168
- return ask("Push notification failed, asking in terminal");
169
- }
170
- const deadline = Date.now() + pushFirstSeconds * 1e3;
171
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
172
- if (answer.answered) {
173
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
174
- }
175
- savePendingQuestion(result.correlationId);
176
- return ask("Sent as push notification. You can also approve here.");
177
- };
178
- var handleNotifyOnly = async (apiKey, description, projectName) => {
179
- try {
180
- await sendNotification(apiKey, {
181
- title: "Agent needs approval",
182
- body: description,
183
- agentName: `Claude Code - ${projectName}`
184
- });
185
- } catch {
186
- }
187
- return ask();
188
- };
189
- var handlePreToolUse = async (input) => {
190
- try {
191
- const apiKey = getApiKey();
192
- const policy = await getPolicy(apiKey);
193
- const toolPolicy = resolvePolicy(policy, input.tool_name);
194
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
195
- return allow();
196
- }
197
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
198
- const projectName = basename(input.cwd ?? process.cwd());
199
- switch (toolPolicy.mode) {
200
- case "push_only":
201
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction);
202
- case "terminal_only":
203
- return handleTerminalOnly();
204
- case "push_first":
205
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
206
- case "notify_only":
207
- return handleNotifyOnly(apiKey, description, projectName);
208
- default:
209
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
210
- }
211
- } catch {
212
- return ask("Pushary unavailable, falling back to terminal approval");
213
- }
214
- };
215
-
216
- export {
217
- getPolicy,
218
- resolvePolicy,
219
- handlePreToolUse
220
- };
@@ -1,244 +0,0 @@
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/npm.ts
206
- import { execSync } from "child_process";
207
- var cleanNpmEnv = () => {
208
- const env = {};
209
- for (const [key, value] of Object.entries(process.env)) {
210
- if (key.toLowerCase().startsWith("npm_config_workspace")) continue;
211
- env[key] = value;
212
- }
213
- return env;
214
- };
215
- var npmErrorMessage = (err) => {
216
- const e = err;
217
- const text = [e?.stderr, e?.stdout].map((part) => part ? part.toString() : "").join("\n");
218
- 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));
219
- return line || e?.message || String(err);
220
- };
221
- var execNpm = (args, options = {}) => {
222
- return execSync(`npm ${args}`, {
223
- timeout: 12e4,
224
- stdio: "pipe",
225
- ...options,
226
- env: { ...cleanNpmEnv(), ...options.env ?? {} }
227
- });
228
- };
229
-
230
- export {
231
- addCodexHooks,
232
- removeCodexHooks,
233
- hasCodexHooks,
234
- missingCodexHookEvents,
235
- addCodexHookTrust,
236
- GEMINI_HOOK_BINARY,
237
- addGeminiMcpServer,
238
- addGeminiHooks,
239
- removeGeminiSettings,
240
- hasGeminiHooks,
241
- missingGeminiHookEvents,
242
- npmErrorMessage,
243
- execNpm
244
- };