@pushary/agent-hooks 0.28.1 → 0.28.2

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 (97) hide show
  1. package/package.json +1 -1
  2. package/dist/chunk-22CV7V7A.js +0 -38
  3. package/dist/chunk-2BE2IPMO.js +0 -315
  4. package/dist/chunk-2CRLBMOX.js +0 -244
  5. package/dist/chunk-2HMNOZPY.js +0 -109
  6. package/dist/chunk-2I6DLXJN.js +0 -219
  7. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  8. package/dist/chunk-3LC4YUMA.js +0 -194
  9. package/dist/chunk-3MIR7ODJ.js +0 -112
  10. package/dist/chunk-3QZESA66.js +0 -222
  11. package/dist/chunk-4Z4MB37G.js +0 -96
  12. package/dist/chunk-5GFUI5N6.js +0 -132
  13. package/dist/chunk-5JEDLXEC.js +0 -99
  14. package/dist/chunk-5LTQNC7R.js +0 -824
  15. package/dist/chunk-5MA3CPZB.js +0 -141
  16. package/dist/chunk-5QHQVXWN.js +0 -174
  17. package/dist/chunk-5V3XJ2ES.js +0 -357
  18. package/dist/chunk-6A3WCJO2.js +0 -416
  19. package/dist/chunk-6QWFMVCD.js +0 -328
  20. package/dist/chunk-6SRXMZAN.js +0 -99
  21. package/dist/chunk-7OXL2QQ4.js +0 -357
  22. package/dist/chunk-7PTU7TGE.js +0 -96
  23. package/dist/chunk-AB4KX4XT.js +0 -109
  24. package/dist/chunk-AC4UYAGX.js +0 -136
  25. package/dist/chunk-ACE77TKQ.js +0 -328
  26. package/dist/chunk-BHAMEPOP.js +0 -323
  27. package/dist/chunk-BYNYYZWW.js +0 -412
  28. package/dist/chunk-C4BMEVK7.js +0 -208
  29. package/dist/chunk-C5TFTNHG.js +0 -244
  30. package/dist/chunk-CH53PBQN.js +0 -265
  31. package/dist/chunk-DF3BM6BF.js +0 -195
  32. package/dist/chunk-DKZVKEOW.js +0 -175
  33. package/dist/chunk-EMPL27ZV.js +0 -96
  34. package/dist/chunk-EQJXMEIR.js +0 -175
  35. package/dist/chunk-FB3N633T.js +0 -145
  36. package/dist/chunk-FGZZRCOG.js +0 -194
  37. package/dist/chunk-FXYTRZHC.js +0 -177
  38. package/dist/chunk-GTJGZBTQ.js +0 -328
  39. package/dist/chunk-GYPPVD3P.js +0 -1047
  40. package/dist/chunk-HJMFYDWY.js +0 -222
  41. package/dist/chunk-HRQEECB6.js +0 -315
  42. package/dist/chunk-HWEMAAOY.js +0 -370
  43. package/dist/chunk-I4GMPUYN.js +0 -231
  44. package/dist/chunk-IBWCHA5M.js +0 -10
  45. package/dist/chunk-JPRRYC5X.js +0 -328
  46. package/dist/chunk-KTM4ZQ3W.js +0 -96
  47. package/dist/chunk-KTP2EPVB.js +0 -27
  48. package/dist/chunk-KYARP7KP.js +0 -97
  49. package/dist/chunk-LXUHXG2X.js +0 -937
  50. package/dist/chunk-M2N5DYWN.js +0 -247
  51. package/dist/chunk-M4GDBGXF.js +0 -824
  52. package/dist/chunk-M5F2L4KF.js +0 -177
  53. package/dist/chunk-M6S3M6E3.js +0 -244
  54. package/dist/chunk-N7VXDBQU.js +0 -6
  55. package/dist/chunk-O2QL6U6G.js +0 -194
  56. package/dist/chunk-O6A5RHWY.js +0 -122
  57. package/dist/chunk-ODUXELPM.js +0 -219
  58. package/dist/chunk-OF5WIOYS.js +0 -129
  59. package/dist/chunk-OP4QAN23.js +0 -99
  60. package/dist/chunk-P4JH2Q7Z.js +0 -102
  61. package/dist/chunk-PMD5JSV3.js +0 -242
  62. package/dist/chunk-PSSHNBEL.js +0 -177
  63. package/dist/chunk-PZO7RZ5W.js +0 -145
  64. package/dist/chunk-QEPRH7JB.js +0 -315
  65. package/dist/chunk-QRXWPZKN.js +0 -308
  66. package/dist/chunk-QY4L6XHN.js +0 -384
  67. package/dist/chunk-RNWPCELY.js +0 -176
  68. package/dist/chunk-RSHN2AQ7.js +0 -29
  69. package/dist/chunk-RZLVE57X.js +0 -38
  70. package/dist/chunk-SDCIKREA.js +0 -241
  71. package/dist/chunk-SDREQWNI.js +0 -175
  72. package/dist/chunk-SH26ZOHU.js +0 -159
  73. package/dist/chunk-SJ5MC36D.js +0 -882
  74. package/dist/chunk-TRLBBLSS.js +0 -176
  75. package/dist/chunk-U6OXZPYC.js +0 -384
  76. package/dist/chunk-UDQZNO5H.js +0 -231
  77. package/dist/chunk-UIBTFZUD.js +0 -314
  78. package/dist/chunk-USUCPCUC.js +0 -156
  79. package/dist/chunk-UTK3TJC4.js +0 -882
  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-X6LV22NZ.js +0 -229
  90. package/dist/chunk-XHTZ2DWC.js +0 -206
  91. package/dist/chunk-XPVSZIA3.js +0 -315
  92. package/dist/chunk-Y633ZIJF.js +0 -384
  93. package/dist/chunk-YCL4GUFR.js +0 -222
  94. package/dist/chunk-YTMKB44I.js +0 -220
  95. package/dist/chunk-ZWBS3T7Q.js +0 -244
  96. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
  97. package/dist/pushary-wait-4BUC6ZM6.js +0 -93
