@pushary/agent-hooks 0.13.0 → 0.14.1

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.
@@ -0,0 +1,315 @@
1
+ import {
2
+ extractPolicyArg,
3
+ isApprovalMode,
4
+ matchRankWeight,
5
+ matchToolPattern
6
+ } from "./chunk-22CV7V7A.js";
7
+ import {
8
+ callMcpTool,
9
+ withRetry
10
+ } from "./chunk-3MIR7ODJ.js";
11
+ import {
12
+ getBaseUrl
13
+ } from "./chunk-VUNL35KE.js";
14
+
15
+ // src/validate.ts
16
+ var isPolicyConfig = (data) => {
17
+ if (!data || typeof data !== "object") return false;
18
+ const d = data;
19
+ return Array.isArray(d.policies) && typeof d.defaultTimeoutSeconds === "number" && typeof d.defaultTimeoutAction === "string";
20
+ };
21
+ var isAskUserResponse = (data) => {
22
+ if (!data || typeof data !== "object") return false;
23
+ const d = data;
24
+ return typeof d.correlationId === "string" && typeof d.status === "string";
25
+ };
26
+ var isWaitForAnswerResponse = (data) => {
27
+ if (!data || typeof data !== "object") return false;
28
+ const d = data;
29
+ return typeof d.answered === "boolean";
30
+ };
31
+
32
+ // src/api.ts
33
+ var askUser = async (apiKey, params) => {
34
+ const result = await callMcpTool(apiKey, "ask_user", { ...params, wait: false }, { maxRetries: 3 });
35
+ if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
36
+ return result;
37
+ };
38
+ var waitForAnswer = async (apiKey, correlationId, timeoutMs = 3e4) => {
39
+ const result = await callMcpTool(apiKey, "wait_for_answer", {
40
+ correlationId,
41
+ timeoutMs
42
+ });
43
+ if (!isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
44
+ return result;
45
+ };
46
+ var cancelQuestion = async (apiKey, correlationId) => {
47
+ await callMcpTool(apiKey, "cancel_question", { correlationId });
48
+ };
49
+ var sendNotification = async (apiKey, params) => {
50
+ await callMcpTool(apiKey, "send_notification", { ...params }, { maxRetries: 3 });
51
+ };
52
+
53
+ // src/policy.ts
54
+ import { createHash } from "crypto";
55
+ import { existsSync, readFileSync, writeFileSync } from "fs";
56
+ import { join } from "path";
57
+ import { tmpdir } from "os";
58
+ var CACHE_TTL_MS = 5 * 60 * 1e3;
59
+ var cacheFile = (apiKey) => {
60
+ const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
61
+ return join(tmpdir(), `pushary-policy-${hash}.json`);
62
+ };
63
+ var fetchPolicy = async (apiKey) => {
64
+ return withRetry(async () => {
65
+ const baseUrl = getBaseUrl();
66
+ const response = await fetch(`${baseUrl}/api/mcp/policy`, {
67
+ headers: { "Authorization": `Bearer ${apiKey}` },
68
+ signal: AbortSignal.timeout(1e4)
69
+ });
70
+ if (!response.ok) {
71
+ throw new Error(`Failed to fetch policy: ${response.status}`);
72
+ }
73
+ const raw = await response.json();
74
+ if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
75
+ return raw;
76
+ }, { maxAttempts: 2 });
77
+ };
78
+ var getPolicy = async (apiKey, expectedVersion) => {
79
+ const path = cacheFile(apiKey);
80
+ let staleCache = null;
81
+ if (existsSync(path)) {
82
+ try {
83
+ const stat = readFileSync(path, "utf-8");
84
+ const cached = JSON.parse(stat);
85
+ if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
86
+ const versionStale = expectedVersion != null && (cached._policyVersion ?? null) !== expectedVersion;
87
+ const ttlFresh = !cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS;
88
+ if (ttlFresh && !versionStale) {
89
+ return cached;
90
+ }
91
+ staleCache = cached;
92
+ } catch {
93
+ }
94
+ }
95
+ try {
96
+ const policy = await fetchPolicy(apiKey);
97
+ try {
98
+ writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now(), _policyVersion: expectedVersion ?? null }), "utf-8");
99
+ } catch {
100
+ }
101
+ return policy;
102
+ } catch {
103
+ if (staleCache) return staleCache;
104
+ throw new Error("Failed to fetch policy and no cached policy available");
105
+ }
106
+ };
107
+ var findBestMatch = (policies, toolName, arg) => {
108
+ let best;
109
+ let bestWeight = 0;
110
+ let bestLength = -1;
111
+ for (const candidate of policies) {
112
+ const rank = matchToolPattern(candidate.tool, toolName, arg);
113
+ if (rank === "none") continue;
114
+ const weight = matchRankWeight(rank);
115
+ const length = rank === "prefix" ? candidate.tool.length : -1;
116
+ if (weight > bestWeight || weight === bestWeight && length > bestLength) {
117
+ best = candidate;
118
+ bestWeight = weight;
119
+ bestLength = length;
120
+ }
121
+ }
122
+ return best;
123
+ };
124
+ var resolvePolicy = (config, toolName, modeOverride, toolInput) => {
125
+ const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
126
+ const base = findBestMatch(config.policies, toolName, arg) ?? config.policies.find((p) => p.tool === "*") ?? {
127
+ tool: toolName,
128
+ timeoutSeconds: config.defaultTimeoutSeconds,
129
+ timeoutAction: config.defaultTimeoutAction,
130
+ mode: config.defaultMode ?? "push_first",
131
+ pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
132
+ };
133
+ const effectiveOverride = modeOverride ?? config.modeOverride;
134
+ if (effectiveOverride) {
135
+ return { ...base, mode: effectiveOverride };
136
+ }
137
+ return base;
138
+ };
139
+ var toPolicyVersion = (value) => typeof value === "string" || typeof value === "number" ? String(value) : null;
140
+ var fetchModeState = async (apiKey, sessionId) => {
141
+ try {
142
+ const baseUrl = getBaseUrl();
143
+ const url = sessionId ? `${baseUrl}/api/mcp/mode?session=${encodeURIComponent(sessionId)}` : `${baseUrl}/api/mcp/mode`;
144
+ const response = await fetch(url, {
145
+ headers: { "Authorization": `Bearer ${apiKey}` },
146
+ signal: AbortSignal.timeout(3e3)
147
+ });
148
+ if (!response.ok) return { mode: null, kill: false, policyVersion: null };
149
+ const data = await response.json();
150
+ const mode = data.override?.mode;
151
+ return {
152
+ mode: isApprovalMode(mode) ? mode : null,
153
+ kill: data.kill === true,
154
+ policyVersion: toPolicyVersion(data.policyVersion)
155
+ };
156
+ } catch {
157
+ return { mode: null, kill: false, policyVersion: null };
158
+ }
159
+ };
160
+ var fetchModeOverride = async (apiKey) => (await fetchModeState(apiKey)).mode;
161
+
162
+ // src/describe.ts
163
+ import { isAbsolute, relative } from "path";
164
+ var hookPrefixes = {
165
+ Bash: (input) => `bash: ${input.command ?? "(no command)"}`,
166
+ Write: (input) => `write file: ${input.file_path ?? "(unknown path)"}`,
167
+ Edit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
168
+ Read: (input) => `read file: ${input.file_path ?? "(unknown path)"}`
169
+ };
170
+ var eventPrefixes = {
171
+ Bash: (input) => `ran: ${String(input.command ?? "").slice(0, 120)}`,
172
+ Write: (input) => `wrote: ${input.file_path ?? "unknown"}`,
173
+ Edit: (input) => `edited: ${input.file_path ?? "unknown"}`,
174
+ Read: (input) => `read: ${input.file_path ?? "unknown"}`
175
+ };
176
+ var describeToolCall = (toolName, toolInput, format = "hook") => {
177
+ const prefixes = format === "hook" ? hookPrefixes : eventPrefixes;
178
+ const builder = prefixes[toolName];
179
+ if (builder) return builder(toolInput);
180
+ return format === "hook" ? `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}` : `${toolName}: done`;
181
+ };
182
+ var TOOL_TARGET_MAX_LENGTH = 80;
183
+ var deriveCommandHead = (command) => {
184
+ if (typeof command !== "string") return void 0;
185
+ const head = command.trim().split(/\s+/).slice(0, 2).join(" ");
186
+ return head ? head.slice(0, TOOL_TARGET_MAX_LENGTH) : void 0;
187
+ };
188
+ var deriveToolTarget = (toolName, toolInput) => {
189
+ if (toolName === "Bash") {
190
+ return deriveCommandHead(toolInput.command);
191
+ }
192
+ if (toolName === "Edit" || toolName === "Write") {
193
+ const filePath = toolInput.file_path;
194
+ if (typeof filePath !== "string") return void 0;
195
+ const separator = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
196
+ const base = filePath.slice(separator + 1);
197
+ const dot = base.lastIndexOf(".");
198
+ if (dot <= 0) return void 0;
199
+ return base.slice(dot).slice(0, TOOL_TARGET_MAX_LENGTH);
200
+ }
201
+ return void 0;
202
+ };
203
+ var RECEIPT_TARGET_MAX_LENGTH = 256;
204
+ var isToolResultError = (toolResult) => {
205
+ try {
206
+ return Boolean(toolResult && ("error" in toolResult || "is_error" in toolResult));
207
+ } catch {
208
+ return false;
209
+ }
210
+ };
211
+ var relativizeReceiptPath = (filePath, cwd) => {
212
+ if (!cwd || !isAbsolute(filePath)) return filePath;
213
+ return relative(cwd, filePath);
214
+ };
215
+ var deriveReceiptMeta = (toolName, toolInput, toolResult, cwd) => {
216
+ try {
217
+ const ok = !isToolResultError(toolResult);
218
+ if (toolName === "Edit" || toolName === "Write") {
219
+ const filePath = toolInput.file_path;
220
+ if (typeof filePath !== "string" || !filePath) return void 0;
221
+ return {
222
+ kind: toolName === "Edit" ? "edit" : "write",
223
+ target: relativizeReceiptPath(filePath, cwd).slice(0, RECEIPT_TARGET_MAX_LENGTH),
224
+ ok
225
+ };
226
+ }
227
+ if (toolName === "Bash") {
228
+ const head = deriveCommandHead(toolInput.command);
229
+ if (!head) return void 0;
230
+ return {
231
+ kind: head === "git commit" ? "commit" : "bash",
232
+ target: head,
233
+ ok
234
+ };
235
+ }
236
+ return void 0;
237
+ } catch {
238
+ return void 0;
239
+ }
240
+ };
241
+
242
+ // src/identity.ts
243
+ import { createHash as createHash2 } from "crypto";
244
+ import { hostname } from "os";
245
+ var deriveMachineId = (host) => createHash2("sha256").update(host).digest("hex").slice(0, 8);
246
+ var getMachineId = () => deriveMachineId(hostname());
247
+
248
+ // src/pending.ts
249
+ import { join as join2 } from "path";
250
+ import { tmpdir as tmpdir2 } from "os";
251
+ import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2, readdirSync, unlinkSync, rmSync, statSync } from "fs";
252
+ var PENDING_DIR = join2(tmpdir2(), "pushary-pending");
253
+ var DEFAULT_SESSION = "_no_session";
254
+ var GRACE_MS = 10 * 60 * 1e3;
255
+ var sanitize = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
256
+ var dirFor = (sessionId) => join2(PENDING_DIR, sanitize(sessionId));
257
+ var isDefaultSession = (sessionId) => sanitize(sessionId) === DEFAULT_SESSION;
258
+ var savePendingQuestion = (sessionId, correlationId) => {
259
+ const dir = dirFor(sessionId);
260
+ if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
261
+ writeFileSync2(join2(dir, correlationId), "", "utf-8");
262
+ };
263
+ var listPendingQuestions = (sessionId) => {
264
+ const dir = dirFor(sessionId);
265
+ let files;
266
+ try {
267
+ files = readdirSync(dir);
268
+ } catch {
269
+ return [];
270
+ }
271
+ if (!isDefaultSession(sessionId)) return files;
272
+ const cutoff = Date.now() - GRACE_MS;
273
+ return files.filter((name) => {
274
+ try {
275
+ return statSync(join2(dir, name)).mtimeMs < cutoff;
276
+ } catch {
277
+ return false;
278
+ }
279
+ });
280
+ };
281
+ var removePendingQuestion = (sessionId, correlationId) => {
282
+ try {
283
+ unlinkSync(join2(dirFor(sessionId), correlationId));
284
+ } catch {
285
+ }
286
+ };
287
+ var removePendingSession = (sessionId) => {
288
+ try {
289
+ rmSync(dirFor(sessionId), { recursive: true, force: true });
290
+ } catch {
291
+ }
292
+ };
293
+
294
+ export {
295
+ isPolicyConfig,
296
+ askUser,
297
+ waitForAnswer,
298
+ cancelQuestion,
299
+ sendNotification,
300
+ getPolicy,
301
+ resolvePolicy,
302
+ fetchModeState,
303
+ fetchModeOverride,
304
+ describeToolCall,
305
+ deriveToolTarget,
306
+ isToolResultError,
307
+ deriveReceiptMeta,
308
+ getMachineId,
309
+ DEFAULT_SESSION,
310
+ isDefaultSession,
311
+ savePendingQuestion,
312
+ listPendingQuestions,
313
+ removePendingQuestion,
314
+ removePendingSession
315
+ };
@@ -16,7 +16,18 @@ interface HookOutput {
16
16
  }
