@pushary/agent-hooks 0.42.0 → 0.44.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.
@@ -1,355 +0,0 @@
1
- import {
2
- callMcpTool,
3
- withRetry
4
- } from "./chunk-DWED7BS3.js";
5
- import {
6
- ACTION_BODY_MAX,
7
- DECISION_LINE_MAX,
8
- extractPolicyArg,
9
- isApprovalMode,
10
- isSafeReadOnlyCommand,
11
- matchRankWeight,
12
- matchToolPattern,
13
- redactSecrets,
14
- redactSecretsDeep
15
- } from "./chunk-Z5PL3K7C.js";
16
- import {
17
- getBaseUrl
18
- } from "./chunk-NKXSILEW.js";
19
-
20
- // src/identity.ts
21
- import { createHash } from "crypto";
22
- import { hostname } from "os";
23
- var deriveMachineId = (host) => createHash("sha256").update(host).digest("hex").slice(0, 8);
24
- var getMachineId = () => deriveMachineId(hostname());
25
-
26
- // src/policy.ts
27
- import { createHash as createHash2 } from "crypto";
28
- import { existsSync, readFileSync, writeFileSync } from "fs";
29
- import { join } from "path";
30
- import { tmpdir } from "os";
31
-
32
- // src/validate.ts
33
- var isPolicyConfig = (data) => {
34
- if (!data || typeof data !== "object") return false;
35
- const d = data;
36
- return Array.isArray(d.policies) && typeof d.defaultTimeoutSeconds === "number" && typeof d.defaultTimeoutAction === "string";
37
- };
38
- var isAskUserResponse = (data) => {
39
- if (!data || typeof data !== "object") return false;
40
- const d = data;
41
- return typeof d.correlationId === "string" && typeof d.status === "string";
42
- };
43
- var isWaitForAnswerResponse = (data) => {
44
- if (!data || typeof data !== "object") return false;
45
- const d = data;
46
- return typeof d.answered === "boolean";
47
- };
48
-
49
- // src/policy.ts
50
- var CACHE_TTL_MS = 60 * 1e3;
51
- var cacheFile = (apiKey) => {
52
- const hash = createHash2("sha256").update(apiKey).digest("hex").slice(0, 12);
53
- return join(tmpdir(), `pushary-policy-${hash}.json`);
54
- };
55
- var fetchPolicy = async (apiKey) => {
56
- return withRetry(async () => {
57
- const baseUrl = getBaseUrl();
58
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
59
- headers: { "Authorization": `Bearer ${apiKey}` },
60
- signal: AbortSignal.timeout(1e4)
61
- });
62
- if (!response.ok) {
63
- throw new Error(`Failed to fetch policy: ${response.status}`);
64
- }
65
- const raw = await response.json();
66
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
67
- return raw;
68
- }, { maxAttempts: 2 });
69
- };
70
- var getPolicy = async (apiKey, expectedVersion) => {
71
- const path = cacheFile(apiKey);
72
- let staleCache = null;
73
- if (existsSync(path)) {
74
- try {
75
- const stat = readFileSync(path, "utf-8");
76
- const cached = JSON.parse(stat);
77
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
78
- const versionStale = expectedVersion != null && (cached._policyVersion ?? null) !== expectedVersion;
79
- const ttlFresh = !cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS;
80
- if (ttlFresh && !versionStale) {
81
- return cached;
82
- }
83
- staleCache = cached;
84
- } catch {
85
- }
86
- }
87
- try {
88
- const policy = await fetchPolicy(apiKey);
89
- try {
90
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now(), _policyVersion: expectedVersion ?? null }), "utf-8");
91
- } catch {
92
- }
93
- return policy;
94
- } catch {
95
- if (staleCache) return staleCache;
96
- throw new Error("Failed to fetch policy and no cached policy available");
97
- }
98
- };
99
- var findBestMatch = (policies, toolName, arg) => {
100
- let best;
101
- let bestWeight = 0;
102
- let bestLength = -1;
103
- for (const candidate of policies) {
104
- const rank = matchToolPattern(candidate.tool, toolName, arg);
105
- if (rank === "none") continue;
106
- const weight = matchRankWeight(rank);
107
- const length = rank === "prefix" ? candidate.tool.length : -1;
108
- if (weight > bestWeight || weight === bestWeight && length > bestLength) {
109
- best = { policy: candidate, rank };
110
- bestWeight = weight;
111
- bestLength = length;
112
- }
113
- }
114
- return best;
115
- };
116
- var autoApprove = (tool) => ({
117
- tool,
118
- timeoutSeconds: 0,
119
- timeoutAction: "approve",
120
- mode: "terminal_only",
121
- pushFirstSeconds: 0
122
- });
123
- var resolveAutoResolveOrigin = (config, toolName, toolInput) => {
124
- const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
125
- const match = findBestMatch(config.policies, toolName, arg);
126
- const governedBySpecificRule = match?.rank === "exact" || match?.rank === "prefix";
127
- if (!governedBySpecificRule && toolName === "Bash" && typeof arg === "string" && isSafeReadOnlyCommand(arg)) {
128
- return "safe_readonly";
129
- }
130
- return "policy_timeout";
131
- };
132
- var resolvePolicy = (config, toolName, modeOverride, toolInput) => {
133
- const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
134
- const match = findBestMatch(config.policies, toolName, arg);
135
- let base = match?.policy ?? config.policies.find((p) => p.tool === "*") ?? {
136
- tool: toolName,
137
- timeoutSeconds: config.defaultTimeoutSeconds,
138
- timeoutAction: config.defaultTimeoutAction,
139
- mode: config.defaultMode ?? "push_first",
140
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
141
- };
142
- const governedBySpecificRule = match?.rank === "exact" || match?.rank === "prefix";
143
- if (!governedBySpecificRule && toolName === "Bash" && typeof arg === "string" && isSafeReadOnlyCommand(arg)) {
144
- base = autoApprove(base.tool);
145
- }
146
- const effectiveOverride = modeOverride ?? config.modeOverride;
147
- if (effectiveOverride) {
148
- return { ...base, mode: effectiveOverride };
149
- }
150
- return base;
151
- };
152
- var toPolicyVersion = (value) => typeof value === "string" || typeof value === "number" ? String(value) : null;
153
- var fetchModeState = async (apiKey, sessionId) => {
154
- try {
155
- const baseUrl = getBaseUrl();
156
- const url = sessionId ? `${baseUrl}/api/mcp/mode?session=${encodeURIComponent(sessionId)}` : `${baseUrl}/api/mcp/mode`;
157
- const response = await fetch(url, {
158
- headers: { "Authorization": `Bearer ${apiKey}` },
159
- signal: AbortSignal.timeout(3e3)
160
- });
161
- if (!response.ok) return { mode: null, kill: false, policyVersion: null, relayUrl: null };
162
- const data = await response.json();
163
- const mode = data.override?.mode;
164
- return {
165
- mode: isApprovalMode(mode) ? mode : null,
166
- kill: data.kill === true,
167
- policyVersion: toPolicyVersion(data.policyVersion),
168
- relayUrl: typeof data.relayUrl === "string" && data.relayUrl.length > 0 ? data.relayUrl : null
169
- };
170
- } catch {
171
- return { mode: null, kill: false, policyVersion: null, relayUrl: null };
172
- }
173
- };
174
- var fetchModeOverride = async (apiKey) => (await fetchModeState(apiKey)).mode;
175
-
176
- // src/api.ts
177
- var askUser = async (apiKey, params, timeoutMs = 15e3) => {
178
- const result = await callMcpTool(apiKey, "ask_user", { ...params, wait: false }, { maxRetries: 3, timeoutMs });
179
- if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
180
- return result;
181
- };
182
- var waitForAnswer = async (apiKey, correlationId, timeoutMs = 3e4) => {
183
- const result = await callMcpTool(apiKey, "wait_for_answer", {
184
- correlationId,
185
- timeoutMs
186
- }, { timeoutMs: timeoutMs + 1e4 });
187
- if (!isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
188
- return result;
189
- };
190
- var cancelQuestion = async (apiKey, correlationId) => {
191
- await callMcpTool(apiKey, "cancel_question", { correlationId });
192
- };
193
- var sendNotification = async (apiKey, params, timeoutMs = 15e3) => {
194
- await callMcpTool(apiKey, "send_notification", { ...params }, { maxRetries: 3, timeoutMs });
195
- };
196
-
197
- // src/describe.ts
198
- import { isAbsolute, relative } from "path";
199
- var hookPrefixes = {
200
- Bash: (input) => `bash: ${input.command ?? "(no command)"}`,
201
- PowerShell: (input) => `powershell: ${input.command ?? "(no command)"}`,
202
- Monitor: (input) => `monitor: ${input.command ?? "(no command)"}`,
203
- Write: (input) => `write file: ${input.file_path ?? "(unknown path)"}`,
204
- Edit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
205
- MultiEdit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
206
- Read: (input) => `read file: ${input.file_path ?? "(unknown path)"}`
207
- };
208
- var describeTodoProgress = (todos) => {
209
- if (!Array.isArray(todos)) return "updated the plan";
210
- const items = todos.filter((t) => !!t && typeof t === "object");
211
- const total = items.length;
212
- if (total === 0) return "updated the plan";
213
- const done = items.filter((t) => t.status === "completed").length;
214
- const current = items.find((t) => t.status === "in_progress");
215
- const label = current ? [current.activeForm, current.content].find((v) => typeof v === "string" && v.trim().length > 0) : void 0;
216
- if (done >= total) return `finished all ${total} tasks`;
217
- if (label) return `${label.trim()} (${done}/${total} done)`;
218
- return `${done}/${total} tasks done`;
219
- };
220
- var eventPrefixes = {
221
- Bash: (input) => `ran: ${String(input.command ?? "")}`,
222
- PowerShell: (input) => `ran: ${String(input.command ?? "")}`,
223
- Monitor: (input) => `ran: ${String(input.command ?? "")}`,
224
- Write: (input) => `wrote: ${input.file_path ?? "unknown"}`,
225
- Edit: (input) => `edited: ${input.file_path ?? "unknown"}`,
226
- MultiEdit: (input) => `edited: ${input.file_path ?? "unknown"}`,
227
- Read: (input) => `read: ${input.file_path ?? "unknown"}`,
228
- TodoWrite: (input) => describeTodoProgress(input.todos)
229
- };
230
- var EVENT_ACTION_MAX = 120;
231
- var HOOK_FALLBACK_MAX = 200;
232
- var describeToolCall = (toolName, toolInput, format = "hook") => {
233
- const prefixes = format === "hook" ? hookPrefixes : eventPrefixes;
234
- const builder = prefixes[toolName];
235
- const raw = builder ? builder(toolInput) : format === "hook" ? `${toolName}: ${JSON.stringify(toolInput)}` : `${toolName}: done`;
236
- const redacted = redactSecrets(raw);
237
- if (format === "event") return redacted.slice(0, EVENT_ACTION_MAX);
238
- return builder ? redacted : redacted.slice(0, HOOK_FALLBACK_MAX);
239
- };
240
- var TOOL_TARGET_MAX_LENGTH = 80;
241
- var deriveCommandHead = (command) => {
242
- if (typeof command !== "string") return void 0;
243
- const head = command.trim().split(/\s+/).slice(0, 2).join(" ");
244
- return head ? head.slice(0, TOOL_TARGET_MAX_LENGTH) : void 0;
245
- };
246
- var deriveToolTarget = (toolName, toolInput) => {
247
- if (toolName === "Bash" || toolName === "PowerShell" || toolName === "Monitor") {
248
- return deriveCommandHead(toolInput.command);
249
- }
250
- if (toolName === "Edit" || toolName === "Write" || toolName === "MultiEdit") {
251
- const filePath = toolInput.file_path;
252
- if (typeof filePath !== "string") return void 0;
253
- const separator = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
254
- const base = filePath.slice(separator + 1);
255
- const dot = base.lastIndexOf(".");
256
- if (dot <= 0) return void 0;
257
- return base.slice(dot).slice(0, TOOL_TARGET_MAX_LENGTH);
258
- }
259
- return void 0;
260
- };
261
- var RECEIPT_TARGET_MAX_LENGTH = 256;
262
- var isToolResultError = (toolResult) => {
263
- try {
264
- return Boolean(toolResult && ("error" in toolResult || "is_error" in toolResult));
265
- } catch {
266
- return false;
267
- }
268
- };
269
- var relativizeReceiptPath = (filePath, cwd) => {
270
- if (!cwd || !isAbsolute(filePath)) return filePath;
271
- return relative(cwd, filePath);
272
- };
273
- var deriveReceiptMeta = (toolName, toolInput, toolResult, cwd) => {
274
- try {
275
- const ok = !isToolResultError(toolResult);
276
- if (toolName === "Edit" || toolName === "Write" || toolName === "MultiEdit") {
277
- const filePath = toolInput.file_path;
278
- if (typeof filePath !== "string" || !filePath) return void 0;
279
- return {
280
- kind: toolName === "Write" ? "write" : "edit",
281
- target: relativizeReceiptPath(filePath, cwd).slice(0, RECEIPT_TARGET_MAX_LENGTH),
282
- ok
283
- };
284
- }
285
- if (toolName === "Bash" || toolName === "PowerShell" || toolName === "Monitor") {
286
- const head = deriveCommandHead(toolInput.command);
287
- if (!head) return void 0;
288
- return {
289
- kind: head === "git commit" ? "commit" : "bash",
290
- target: head,
291
- ok
292
- };
293
- }
294
- return void 0;
295
- } catch {
296
- return void 0;
297
- }
298
- };
299
- var firstString = (...values) => values.find((v) => typeof v === "string" && v.length > 0);
300
- var ACTION_BODY_TRUNCATION_MARKER = "\n\u2026 [truncated]";
301
- var capActionBody = (text) => text.length <= ACTION_BODY_MAX ? text : `${text.slice(0, ACTION_BODY_MAX - ACTION_BODY_TRUNCATION_MARKER.length)}${ACTION_BODY_TRUNCATION_MARKER}`;
302
- var rawActionBody = (toolName, toolInput) => {
303
- if (toolName === "Edit" || toolName === "replace") {
304
- const before = firstString(toolInput.old_string);
305
- const after = firstString(toolInput.new_string);
306
- if (before === void 0 && after === void 0) return void 0;
307
- return `- ${before ?? ""}
308
- + ${after ?? ""}`;
309
- }
310
- if (toolName === "Write" || toolName === "write_file") return firstString(toolInput.content);
311
- if (toolName === "Bash" || toolName === "PowerShell" || toolName === "Monitor" || toolName === "run_shell_command" || toolName === "shell" || toolName === "apply_patch") {
312
- return firstString(toolInput.command);
313
- }
314
- return void 0;
315
- };
316
- var deriveActionBody = (toolName, toolInput) => {
317
- try {
318
- const raw = rawActionBody(toolName, toolInput);
319
- if (!raw) return void 0;
320
- return capActionBody(redactSecretsDeep(raw));
321
- } catch {
322
- return void 0;
323
- }
324
- };
325
- var deriveAction = (toolName, toolInput) => describeToolCall(toolName, toolInput, "hook").slice(0, DECISION_LINE_MAX);
326
- var BLOCKER_BY_MODE = {
327
- push_only: "Approval required before this runs",
328
- push_first: "Paused for your approval before continuing",
329
- escalate: "Escalated to you after the approval timeout"
330
- };
331
- var deriveBlocker = (mode, reason) => {
332
- const text = reason?.replace(/\s+/g, " ").trim() || BLOCKER_BY_MODE[mode] || "Waiting for your approval";
333
- return text.slice(0, DECISION_LINE_MAX);
334
- };
335
-
336
- export {
337
- getMachineId,
338
- isPolicyConfig,
339
- getPolicy,
340
- resolveAutoResolveOrigin,
341
- resolvePolicy,
342
- fetchModeState,
343
- fetchModeOverride,
344
- askUser,
345
- waitForAnswer,
346
- cancelQuestion,
347
- sendNotification,
348
- describeToolCall,
349
- deriveToolTarget,
350
- isToolResultError,
351
- deriveReceiptMeta,
352
- deriveActionBody,
353
- deriveAction,
354
- deriveBlocker
355
- };