@@ -1,412 +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-6QWFMVCD.js";
16
- import {
17
- withRetry
18
- } from "./chunk-DWED7BS3.js";
19
- import {
20
- getApiKey,
21
- getBaseUrl
22
- } from "./chunk-NKXSILEW.js";
23
-
24
- // src/codex-adapter.ts
25
- import { resolve } from "path";
26
- var CODEX_AGENT = { type: "codex", label: "Codex" };
27
- var codexAllow = () => ({ kind: "allow" });
28
- var codexDeny = (reason) => ({ kind: "deny", reason });
29
- var codexPass = () => ({ kind: "pass" });
30
- var toCodexWire = (event, decision) => {
31
- if (event === "PermissionRequest") {
32
- if (decision.kind === "allow") {
33
- return {
34
- hookSpecificOutput: {
35
- hookEventName: "PermissionRequest",
36
- decision: { behavior: "allow" }
37
- }
38
- };
39
- }
40
- if (decision.kind === "deny") {
41
- return {
42
- hookSpecificOutput: {
43
- hookEventName: "PermissionRequest",
44
- decision: { behavior: "deny", message: decision.reason }
45
- }
46
- };
47
- }
48
- return null;
49
- }
50
- if (event === "PreToolUse" && decision.kind === "deny") {
51
- return {
52
- hookSpecificOutput: {
53
- hookEventName: "PreToolUse",
54
- permissionDecision: "deny",
55
- permissionDecisionReason: decision.reason
56
- }
57
- };
58
- }
59
- return null;
60
- };
61
- var parseApplyPatchOps = (command) => {
62
- if (typeof command !== "string") return [];
63
- const ops = [];
64
- for (const line of command.split("\n")) {
65
- const file = line.match(/^\*\*\*\s+(Add|Update|Delete) File:\s+(.+?)\s*$/);
66
- if (file) {
67
- ops.push({ op: file[1].toLowerCase(), path: file[2] });
68
- continue;
69
- }
70
- const move = line.match(/^\*\*\*\s+Move to:\s+(.+?)\s*$/);
71
- if (move) ops.push({ op: "move", path: move[1] });
72
- }
73
- return ops;
74
- };
75
- var parseApplyPatchFiles = (command) => [...new Set(parseApplyPatchOps(command).map((entry) => entry.path))];
76
- var describeApplyPatch = (command) => {
77
- const ops = parseApplyPatchOps(command);
78
- if (ops.length === 0) return null;
79
- const files = [...new Set(ops.map((entry) => entry.path))];
80
- if (files.length === 1) {
81
- const verb = ops[0].op === "add" ? "create" : ops[0].op === "delete" ? "delete" : ops[0].op === "move" ? "move" : "edit";
82
- return `${verb} file: ${files[0]}`;
83
- }
84
- return `apply patch to ${files.length} files`;
85
- };
86
- var toPolicyLookup = (toolName, toolInput, cwd) => {
87
- if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
88
- const command = toolInput.command;
89
- const files = parseApplyPatchFiles(command);
90
- if (files.length === 1) {
91
- return { tool: "Edit", input: { file_path: cwd ? resolve(cwd, files[0]) : files[0] } };
92
- }
93
- return { tool: "Edit", input: typeof command === "string" ? { file_path: command } : {} };
94
- };
95
- var permissionTimeoutDecision = (timeoutAction) => {
96
- if (timeoutAction === "approve") return codexAllow();
97
- if (timeoutAction === "deny") return codexDeny("No response within timeout");
98
- return codexPass();
99
- };
100
- var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
101
-
102
- // src/usage.ts
103
- import { closeSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "fs";
104
- import { join } from "path";
105
- import { tmpdir } from "os";
106
- var DEFAULT_PRICES = [
107
- { match: "opus-4-1", in: 15, out: 75 },
108
- { match: "opus-4-0", in: 15, out: 75 },
109
- { match: "3-opus", in: 15, out: 75 },
110
- { match: "opus", in: 5, out: 25 },
111
- { match: "haiku", in: 1, out: 5 },
112
- { match: "sonnet", in: 3, out: 15 }
113
- ];
114
- var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
115
- var CACHE_WRITE_MULTIPLIER = 1.25;
116
- var CACHE_READ_MULTIPLIER = 0.1;
117
- var RECENT_ID_LIMIT = 200;
118
- var READ_CHUNK_BYTES = 1024 * 1024;
119
- var isModelPrice = (value) => {
120
- if (!value || typeof value !== "object") return false;
121
- const candidate = value;
122
- return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
123
- };
124
- var priceTable = () => {
125
- const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
126
- if (!raw) return DEFAULT_PRICES;
127
- try {
128
- const parsed = JSON.parse(raw);
129
- if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
130
- } catch {
131
- }
132
- return DEFAULT_PRICES;
133
- };
134
- var estimateCostUsd = (usage, model) => {
135
- const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
136
- const perTokenIn = price.in / 1e6;
137
- const perTokenOut = price.out / 1e6;
138
- return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
139
- };
140
- var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join(tmpdir(), "pushary-usage");
141
- var stateFile = (sessionId) => join(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
142
- var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
143
- var readState = (path) => {
144
- try {
145
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
146
- if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
147
- return {
148
- offset: parsed.offset,
149
- tokensIn: parsed.tokensIn,
150
- tokensOut: parsed.tokensOut,
151
- costUsd: parsed.costUsd,
152
- recentIds: parsed.recentIds.filter((id) => typeof id === "string")
153
- };
154
- }
155
- } catch {
156
- }
157
- return emptyState();
158
- };
159
- var readRange = (path, start, end) => {
160
- const fd = openSync(path, "r");
161
- try {
162
- const chunks = [];
163
- let position = start;
164
- while (position < end) {
165
- const length = Math.min(READ_CHUNK_BYTES, end - position);
166
- const buffer = Buffer.alloc(length);
167
- const bytesRead = readSync(fd, buffer, 0, length, position);
168
- if (bytesRead <= 0) break;
169
- chunks.push(buffer.subarray(0, bytesRead));
170
- position += bytesRead;
171
- }
172
- return Buffer.concat(chunks);
173
- } finally {
174
- closeSync(fd);
175
- }
176
- };
177
- var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
178
- var applyLine = (state, line) => {
179
- let parsed;
180
- try {
181
- parsed = JSON.parse(line);
182
- } catch {
183
- return 0;
184
- }
185
- if (parsed.type !== "assistant") return 0;
186
- const usage = parsed.message?.usage;
187
- if (!usage || typeof usage !== "object") return 0;
188
- const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
189
- if (model.includes("<synthetic>")) return 0;
190
- const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
191
- if (id) {
192
- if (state.recentIds.includes(id)) return 0;
193
- state.recentIds.push(id);
194
- if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
195
- }
196
- const messageUsage = {
197
- inputTokens: toCount(usage.input_tokens),
198
- outputTokens: toCount(usage.output_tokens),
199
- cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
200
- cacheReadTokens: toCount(usage.cache_read_input_tokens)
201
- };
202
- const cost = estimateCostUsd(messageUsage, model);
203
- state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
204
- state.tokensOut += messageUsage.outputTokens;
205
- state.costUsd += cost;
206
- return cost;
207
- };
208
- var readNewUsage = (transcriptPath, sessionId) => {
209
- try {
210
- const size = statSync(transcriptPath).size;
211
- const path = stateFile(sessionId);
212
- let state = readState(path);
213
- if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
214
- let deltaUsd = 0;
215
- if (size > state.offset) {
216
- const buffer = readRange(transcriptPath, state.offset, size);
217
- const lastNewline = buffer.lastIndexOf(10);
218
- if (lastNewline >= 0) {
219
- const complete = buffer.subarray(0, lastNewline + 1);
220
- for (const line of complete.toString("utf-8").split("\n")) {
221
- if (line.trim()) deltaUsd += applyLine(state, line);
222
- }
223
- state.offset += lastNewline + 1;
224
- }
225
- }
226
- mkdirSync(stateDir(), { recursive: true });
227
- writeFileSync(path, JSON.stringify(state), "utf-8");
228
- if (state.tokensIn === 0 && state.tokensOut === 0) return null;
229
- return {
230
- tokensIn: state.tokensIn,
231
- tokensOut: state.tokensOut,
232
- costUsd: state.costUsd,
233
- deltaUsd
234
- };
235
- } catch {
236
- return null;
237
- }
238
- };
239
-
240
- // src/events.ts
241
- import { basename, join as join2 } from "path";
242
- import { createHash } from "crypto";
243
- import { existsSync, readFileSync as readFileSync2 } from "fs";
244
- import { tmpdir as tmpdir2 } from "os";
245
- var cleanupPendingQuestions = async (sessionId) => {
246
- try {
247
- const files = listPendingQuestions(sessionId);
248
- const apiKey = getApiKey();
249
- for (const correlationId of files) {
250
- try {
251
- await cancelQuestion(apiKey, correlationId);
252
- } catch {
253
- }
254
- removePendingQuestion(sessionId, correlationId);
255
- }
256
- if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
257
- } catch {
258
- }
259
- };
260
- var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
261
- var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
262
- var readFreshCachedPolicy = (apiKey) => {
263
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
264
- const path = join2(tmpdir2(), `pushary-policy-${hash}.json`);
265
- if (!existsSync(path)) return null;
266
- const cached = JSON.parse(readFileSync2(path, "utf-8"));
267
- if (!isPolicyConfig(cached)) return null;
268
- if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
269
- return cached;
270
- };
271
- var deriveDecisionSource = (toolName, toolInput, liveMode) => {
272
- try {
273
- if (liveMode.kill) return "terminal";
274
- const policy = readFreshCachedPolicy(getApiKey());
275
- if (!policy) return void 0;
276
- const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
277
- if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
278
- if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
279
- return "terminal";
280
- } catch {
281
- return void 0;
282
- }
283
- };
284
- var deriveUsage = (transcriptPath, sessionId) => {
285
- if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
286
- try {
287
- return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
288
- } catch {
289
- return void 0;
290
- }
291
- };
292
- var reportEvent = async (event, options = {}) => {
293
- const apiKey = getApiKey();
294
- const baseUrl = getBaseUrl();
295
- return withRetry(async () => {
296
- const res = await fetch(`${baseUrl}/api/agent/event`, {
297
- method: "POST",
298
- headers: {
299
- "Content-Type": "application/json",
300
- "Authorization": `Bearer ${apiKey}`
301
- },
302
- body: JSON.stringify({
303
- ...event,
304
- machineId: event.machineId ?? getMachineId()
305
- }),
306
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
307
- });
308
- try {
309
- return await res.json();
310
- } catch {
311
- return null;
312
- }
313
- }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
314
- };
315
- var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
316
- try {
317
- const projectName = basename(input.cwd ?? process.cwd());
318
- const action = describeToolCall(input.tool_name, input.tool_input, "event");
319
- const lookup = toPolicyLookup(input.tool_name, input.tool_input);
320
- const isError = isToolResultError(input.tool_result);
321
- const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
322
- const liveMode = await fetchModeState(getApiKey(), input.session_id);
323
- await Promise.allSettled([
324
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
325
- reportEvent({
326
- event: isError ? "tool_error" : "tool_complete",
327
- agentType: agent.type,
328
- agentName: `${agent.label} - ${projectName}`,
329
- action,
330
- sessionId: input.session_id,
331
- error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
332
- decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
333
- meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
334
- usage: deriveUsage(input.transcript_path, input.session_id)
335
- })
336
- ]);
337
- } catch {
338
- }
339
- };
340
- var TASK_TITLE_MAX_LENGTH = 120;
341
- var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
342
- try {
343
- const projectName = basename(input.cwd ?? process.cwd());
344
- const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
345
- const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
346
- await reportEvent({
347
- event: "user_prompt",
348
- agentType: agent.type,
349
- agentName: `${agent.label} - ${projectName}`,
350
- sessionId: input.session_id,
351
- taskTitle
352
- }, { maxAttempts: 1, timeoutMs: 800 });
353
- } catch {
354
- }
355
- };
356
- var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
357
- try {
358
- const projectName = basename(input.cwd ?? process.cwd());
359
- const [, reported] = await Promise.allSettled([
360
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
361
- reportEvent({
362
- event: "session_end",
363
- agentType: agent.type,
364
- agentName: `${agent.label} - ${projectName}`,
365
- action: "Session ended",
366
- sessionId: input.session_id,
367
- usage: deriveUsage(input.transcript_path, input.session_id)
368
- })
369
- ]);
370
- const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
371
- if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
372
- return {
373
- decision: "block",
374
- reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
375
- };
376
- }
377
- return void 0;
378
- } catch {
379
- return void 0;
380
- }
381
- };
382
- var handleNotification = async (input) => {
383
- try {
384
- const projectName = basename(input.cwd ?? process.cwd());
385
- await reportEvent({
386
- event: input.type === "error" ? "error" : "notification",
387
- agentType: "claude_code",
388
- agentName: `Claude Code - ${projectName}`,
389
- action: input.title ?? input.message ?? "Notification",
390
- sessionId: input.session_id,
391
- error: input.type === "error" ? input.message : void 0
392
- });
393
- } catch {
394
- }
395
- };
396
-
397
- export {
398
- CODEX_AGENT,
399
- codexAllow,
400
- codexDeny,
401
- codexPass,
402
- toCodexWire,
403
- describeApplyPatch,
404
- toPolicyLookup,
405
- permissionTimeoutDecision,
406
- preToolUseTimeoutDecision,
407
- reportEvent,
408
- handlePostToolUse,
409
- handleUserPrompt,
410
- handleStop,
411
- handleNotification
412
- };
@@ -1,208 +0,0 @@
1
- // ../contracts/src/index.ts
2
- var APPROVAL_MODES = ["push_only", "terminal_only", "push_first", "notify_only"];
3
- var isApprovalMode = (value) => typeof value === "string" && APPROVAL_MODES.includes(value);
4
- var HOOK_BUDGETS = {
5
- claude: { budgetSeconds: 120, guardSeconds: 10 },
6
- codex: { budgetSeconds: 180, guardSeconds: 10 },
7
- gemini: { budgetSeconds: 180, guardSeconds: 10 },
8
- // The Cursor gate is a dependency-free .mjs that cannot import this module; it
9
- // mirrors these as MAX_BLOCK_MS (45s) inside its 60s failClosed budget.
10
- cursor: { budgetSeconds: 60, guardSeconds: 15 }
11
- };
12
- var hookMaxWaitSeconds = (agent) => Math.max(HOOK_BUDGETS[agent].budgetSeconds - HOOK_BUDGETS[agent].guardSeconds, 1);
13
- var hookWaitDeadline = (startMs, policyWaitSeconds, agent, nowMs) => {
14
- const maxWait = hookMaxWaitSeconds(agent);
15
- return Math.min(
16
- nowMs + Math.min(Math.max(policyWaitSeconds, 0), maxWait) * 1e3,
17
- startMs + maxWait * 1e3
18
- );
19
- };
20
- var hookWaitClamped = (startMs, policyWaitSeconds, agent, nowMs) => startMs + hookMaxWaitSeconds(agent) * 1e3 < nowMs + Math.max(policyWaitSeconds, 0) * 1e3;
21
- var effectiveWaitSeconds = (timeoutAction, policySeconds, agent) => timeoutAction === "wait" ? hookMaxWaitSeconds(agent) : policySeconds;
22
- var MATCH_RANKS = ["none", "tool", "prefix", "exact"];
23
- var matchRankWeight = (rank) => MATCH_RANKS.indexOf(rank);
24
- var matchToolPattern = (pattern, toolName, arg) => {
25
- const open = pattern.indexOf("(");
26
- if (open === -1 || !pattern.endsWith(")")) {
27
- return pattern === toolName ? "tool" : "none";
28
- }
29
- if (pattern.slice(0, open) !== toolName || arg === void 0) return "none";
30
- const inner = pattern.slice(open + 1, -1);
31
- if (inner.endsWith(":*")) {
32
- return arg.startsWith(inner.slice(0, -2)) ? "prefix" : "none";
33
- }
34
- return arg === inner ? "exact" : "none";
35
- };
36
- var POLICY_ARG_KEYS = {
37
- Bash: "command",
38
- Edit: "file_path",
39
- Write: "file_path"
40
- };
41
- var extractPolicyArg = (toolName, toolInput) => {
42
- const key = POLICY_ARG_KEYS[toolName];
43
- if (!key) return void 0;
44
- const value = toolInput[key];
45
- return typeof value === "string" ? value : void 0;
46
- };
47
- var SAFE_SHELL_COMMANDS = /* @__PURE__ */ new Set([
48
- "ls",
49
- "pwd",
50
- "cd",
51
- "cat",
52
- "head",
53
- "tail",
54
- "wc",
55
- "echo",
56
- "printf",
57
- "which",
58
- "type",
59
- "whoami",
60
- "id",
61
- "uname",
62
- "arch",
63
- "printenv",
64
- "locale",
65
- "tty",
66
- "dirname",
67
- "basename",
68
- "realpath",
69
- "readlink",
70
- "stat",
71
- "cut",
72
- "nl",
73
- "tr",
74
- "comm",
75
- "diff",
76
- "cmp",
77
- "grep",
78
- "egrep",
79
- "fgrep",
80
- "jq",
81
- "cksum",
82
- "md5sum",
83
- "sha1sum",
84
- "sha256sum",
85
- "du",
86
- "df",
87
- "ps",
88
- "true"
89
- ]);
90
- var SAFE_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
91
- "status",
92
- "log",
93
- "diff",
94
- "show",
95
- "rev-parse",
96
- "describe",
97
- "blame",
98
- "shortlog",
99
- "ls-files",
100
- "ls-tree",
101
- "cat-file",
102
- "whatchanged",
103
- "rev-list",
104
- "name-rev",
105
- "for-each-ref",
106
- "var",
107
- "count-objects"
108
- ]);
109
- var GIT_WRITE_FLAGS = (token) => token === "--output" || token.startsWith("--output=");
110
- var UNSAFE_SHELL_CHARS = /[;&|<>(){}`\\\n\r]/;
111
- var basenameOf = (token) => {
112
- const slash = Math.max(token.lastIndexOf("/"), token.lastIndexOf("\\"));
113
- return slash === -1 ? token : token.slice(slash + 1);
114
- };
115
- var tokenizeShellCommand = (command) => {
116
- const tokens = [];
117
- let current = "";
118
- let quote = null;
119
- let started = false;
120
- for (const ch of command) {
121
- if (quote) {
122
- if (ch === quote) quote = null;
123
- else current += ch;
124
- started = true;
125
- continue;
126
- }
127
- if (ch === '"' || ch === "'") {
128
- quote = ch;
129
- started = true;
130
- continue;
131
- }
132
- if (ch === " " || ch === " ") {
133
- if (started) {
134
- tokens.push(current);
135
- current = "";
136
- started = false;
137
- }
138
- continue;
139
- }
140
- current += ch;
141
- started = true;
142
- }
143
- if (quote) return null;
144
- if (started) tokens.push(current);
145
- return tokens;
146
- };
147
- var isSafeReadOnlyCommand = (command) => {
148
- const trimmed = command.trim();
149
- if (!trimmed || trimmed.length > 2e3) return false;
150
- if (UNSAFE_SHELL_CHARS.test(trimmed)) return false;
151
- const tokens = tokenizeShellCommand(trimmed);
152
- if (!tokens || tokens.length === 0) return false;
153
- const first = tokens[0];
154
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first) || first.includes("$")) return false;
155
- const exe = basenameOf(first);
156
- if (exe === "git") {
157
- const sub = tokens[1];
158
- if (!sub || sub.startsWith("-")) return false;
159
- if (!SAFE_GIT_SUBCOMMANDS.has(sub)) return false;
160
- return !tokens.some(GIT_WRITE_FLAGS);
161
- }
162
- return SAFE_SHELL_COMMANDS.has(exe);
163
- };
164
- var API_KEY_PATTERN = /^pk_[a-f0-9]+\.[a-f0-9]+$/;
165
- var isValidApiKey = (value) => API_KEY_PATTERN.test(value);
166
- var ACTION_BODY_MAX = 4e3;
167
- var DECISION_LINE_MAX = 500;
168
- var SECRET_REDACTION_RULES = [
169
- { pattern: /-----BEGIN[A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END[A-Z0-9 ]*PRIVATE KEY-----/g, replacement: "[redacted key]" },
170
- { pattern: /\bsk-[A-Za-z0-9_-]{16,}\b/g, replacement: "[redacted]" },
171
- { pattern: /\b[spr]k_(?:live|test)_[A-Za-z0-9]{8,}\b/g, replacement: "[redacted]" },
172
- { pattern: /\bwhsec_[A-Za-z0-9]{16,}\b/g, replacement: "[redacted]" },
173
- { pattern: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/g, replacement: "[redacted]" },
174
- { pattern: /\bgithub_pat_[A-Za-z0-9_]{22,}\b/g, replacement: "[redacted]" },
175
- { pattern: /\bglpat-[A-Za-z0-9_-]{20,}\b/g, replacement: "[redacted]" },
176
- { pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, replacement: "[redacted]" },
177
- { pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g, replacement: "[redacted]" },
178
- { pattern: /\bAKIA[0-9A-Z]{16}\b/g, replacement: "[redacted]" },
179
- { pattern: /\bnpm_[A-Za-z0-9]{36}\b/g, replacement: "[redacted]" },
180
- { pattern: /\bxai-[A-Za-z0-9]{16,}\b/g, replacement: "[redacted]" },
181
- { pattern: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, replacement: "[redacted]" },
182
- { pattern: /\bbearer\s+[A-Za-z0-9._~+/=-]+/gi, replacement: "bearer [redacted]" },
183
- { pattern: /\bauthorization:\s*\S+/gi, replacement: "authorization: [redacted]" },
184
- {
185
- pattern: /((?:secret|token|password|passwd|api[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key)\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi,
186
- replacement: "$1[redacted]"
187
- }
188
- ];
189
- var HIGH_ENTROPY_RULE = { pattern: /[A-Za-z0-9+/]{40,}={0,2}/g, replacement: "[redacted]" };
190
- var redactSecrets = (text) => SECRET_REDACTION_RULES.reduce((acc, rule) => acc.replace(rule.pattern, rule.replacement), text);
191
- var redactSecretsDeep = (text) => redactSecrets(text).replace(HIGH_ENTROPY_RULE.pattern, HIGH_ENTROPY_RULE.replacement);
192
-
193
- export {
194
- isApprovalMode,
195
- HOOK_BUDGETS,
196
- hookWaitDeadline,
197
- hookWaitClamped,
198
- effectiveWaitSeconds,
199
- matchRankWeight,
200
- matchToolPattern,
201
- extractPolicyArg,
202
- isSafeReadOnlyCommand,
203
- isValidApiKey,
204
- ACTION_BODY_MAX,
205
- DECISION_LINE_MAX,
206
- redactSecrets,
207
- redactSecretsDeep
208
- };