17
17
  declare const handlePreToolUse: (input: ToolInput) => Promise<HookOutput>;
18
18
 
19
+ type ReceiptKind = 'edit' | 'write' | 'bash' | 'commit';
20
+ interface ReceiptMeta {
21
+ kind: ReceiptKind;
22
+ target: string;
23
+ ok: boolean;
24
+ }
25
+
19
26
  type DecisionSource = 'policy_auto' | 'human' | 'terminal';
27
+ interface AgentIdentity {
28
+ readonly type: string;
29
+ readonly label: string;
30
+ }
20
31
  interface AgentEvent {
21
32
  event: string;
22
33
  agentType: string;
@@ -27,6 +38,7 @@ interface AgentEvent {
27
38
  error?: string;
28
39
  taskTitle?: string;
29
40
  decisionSource?: DecisionSource;
41
+ meta?: ReceiptMeta;
30
42
  }
31
43
  interface ReportEventOptions {
32
44
  maxAttempts?: number;
@@ -39,12 +51,12 @@ declare const handlePostToolUse: (input: {
39
51
  tool_result?: Record<string, unknown>;
40
52
  cwd?: string;
41
53
  session_id?: string;
42
- }) => Promise<void>;
54
+ }, agent?: AgentIdentity) => Promise<void>;
43
55
  declare const handleStop: (input: {
44
56
  cwd?: string;
45
57
  session_id?: string;
46
58
  stop_hook_active?: boolean;
47
- }) => Promise<void>;
59
+ }, agent?: AgentIdentity) => Promise<void>;
48
60
  declare const handleNotification: (input: {
49
61
  message?: string;
50
62
  title?: string;
@@ -76,11 +88,12 @@ declare const askUser: (apiKey: string, params: AskUserParams) => Promise<AskUse
76
88
  declare const waitForAnswer: (apiKey: string, correlationId: string, timeoutMs?: number) => Promise<WaitForAnswerResponse>;
77
89
  declare const cancelQuestion: (apiKey: string, correlationId: string) => Promise<void>;
78
90
 
79
- declare const getPolicy: (apiKey: string) => Promise<PolicyConfig>;
91
+ declare const getPolicy: (apiKey: string, expectedVersion?: string | null) => Promise<PolicyConfig>;
80
92
  declare const resolvePolicy: (config: PolicyConfig, toolName: string, modeOverride?: ApprovalMode | null, toolInput?: Record<string, unknown>) => ToolPolicy;
81
93
  interface ModeState {
82
94
  readonly mode: ApprovalMode | null;
83
95
  readonly kill: boolean;
96
+ readonly policyVersion: string | null;
84
97
  }
85
98
  declare const fetchModeState: (apiKey: string, sessionId?: string) => Promise<ModeState>;
86
99
  declare const fetchModeOverride: (apiKey: string) => Promise<ApprovalMode | null>;
package/dist/src/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  handlePreToolUse
3
- } from "../chunk-RNWPCELY.js";
3
+ } from "../chunk-V4GLWPD7.js";
4
4
  import {
5
5
  handleNotification,
6
6
  handlePostToolUse,
7
7
  handleStop,
8
8
  reportEvent
9
- } from "../chunk-WCGKLHCL.js";
9
+ } from "../chunk-HJMFYDWY.js";
10
10
  import {
11
11
  askUser,
12
12
  cancelQuestion,
@@ -15,13 +15,13 @@ import {
15
15
  getPolicy,
16
16
  resolvePolicy,
17
17
  waitForAnswer
18
- } from "../chunk-CH53PBQN.js";
18
+ } from "../chunk-XPVSZIA3.js";
19
+ import "../chunk-22CV7V7A.js";
19
20
  import "../chunk-3MIR7ODJ.js";
