@pushary/agent-hooks 0.21.0 → 0.22.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.
@@ -0,0 +1,177 @@
1
+ import {
2
+ denyReasonFrom
3
+ } from "./chunk-N7VXDBQU.js";
4
+ import {
5
+ DEFAULT_SESSION,
6
+ askUser,
7
+ deriveToolTarget,
8
+ describeToolCall,
9
+ fetchModeState,
10
+ getMachineId,
11
+ getPolicy,
12
+ resolvePolicy,
13
+ savePendingQuestion,
14
+ sendNotification,
15
+ waitForAnswer
16
+ } from "./chunk-6QWFMVCD.js";
17
+ import {
18
+ getApiKey
19
+ } from "./chunk-NKXSILEW.js";
20
+
21
+ // src/hook.ts
22
+ import { basename } from "path";
23
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ var allow = () => ({
25
+ hookSpecificOutput: {
26
+ hookEventName: "PreToolUse",
27
+ permissionDecision: "allow"
28
+ }
29
+ });
30
+ var deny = (reason) => ({
31
+ hookSpecificOutput: {
32
+ hookEventName: "PreToolUse",
33
+ permissionDecision: "deny",
34
+ permissionDecisionReason: reason
35
+ }
36
+ });
37
+ var ask = (reason) => ({
38
+ hookSpecificOutput: {
39
+ hookEventName: "PreToolUse",
40
+ permissionDecision: "ask",
41
+ ...reason ? { permissionDecisionReason: reason } : {}
42
+ }
43
+ });
44
+ var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
45
+ while (Date.now() < deadlineMs) {
46
+ const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
47
+ let answer;
48
+ try {
49
+ answer = await waitForAnswer(apiKey, correlationId, remaining);
50
+ } catch {
51
+ if (Date.now() + pollInterval >= deadlineMs) break;
52
+ await sleep(pollInterval);
53
+ continue;
54
+ }
55
+ if (answer.answered) return answer;
56
+ if (Date.now() + pollInterval >= deadlineMs) break;
57
+ await sleep(pollInterval);
58
+ }
59
+ return { answered: false };
60
+ };
61
+ var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
62
+ let result;
63
+ try {
64
+ result = await askUser(apiKey, {
65
+ question: `Allow ${description}?`,
66
+ type: "confirm",
67
+ context: `Agent wants to run this in ${projectName}`,
68
+ agentName: `Claude Code - ${projectName}`,
69
+ sessionId,
70
+ machineId,
71
+ toolName,
72
+ toolTarget
73
+ });
74
+ } catch {
75
+ switch (timeoutAction) {
76
+ case "approve":
77
+ return allow();
78
+ case "deny":
79
+ return deny("Push notification failed, denying per policy");
80
+ default:
81
+ return ask("Push notification failed, asking in terminal");
82
+ }
83
+ }
84
+ const deadline = Date.now() + timeoutSeconds * 1e3;
85
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
86
+ if (answer.answered) {
87
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
88
+ }
89
+ switch (timeoutAction) {
90
+ case "approve":
91
+ return allow();
92
+ case "deny":
93
+ return deny("No response within timeout");
94
+ default:
95
+ return ask("No push response, asking in terminal");
96
+ }
97
+ };
98
+ var handleTerminalOnly = () => {
99
+ return ask();
100
+ };
101
+ var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
102
+ let result;
103
+ try {
104
+ result = await askUser(apiKey, {
105
+ question: `Allow ${description}?`,
106
+ type: "confirm",
107
+ context: `Agent wants to run this in ${projectName}`,
108
+ agentName: `Claude Code - ${projectName}`,
109
+ sessionId,
110
+ machineId,
111
+ toolName,
112
+ toolTarget
113
+ });
114
+ } catch {
115
+ return ask("Push notification failed, asking in terminal");
116
+ }
117
+ const deadline = Date.now() + pushFirstSeconds * 1e3;
118
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
119
+ if (answer.answered) {
120
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
121
+ }
122
+ savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
123
+ return ask("Sent as push notification. You can also approve here.");
124
+ };
125
+ var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
126
+ try {
127
+ await sendNotification(apiKey, {
128
+ title: "Agent needs approval",
129
+ body: description,
130
+ agentName: `Claude Code - ${projectName}`,
131
+ sessionId,
132
+ machineId
133
+ });
134
+ } catch {
135
+ }
136
+ return ask();
137
+ };
138
+ var handlePreToolUse = async (input) => {
139
+ try {
140
+ const apiKey = getApiKey();
141
+ const modeState = await fetchModeState(apiKey, input.session_id);
142
+ const policy = await getPolicy(apiKey, modeState.policyVersion);
143
+ if (modeState.kill) {
144
+ return deny("Stopped by user \u2014 this agent was halted from Pushary");
145
+ }
146
+ const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
147
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
148
+ return allow();
149
+ }
150
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
151
+ return deny(`Denied by policy for ${toolPolicy.tool}`);
152
+ }
153
+ const description = describeToolCall(input.tool_name, input.tool_input, "hook");
154
+ const projectName = basename(input.cwd ?? process.cwd());
155
+ const sessionId = input.session_id;
156
+ const machineId = getMachineId();
157
+ const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
158
+ switch (toolPolicy.mode) {
159
+ case "push_only":
160
+ return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
161
+ case "terminal_only":
162
+ return handleTerminalOnly();
163
+ case "push_first":
164
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
165
+ case "notify_only":
166
+ return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
167
+ default:
168
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
169
+ }
170
+ } catch {
171
+ return ask("Pushary unavailable, falling back to terminal approval");
172
+ }
173
+ };
174
+
175
+ export {
176
+ handlePreToolUse
177
+ };
@@ -0,0 +1,177 @@
1
+ import {
2
+ denyReasonFrom
3
+ } from "./chunk-N7VXDBQU.js";
4
+ import {
5
+ DEFAULT_SESSION,
6
+ askUser,
7
+ deriveToolTarget,
8
+ describeToolCall,
9
+ fetchModeState,
10
+ getMachineId,
11
+ getPolicy,
12
+ resolvePolicy,
13
+ savePendingQuestion,
14
+ sendNotification,
15
+ waitForAnswer
16
+ } from "./chunk-GTJGZBTQ.js";
17
+ import {
18
+ getApiKey
19
+ } from "./chunk-NKXSILEW.js";
20
+
21
+ // src/hook.ts
22
+ import { basename } from "path";
23
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ var allow = () => ({
25
+ hookSpecificOutput: {
26
+ hookEventName: "PreToolUse",
27
+ permissionDecision: "allow"
28
+ }
29
+ });
30
+ var deny = (reason) => ({
31
+ hookSpecificOutput: {
32
+ hookEventName: "PreToolUse",
33
+ permissionDecision: "deny",
34
+ permissionDecisionReason: reason
35
+ }
36
+ });
37
+ var ask = (reason) => ({
38
+ hookSpecificOutput: {
39
+ hookEventName: "PreToolUse",
40
+ permissionDecision: "ask",
41
+ ...reason ? { permissionDecisionReason: reason } : {}
42
+ }
43
+ });
44
+ var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
45
+ while (Date.now() < deadlineMs) {
46
+ const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
47
+ let answer;
48
+ try {
49
+ answer = await waitForAnswer(apiKey, correlationId, remaining);
50
+ } catch {
51
+ if (Date.now() + pollInterval >= deadlineMs) break;
52
+ await sleep(pollInterval);
53
+ continue;
54
+ }
55
+ if (answer.answered) return answer;
56
+ if (Date.now() + pollInterval >= deadlineMs) break;
57
+ await sleep(pollInterval);
58
+ }
59
+ return { answered: false };
60
+ };
61
+ var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
62
+ let result;
63
+ try {
64
+ result = await askUser(apiKey, {
65
+ question: `Allow ${description}?`,
66
+ type: "confirm",
67
+ context: `Agent wants to run this in ${projectName}`,
68
+ agentName: `Claude Code - ${projectName}`,
69
+ sessionId,
70
+ machineId,
71
+ toolName,
72
+ toolTarget
73
+ });
74
+ } catch {
75
+ switch (timeoutAction) {
76
+ case "approve":
77
+ return allow();
78
+ case "deny":
79
+ return deny("Push notification failed, denying per policy");
80
+ default:
81
+ return ask("Push notification failed, asking in terminal");
82
+ }
83
+ }
84
+ const deadline = Date.now() + timeoutSeconds * 1e3;
85
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
86
+ if (answer.answered) {
87
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
88
+ }
89
+ switch (timeoutAction) {
90
+ case "approve":
91
+ return allow();
92
+ case "deny":
93
+ return deny("No response within timeout");
94
+ default:
95
+ return ask("No push response, asking in terminal");
96
+ }
97
+ };
98
+ var handleTerminalOnly = () => {
99
+ return ask();
100
+ };
101
+ var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
102
+ let result;
103
+ try {
104
+ result = await askUser(apiKey, {
105
+ question: `Allow ${description}?`,
106
+ type: "confirm",
107
+ context: `Agent wants to run this in ${projectName}`,
108
+ agentName: `Claude Code - ${projectName}`,
109
+ sessionId,
110
+ machineId,
111
+ toolName,
112
+ toolTarget
113
+ });
114
+ } catch {
115
+ return ask("Push notification failed, asking in terminal");
116
+ }
117
+ const deadline = Date.now() + pushFirstSeconds * 1e3;
118
+ const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
119
+ if (answer.answered) {
120
+ return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
121
+ }
122
+ savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
123
+ return ask("Sent as push notification. You can also approve here.");
124
+ };
125
+ var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
126
+ try {
127
+ await sendNotification(apiKey, {
128
+ title: "Agent needs approval",
129
+ body: description,
130
+ agentName: `Claude Code - ${projectName}`,
131
+ sessionId,
132
+ machineId
133
+ });
134
+ } catch {
135
+ }
136
+ return ask();
137
+ };
138
+ var handlePreToolUse = async (input) => {
139
+ try {
140
+ const apiKey = getApiKey();
141
+ const modeState = await fetchModeState(apiKey, input.session_id);
142
+ const policy = await getPolicy(apiKey, modeState.policyVersion);
143
+ if (modeState.kill) {
144
+ return deny("Stopped by user \u2014 this agent was halted from Pushary");
145
+ }
146
+ const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
147
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
148
+ return allow();
149
+ }
150
+ if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
151
+ return deny(`Denied by policy for ${toolPolicy.tool}`);
152
+ }
153
+ const description = describeToolCall(input.tool_name, input.tool_input, "hook");
154
+ const projectName = basename(input.cwd ?? process.cwd());
155
+ const sessionId = input.session_id;
156
+ const machineId = getMachineId();
157
+ const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
158
+ switch (toolPolicy.mode) {
159
+ case "push_only":
160
+ return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
161
+ case "terminal_only":
162
+ return handleTerminalOnly();
163
+ case "push_first":
164
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
165
+ case "notify_only":
166
+ return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
167
+ default:
168
+ return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
169
+ }
170
+ } catch {
171
+ return ask("Pushary unavailable, falling back to terminal approval");
172
+ }
173
+ };
174
+
175
+ export {
176
+ handlePreToolUse
177
+ };
@@ -0,0 +1,160 @@
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 MATCH_RANKS = ["none", "tool", "prefix", "exact"];
5
+ var matchRankWeight = (rank) => MATCH_RANKS.indexOf(rank);
6
+ var matchToolPattern = (pattern, toolName, arg) => {
7
+ const open = pattern.indexOf("(");
8
+ if (open === -1 || !pattern.endsWith(")")) {
9
+ return pattern === toolName ? "tool" : "none";
10
+ }
11
+ if (pattern.slice(0, open) !== toolName || arg === void 0) return "none";
12
+ const inner = pattern.slice(open + 1, -1);
13
+ if (inner.endsWith(":*")) {
14
+ return arg.startsWith(inner.slice(0, -2)) ? "prefix" : "none";
15
+ }
16
+ return arg === inner ? "exact" : "none";
17
+ };
18
+ var POLICY_ARG_KEYS = {
19
+ Bash: "command",
20
+ Edit: "file_path",
21
+ Write: "file_path"
22
+ };
23
+ var extractPolicyArg = (toolName, toolInput) => {
24
+ const key = POLICY_ARG_KEYS[toolName];
25
+ if (!key) return void 0;
26
+ const value = toolInput[key];
27
+ return typeof value === "string" ? value : void 0;
28
+ };
29
+ var SAFE_SHELL_COMMANDS = /* @__PURE__ */ new Set([
30
+ "ls",
31
+ "pwd",
32
+ "cd",
33
+ "cat",
34
+ "head",
35
+ "tail",
36
+ "wc",
37
+ "echo",
38
+ "printf",
39
+ "which",
40
+ "type",
41
+ "whoami",
42
+ "id",
43
+ "uname",
44
+ "arch",
45
+ "printenv",
46
+ "locale",
47
+ "tty",
48
+ "dirname",
49
+ "basename",
50
+ "realpath",
51
+ "readlink",
52
+ "stat",
53
+ "cut",
54
+ "nl",
55
+ "tr",
56
+ "comm",
57
+ "diff",
58
+ "cmp",
59
+ "grep",
60
+ "egrep",
61
+ "fgrep",
62
+ "jq",
63
+ "cksum",
64
+ "md5sum",
65
+ "sha1sum",
66
+ "sha256sum",
67
+ "du",
68
+ "df",
69
+ "ps",
70
+ "true"
71
+ ]);
72
+ var SAFE_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
73
+ "status",
74
+ "log",
75
+ "diff",
76
+ "show",
77
+ "rev-parse",
78
+ "describe",
79
+ "blame",
80
+ "shortlog",
81
+ "ls-files",
82
+ "ls-tree",
83
+ "cat-file",
84
+ "whatchanged",
85
+ "rev-list",
86
+ "name-rev",
87
+ "for-each-ref",
88
+ "var",
89
+ "count-objects"
90
+ ]);
91
+ var GIT_WRITE_FLAGS = (token) => token === "--output" || token.startsWith("--output=");
92
+ var UNSAFE_SHELL_CHARS = /[;&|<>(){}`\\\n\r]/;
93
+ var basenameOf = (token) => {
94
+ const slash = Math.max(token.lastIndexOf("/"), token.lastIndexOf("\\"));
95
+ return slash === -1 ? token : token.slice(slash + 1);
96
+ };
97
+ var tokenizeShellCommand = (command) => {
98
+ const tokens = [];
99
+ let current = "";
100
+ let quote = null;
101
+ let started = false;
102
+ for (const ch of command) {
103
+ if (quote) {
104
+ if (ch === quote) quote = null;
105
+ else current += ch;
106
+ started = true;
107
+ continue;
108
+ }
109
+ if (ch === '"' || ch === "'") {
110
+ quote = ch;
111
+ started = true;
112
+ continue;
113
+ }
114
+ if (ch === " " || ch === " ") {
115
+ if (started) {
116
+ tokens.push(current);
117
+ current = "";
118
+ started = false;
119
+ }
120
+ continue;
121
+ }
122
+ current += ch;
123
+ started = true;
124
+ }
125
+ if (quote) return null;
126
+ if (started) tokens.push(current);
127
+ return tokens;
128
+ };
129
+ var isSafeReadOnlyCommand = (command) => {
130
+ const trimmed = command.trim();
131
+ if (!trimmed || trimmed.length > 2e3) return false;
132
+ if (UNSAFE_SHELL_CHARS.test(trimmed)) return false;
133
+ const tokens = tokenizeShellCommand(trimmed);
134
+ if (!tokens || tokens.length === 0) return false;
135
+ const first = tokens[0];
136
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first) || first.includes("$")) return false;
137
+ const exe = basenameOf(first);
138
+ if (exe === "git") {
139
+ const sub = tokens[1];
140
+ if (!sub || sub.startsWith("-")) return false;
141
+ if (!SAFE_GIT_SUBCOMMANDS.has(sub)) return false;
142
+ return !tokens.some(GIT_WRITE_FLAGS);
143
+ }
144
+ return SAFE_SHELL_COMMANDS.has(exe);
145
+ };
146
+ var API_KEY_PATTERN = /^pk_[a-f0-9]+\.[a-f0-9]+$/;
147
+ var isValidApiKey = (value) => API_KEY_PATTERN.test(value);
148
+ var ACTION_BODY_MAX = 4e3;
149
+ var DECISION_LINE_MAX = 500;
150
+
151
+ export {
152
+ isApprovalMode,
153
+ matchRankWeight,
154
+ matchToolPattern,
155
+ extractPolicyArg,
156
+ isSafeReadOnlyCommand,
157
+ isValidApiKey,
158
+ ACTION_BODY_MAX,
159
+ DECISION_LINE_MAX
160
+ };
@@ -94,6 +94,10 @@ interface AskUserParams {
94
94
  machineId?: string;
95
95
  toolName?: string;
96
96
  toolTarget?: string;
97
+ intent?: string;
98
+ action?: string;
99
+ blocker?: string;
100
+ actionBody?: string;
97
101
  }
98
102
  interface AskUserResponse {
99
103
  correlationId: string;
@@ -103,7 +107,7 @@ interface WaitForAnswerResponse {
103
107
  answered: boolean;
104
108
  value?: string;
105
109
  }
106
- declare const askUser: (apiKey: string, params: AskUserParams) => Promise<AskUserResponse>;
110
+ declare const askUser: (apiKey: string, params: AskUserParams, timeoutMs?: number) => Promise<AskUserResponse>;
107
111
  declare const waitForAnswer: (apiKey: string, correlationId: string, timeoutMs?: number) => Promise<WaitForAnswerResponse>;
108
112
  declare const cancelQuestion: (apiKey: string, correlationId: string) => Promise<void>;
109
113
 
package/dist/src/index.js CHANGED
@@ -1,23 +1,21 @@
1
1
  import {
2
2
  handlePreToolUse
3
- } from "../chunk-FXYTRZHC.js";
4
- import "../chunk-N7VXDBQU.js";
5
- import {
6
- handleNotification,
7
- handlePostToolUse,
8
- handleStop,
9
- reportEvent
10
- } from "../chunk-QY4L6XHN.js";
3
+ } from "../chunk-FGZZRCOG.js";
4
+ import "../chunk-KQYIHZ5E.js";
11
5
  import {
12
6
  askUser,
13
7
  cancelQuestion,
14
8
  fetchModeOverride,
15
9
  fetchModeState,
16
10
  getPolicy,
11
+ handleNotification,
12
+ handlePostToolUse,
13
+ handleStop,
14
+ reportEvent,
17
15
  resolvePolicy,
18
16
  waitForAnswer
19
- } from "../chunk-ACE77TKQ.js";
20
- import "../chunk-USUCPCUC.js";
17
+ } from "../chunk-M4GDBGXF.js";
18
+ import "../chunk-WPVL6VIT.js";
21
19
  import "../chunk-DWED7BS3.js";
22
20
  import {
23
21
  getApiKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/agent-hooks",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
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",