@pushary/agent-hooks 0.28.1 → 0.28.3

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,174 +0,0 @@
1
- import {
2
- DEFAULT_SESSION,
3
- askUser,
4
- deriveToolTarget,
5
- describeToolCall,
6
- fetchModeState,
7
- getMachineId,
8
- getPolicy,
9
- resolvePolicy,
10
- savePendingQuestion,
11
- sendNotification,
12
- waitForAnswer
13
- } from "./chunk-XPVSZIA3.js";
14
- import {
15
- getApiKey
16
- } from "./chunk-VUNL35KE.js";
17
-
18
- // src/hook.ts
19
- import { basename } from "path";
20
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
- var allow = () => ({
22
- hookSpecificOutput: {
23
- hookEventName: "PreToolUse",
24
- permissionDecision: "allow"
25
- }
26
- });
27
- var deny = (reason) => ({
28
- hookSpecificOutput: {
29
- hookEventName: "PreToolUse",
30
- permissionDecision: "deny",
31
- permissionDecisionReason: reason
32
- }
33
- });
34
- var ask = (reason) => ({
35
- hookSpecificOutput: {
36
- hookEventName: "PreToolUse",
37
- permissionDecision: "ask",
38
- ...reason ? { permissionDecisionReason: reason } : {}
39
- }
40
- });
41
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
42
- while (Date.now() < deadlineMs) {
43
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
44
- let answer;
45
- try {
46
- answer = await waitForAnswer(apiKey, correlationId, remaining);
47
- } catch {
48
- if (Date.now() + pollInterval >= deadlineMs) break;
49
- await sleep(pollInterval);
50
- continue;
51
- }
52
- if (answer.answered) return answer;
53
- if (Date.now() + pollInterval >= deadlineMs) break;
54
- await sleep(pollInterval);
55
- }
56
- return { answered: false };
57
- };
58
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
59
- let result;
60
- try {
61
- result = await askUser(apiKey, {
62
- question: `Allow ${description}?`,
63
- type: "confirm",
64
- context: `Agent wants to run this in ${projectName}`,
65
- agentName: `Claude Code - ${projectName}`,
66
- sessionId,
67
- machineId,
68
- toolName,
69
- toolTarget
70
- });
71
- } catch {
72
- switch (timeoutAction) {
73
- case "approve":
74
- return allow();
75
- case "deny":
76
- return deny("Push notification failed, denying per policy");
77
- default:
78
- return ask("Push notification failed, asking in terminal");
79
- }
80
- }
81
- const deadline = Date.now() + timeoutSeconds * 1e3;
82
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
83
- if (answer.answered) {
84
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
85
- }
86
- switch (timeoutAction) {
87
- case "approve":
88
- return allow();
89
- case "deny":
90
- return deny("No response within timeout");
91
- default:
92
- return ask("No push response, asking in terminal");
93
- }
94
- };
95
- var handleTerminalOnly = () => {
96
- return ask();
97
- };
98
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
99
- let result;
100
- try {
101
- result = await askUser(apiKey, {
102
- question: `Allow ${description}?`,
103
- type: "confirm",
104
- context: `Agent wants to run this in ${projectName}`,
105
- agentName: `Claude Code - ${projectName}`,
106
- sessionId,
107
- machineId,
108
- toolName,
109
- toolTarget
110
- });
111
- } catch {
112
- return ask("Push notification failed, asking in terminal");
113
- }
114
- const deadline = Date.now() + pushFirstSeconds * 1e3;
115
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
116
- if (answer.answered) {
117
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
118
- }
119
- savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
120
- return ask("Sent as push notification. You can also approve here.");
121
- };
122
- var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
123
- try {
124
- await sendNotification(apiKey, {
125
- title: "Agent needs approval",
126
- body: description,
127
- agentName: `Claude Code - ${projectName}`,
128
- sessionId,
129
- machineId
130
- });
131
- } catch {
132
- }
133
- return ask();
134
- };
135
- var handlePreToolUse = async (input) => {
136
- try {
137
- const apiKey = getApiKey();
138
- const modeState = await fetchModeState(apiKey, input.session_id);
139
- const policy = await getPolicy(apiKey, modeState.policyVersion);
140
- if (modeState.kill) {
141
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
142
- }
143
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
144
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
145
- return allow();
146
- }
147
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
148
- return deny(`Denied by policy for ${toolPolicy.tool}`);
149
- }
150
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
151
- const projectName = basename(input.cwd ?? process.cwd());
152
- const sessionId = input.session_id;
153
- const machineId = getMachineId();
154
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
155
- switch (toolPolicy.mode) {
156
- case "push_only":
157
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
158
- case "terminal_only":
159
- return handleTerminalOnly();
160
- case "push_first":
161
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
162
- case "notify_only":
163
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
164
- default:
165
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
166
- }
167
- } catch {
168
- return ask("Pushary unavailable, falling back to terminal approval");
169
- }
170
- };
171
-
172
- export {
173
- handlePreToolUse
174
- };
@@ -1,142 +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/npm.ts
110
- import { execSync } from "child_process";
111
- var cleanNpmEnv = () => {
112
- const env = {};
113
- for (const [key, value] of Object.entries(process.env)) {
114
- if (key.toLowerCase().startsWith("npm_config_workspace")) continue;
115
- env[key] = value;
116
- }
117
- return env;
118
- };
119
- var npmErrorMessage = (err) => {
120
- const e = err;
121
- const text = [e?.stderr, e?.stdout].map((part) => part ? part.toString() : "").join("\n");
122
- 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));
123
- return line || e?.message || String(err);
124
- };
125
- var execNpm = (args, options = {}) => {
126
- return execSync(`npm ${args}`, {
127
- timeout: 12e4,
128
- stdio: "pipe",
129
- ...options,
130
- env: { ...cleanNpmEnv(), ...options.env ?? {} }
131
- });
132
- };
133
-
134
- export {
135
- addCodexHooks,
136
- removeCodexHooks,
137
- hasCodexHooks,
138
- missingCodexHookEvents,
139
- addCodexHookTrust,
140
- npmErrorMessage,
141
- execNpm
142
- };
@@ -1,88 +0,0 @@
1
- // src/config.ts
2
- var getApiKey = () => {
3
- const key = process.env.PUSHARY_API_KEY;
4
- if (!key) {
5
- throw new Error(
6
- "PUSHARY_API_KEY environment variable is not set. Get your API key at https://pushary.com/sign-up?from=ai-coding"
7
- );
8
- }
9
- return key;
10
- };
11
- var getBaseUrl = () => process.env.PUSHARY_BASE_URL ?? "https://pushary.com";
12
-
13
- // src/mcp-http.ts
14
- var parseSseJson = (body) => {
15
- const messages = [];
16
- for (const event of body.split(/\r?\n\r?\n/)) {
17
- const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n").trim();
18
- if (!data) continue;
19
- messages.push(JSON.parse(data));
20
- }
21
- const message = messages.at(-1);
22
- if (!message) throw new Error("Empty response from Pushary");
23
- return message;
24
- };
25
- var parseMcpResponse = (body, contentType) => {
26
- if (contentType?.includes("text/event-stream")) {
27
- return parseSseJson(body);
28
- }
29
- return JSON.parse(body);
30
- };
31
- var sendMcpRequest = async (apiKey, message, options = {}) => {
32
- const baseUrl = options.baseUrl ?? getBaseUrl();
33
- const fetchFn = options.fetchFn ?? fetch;
34
- const headers = {
35
- "Content-Type": "application/json",
36
- "Accept": "application/json, text/event-stream",
37
- "Authorization": `Bearer ${apiKey}`
38
- };
39
- if (options.sessionId) {
40
- headers["Mcp-Session-Id"] = options.sessionId;
41
- }
42
- const response = await fetchFn(`${baseUrl}/api/mcp/mcp`, {
43
- method: "POST",
44
- headers,
45
- body: JSON.stringify(message),
46
- signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0
47
- });
48
- const body = await response.text();
49
- const contentType = response.headers.get("content-type");
50
- let data = null;
51
- if (body.trim()) {
52
- try {
53
- data = parseMcpResponse(body, contentType);
54
- } catch (err) {
55
- if (response.ok) throw err;
56
- }
57
- }
58
- if (!response.ok) {
59
- const message2 = data?.error?.message ?? (body.trim() || response.statusText);
60
- throw new Error(`Pushary MCP error: ${response.status} ${message2}`);
61
- }
62
- if (!data) throw new Error("Empty response from Pushary");
63
- if (data.error) throw new Error(data.error.message ?? "Pushary MCP error");
64
- return {
65
- data,
66
- sessionId: response.headers.get("mcp-session-id") ?? "",
67
- status: response.status,
68
- statusText: response.statusText
69
- };
70
- };
71
- var callMcpTool = async (apiKey, toolName, params, options = {}) => {
72
- const { data } = await sendMcpRequest(apiKey, {
73
- jsonrpc: "2.0",
74
- id: options.id ?? Date.now(),
75
- method: "tools/call",
76
- params: { name: toolName, arguments: params }
77
- }, options);
78
- const text = data.result?.content?.[0]?.text;
79
- if (!text) throw new Error("Empty response from Pushary");
80
- return JSON.parse(text);
81
- };
82
-
83
- export {
84
- getApiKey,
85
- getBaseUrl,
86
- sendMcpRequest,
87
- callMcpTool
88
- };
@@ -1,16 +0,0 @@
1
- // src/config.ts
2
- var getApiKey = () => {
3
- const key = process.env.PUSHARY_API_KEY;
4
- if (!key) {
5
- throw new Error(
6
- "PUSHARY_API_KEY environment variable is not set. Get your API key at https://pushary.com/sign-up?from=ai-coding"
7
- );
8
- }
9
- return key;
10
- };
11
- var getBaseUrl = () => process.env.PUSHARY_BASE_URL ?? "https://pushary.com";
12
-
13
- export {
14
- getApiKey,
15
- getBaseUrl
16
- };
@@ -1,174 +0,0 @@
1
- import {
2
- DEFAULT_SESSION,
3
- askUser,
4
- deriveToolTarget,
5
- describeToolCall,
6
- fetchModeState,
7
- getMachineId,
8
- getPolicy,
9
- resolvePolicy,
10
- savePendingQuestion,
11
- sendNotification,
12
- waitForAnswer
13
- } from "./chunk-HRQEECB6.js";
14
- import {
15
- getApiKey
16
- } from "./chunk-NKXSILEW.js";
17
-
18
- // src/hook.ts
19
- import { basename } from "path";
20
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
- var allow = () => ({
22
- hookSpecificOutput: {
23
- hookEventName: "PreToolUse",
24
- permissionDecision: "allow"
25
- }
26
- });
27
- var deny = (reason) => ({
28
- hookSpecificOutput: {
29
- hookEventName: "PreToolUse",
30
- permissionDecision: "deny",
31
- permissionDecisionReason: reason
32
- }
33
- });
34
- var ask = (reason) => ({
35
- hookSpecificOutput: {
36
- hookEventName: "PreToolUse",
37
- permissionDecision: "ask",
38
- ...reason ? { permissionDecisionReason: reason } : {}
39
- }
40
- });
41
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
42
- while (Date.now() < deadlineMs) {
43
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
44
- let answer;
45
- try {
46
- answer = await waitForAnswer(apiKey, correlationId, remaining);
47
- } catch {
48
- if (Date.now() + pollInterval >= deadlineMs) break;
49
- await sleep(pollInterval);
50
- continue;
51
- }
52
- if (answer.answered) return answer;
53
- if (Date.now() + pollInterval >= deadlineMs) break;
54
- await sleep(pollInterval);
55
- }
56
- return { answered: false };
57
- };
58
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
59
- let result;
60
- try {
61
- result = await askUser(apiKey, {
62
- question: `Allow ${description}?`,
63
- type: "confirm",
64
- context: `Agent wants to run this in ${projectName}`,
65
- agentName: `Claude Code - ${projectName}`,
66
- sessionId,
67
- machineId,
68
- toolName,
69
- toolTarget
70
- });
71
- } catch {
72
- switch (timeoutAction) {
73
- case "approve":
74
- return allow();
75
- case "deny":
76
- return deny("Push notification failed, denying per policy");
77
- default:
78
- return ask("Push notification failed, asking in terminal");
79
- }
80
- }
81
- const deadline = Date.now() + timeoutSeconds * 1e3;
82
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
83
- if (answer.answered) {
84
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
85
- }
86
- switch (timeoutAction) {
87
- case "approve":
88
- return allow();
89
- case "deny":
90
- return deny("No response within timeout");
91
- default:
92
- return ask("No push response, asking in terminal");
93
- }
94
- };
95
- var handleTerminalOnly = () => {
96
- return ask();
97
- };
98
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
99
- let result;
100
- try {
101
- result = await askUser(apiKey, {
102
- question: `Allow ${description}?`,
103
- type: "confirm",
104
- context: `Agent wants to run this in ${projectName}`,
105
- agentName: `Claude Code - ${projectName}`,
106
- sessionId,
107
- machineId,
108
- toolName,
109
- toolTarget
110
- });
111
- } catch {
112
- return ask("Push notification failed, asking in terminal");
113
- }
114
- const deadline = Date.now() + pushFirstSeconds * 1e3;
115
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
116
- if (answer.answered) {
117
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
118
- }
119
- savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
120
- return ask("Sent as push notification. You can also approve here.");
121
- };
122
- var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
123
- try {
124
- await sendNotification(apiKey, {
125
- title: "Agent needs approval",
126
- body: description,
127
- agentName: `Claude Code - ${projectName}`,
128
- sessionId,
129
- machineId
130
- });
131
- } catch {
132
- }
133
- return ask();
134
- };
135
- var handlePreToolUse = async (input) => {
136
- try {
137
- const apiKey = getApiKey();
138
- const modeState = await fetchModeState(apiKey, input.session_id);
139
- const policy = await getPolicy(apiKey, modeState.policyVersion);
140
- if (modeState.kill) {
141
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
142
- }
143
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
144
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
145
- return allow();
146
- }
147
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
148
- return deny(`Denied by policy for ${toolPolicy.tool}`);
149
- }
150
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
151
- const projectName = basename(input.cwd ?? process.cwd());
152
- const sessionId = input.session_id;
153
- const machineId = getMachineId();
154
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
155
- switch (toolPolicy.mode) {
156
- case "push_only":
157
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
158
- case "terminal_only":
159
- return handleTerminalOnly();
160
- case "push_first":
161
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
162
- case "notify_only":
163
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
164
- default:
165
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
166
- }
167
- } catch {
168
- return ask("Pushary unavailable, falling back to terminal approval");
169
- }
170
- };
171
-
172
- export {
173
- handlePreToolUse
174
- };