20
21
  import {
21
22
  getApiKey,
22
23
  getBaseUrl
23
24
  } from "../chunk-VUNL35KE.js";
24
- import "../chunk-22CV7V7A.js";
25
25
  export {
26
26
  askUser,
27
27
  cancelQuestion,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/agent-hooks",
3
- "version": "0.13.0",
3
+ "version": "0.14.1",
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",
@@ -21,6 +21,7 @@
21
21
  "pushary-stop-hook": "./dist/bin/pushary-stop-hook.js",
22
22
  "pushary-prompt-hook": "./dist/bin/pushary-prompt-hook.js",
23
23
  "pushary-codex": "./dist/bin/pushary-codex.js",
24
+ "pushary-codex-hook": "./dist/bin/pushary-codex-hook.js",
24
25
  "pushary-setup": "./dist/bin/pushary-setup.js",
25
26
  "pushary-clean": "./dist/bin/pushary-clean.js",
26
27
  "pushary-doctor": "./dist/bin/pushary-doctor.js",
@@ -33,7 +34,7 @@
33
34
  "scripts": {
34
35
  "build": "node scripts/bundle-plugin.mjs && tsup",
35
36
  "dev": "tsup --watch",
36
- "test": "bun test src/api.test.ts && bun test src/claude-config.test.ts && bun test src/mcp-http.test.ts && bun test src/retry.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/hook.test.ts"
37
+ "test": "bun test src/api.test.ts && bun test src/claude-config.test.ts && bun test src/mcp-http.test.ts && bun test src/retry.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/hook.test.ts && bun test src/codex-adapter.test.ts && bun test src/codex-config.test.ts"
37
38
  },
38
39
  "dependencies": {
39
40
  "@inquirer/prompts": "^8.4.2",