@pushary/agent-hooks 0.25.0 → 0.26.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.
Files changed (94) hide show
  1. package/dist/bin/pushary-clean.js +1 -1
  2. package/dist/bin/pushary-codex-hook.js +1 -1
  3. package/dist/bin/pushary-codex.js +1 -1
  4. package/dist/bin/pushary-doctor.js +21 -9
  5. package/dist/bin/pushary-gemini-hook.js +1 -1
  6. package/dist/bin/pushary-hook.js +2 -2
  7. package/dist/bin/pushary-post-hook.js +1 -1
  8. package/dist/bin/pushary-prompt-hook.js +1 -1
  9. package/dist/bin/pushary-setup.js +7 -19
  10. package/dist/bin/pushary-stop-hook.js +1 -1
  11. package/dist/{chunk-GYPPVD3P.js → chunk-A7DQCA2N.js} +1 -1
  12. package/dist/{chunk-O2QL6U6G.js → chunk-SA4BDS7T.js} +1 -1
  13. package/dist/{chunk-JPRRYC5X.js → chunk-SLX4AONG.js} +25 -0
  14. package/dist/src/index.js +2 -2
  15. package/package.json +1 -1
  16. package/dist/chunk-22CV7V7A.js +0 -38
  17. package/dist/chunk-2BE2IPMO.js +0 -315
  18. package/dist/chunk-2CRLBMOX.js +0 -244
  19. package/dist/chunk-2HMNOZPY.js +0 -109
  20. package/dist/chunk-2I6DLXJN.js +0 -219
  21. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  22. package/dist/chunk-3LC4YUMA.js +0 -194
  23. package/dist/chunk-3MIR7ODJ.js +0 -112
  24. package/dist/chunk-3QZESA66.js +0 -222
  25. package/dist/chunk-4Z4MB37G.js +0 -96
  26. package/dist/chunk-5GFUI5N6.js +0 -132
  27. package/dist/chunk-5JEDLXEC.js +0 -99
  28. package/dist/chunk-5LTQNC7R.js +0 -824
  29. package/dist/chunk-5QHQVXWN.js +0 -174
  30. package/dist/chunk-6A3WCJO2.js +0 -416
  31. package/dist/chunk-6QWFMVCD.js +0 -328
  32. package/dist/chunk-6SRXMZAN.js +0 -99
  33. package/dist/chunk-7PTU7TGE.js +0 -96
  34. package/dist/chunk-AB4KX4XT.js +0 -109
  35. package/dist/chunk-AC4UYAGX.js +0 -136
  36. package/dist/chunk-ACE77TKQ.js +0 -328
  37. package/dist/chunk-BHAMEPOP.js +0 -323
  38. package/dist/chunk-BYNYYZWW.js +0 -412
  39. package/dist/chunk-C5TFTNHG.js +0 -244
  40. package/dist/chunk-CH53PBQN.js +0 -265
  41. package/dist/chunk-DF3BM6BF.js +0 -195
  42. package/dist/chunk-DKZVKEOW.js +0 -175
  43. package/dist/chunk-EMPL27ZV.js +0 -96
  44. package/dist/chunk-EQJXMEIR.js +0 -175
  45. package/dist/chunk-FGZZRCOG.js +0 -194
  46. package/dist/chunk-FXYTRZHC.js +0 -177
  47. package/dist/chunk-GTJGZBTQ.js +0 -328
  48. package/dist/chunk-HJMFYDWY.js +0 -222
  49. package/dist/chunk-HRQEECB6.js +0 -315
  50. package/dist/chunk-HWEMAAOY.js +0 -370
  51. package/dist/chunk-IBWCHA5M.js +0 -10
  52. package/dist/chunk-KTM4ZQ3W.js +0 -96
  53. package/dist/chunk-KTP2EPVB.js +0 -27
  54. package/dist/chunk-KYARP7KP.js +0 -97
  55. package/dist/chunk-M2N5DYWN.js +0 -247
  56. package/dist/chunk-M4GDBGXF.js +0 -824
  57. package/dist/chunk-M5F2L4KF.js +0 -177
  58. package/dist/chunk-M6S3M6E3.js +0 -244
  59. package/dist/chunk-N7VXDBQU.js +0 -6
  60. package/dist/chunk-O6A5RHWY.js +0 -122
  61. package/dist/chunk-ODUXELPM.js +0 -219
  62. package/dist/chunk-OF5WIOYS.js +0 -129
  63. package/dist/chunk-OP4QAN23.js +0 -99
  64. package/dist/chunk-P4JH2Q7Z.js +0 -102
  65. package/dist/chunk-PMD5JSV3.js +0 -242
  66. package/dist/chunk-PSSHNBEL.js +0 -177
  67. package/dist/chunk-QEPRH7JB.js +0 -315
  68. package/dist/chunk-QRXWPZKN.js +0 -308
  69. package/dist/chunk-QY4L6XHN.js +0 -384
  70. package/dist/chunk-RNWPCELY.js +0 -176
  71. package/dist/chunk-RSHN2AQ7.js +0 -29
  72. package/dist/chunk-RZLVE57X.js +0 -38
  73. package/dist/chunk-SDCIKREA.js +0 -241
  74. package/dist/chunk-SDREQWNI.js +0 -175
  75. package/dist/chunk-SH26ZOHU.js +0 -159
  76. package/dist/chunk-TRLBBLSS.js +0 -176
  77. package/dist/chunk-U6OXZPYC.js +0 -384
  78. package/dist/chunk-UIBTFZUD.js +0 -314
  79. package/dist/chunk-USUCPCUC.js +0 -156
  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-XPVSZIA3.js +0 -315
  90. package/dist/chunk-Y633ZIJF.js +0 -384
  91. package/dist/chunk-YCL4GUFR.js +0 -222
  92. package/dist/chunk-YTMKB44I.js +0 -220
  93. package/dist/chunk-ZWBS3T7Q.js +0 -244
  94. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
@@ -1,176 +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-QRXWPZKN.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 [policy, modeState] = await Promise.all([
139
- getPolicy(apiKey),
140
- fetchModeState(apiKey, input.session_id)
141
- ]);
142
- if (modeState.kill) {
143
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
144
- }
145
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
146
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
147
- return allow();
148
- }
149
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
150
- return deny(`Denied by policy for ${toolPolicy.tool}`);
151
- }
152
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
153
- const projectName = basename(input.cwd ?? process.cwd());
154
- const sessionId = input.session_id;
155
- const machineId = getMachineId();
156
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
157
- switch (toolPolicy.mode) {
158
- case "push_only":
159
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
160
- case "terminal_only":
161
- return handleTerminalOnly();
162
- case "push_first":
163
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
164
- case "notify_only":
165
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
166
- default:
167
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
168
- }
169
- } catch {
170
- return ask("Pushary unavailable, falling back to terminal approval");
171
- }
172
- };
173
-
174
- export {
175
- handlePreToolUse
176
- };
@@ -1,384 +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-HRQEECB6.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
- var CODEX_AGENT = { type: "codex", label: "Codex" };
26
- var codexAllow = () => ({ kind: "allow" });
27
- var codexDeny = (reason) => ({ kind: "deny", reason });
28
- var codexPass = () => ({ kind: "pass" });
29
- var toCodexWire = (event, decision) => {
30
- if (event === "PermissionRequest") {
31
- if (decision.kind === "allow") {
32
- return {
33
- hookSpecificOutput: {
34
- hookEventName: "PermissionRequest",
35
- decision: { behavior: "allow" }
36
- }
37
- };
38
- }
39
- if (decision.kind === "deny") {
40
- return {
41
- hookSpecificOutput: {
42
- hookEventName: "PermissionRequest",
43
- decision: { behavior: "deny", message: decision.reason }
44
- }
45
- };
46
- }
47
- return null;
48
- }
49
- if (event === "PreToolUse" && decision.kind === "deny") {
50
- return {
51
- hookSpecificOutput: {
52
- hookEventName: "PreToolUse",
53
- permissionDecision: "deny",
54
- permissionDecisionReason: decision.reason
55
- }
56
- };
57
- }
58
- return null;
59
- };
60
- var toPolicyLookup = (toolName, toolInput) => {
61
- if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
62
- const command = toolInput.command;
63
- return {
64
- tool: "Edit",
65
- input: typeof command === "string" ? { file_path: command } : {}
66
- };
67
- };
68
- var permissionTimeoutDecision = (timeoutAction) => {
69
- if (timeoutAction === "approve") return codexAllow();
70
- if (timeoutAction === "deny") return codexDeny("No response within timeout");
71
- return codexPass();
72
- };
73
- var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
74
-
75
- // src/usage.ts
76
- import { closeSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "fs";
77
- import { join } from "path";
78
- import { tmpdir } from "os";
79
- var DEFAULT_PRICES = [
80
- { match: "opus-4-1", in: 15, out: 75 },
81
- { match: "opus-4-0", in: 15, out: 75 },
82
- { match: "3-opus", in: 15, out: 75 },
83
- { match: "opus", in: 5, out: 25 },
84
- { match: "haiku", in: 1, out: 5 },
85
- { match: "sonnet", in: 3, out: 15 }
86
- ];
87
- var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
88
- var CACHE_WRITE_MULTIPLIER = 1.25;
89
- var CACHE_READ_MULTIPLIER = 0.1;
90
- var RECENT_ID_LIMIT = 200;
91
- var READ_CHUNK_BYTES = 1024 * 1024;
92
- var isModelPrice = (value) => {
93
- if (!value || typeof value !== "object") return false;
94
- const candidate = value;
95
- return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
96
- };
97
- var priceTable = () => {
98
- const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
99
- if (!raw) return DEFAULT_PRICES;
100
- try {
101
- const parsed = JSON.parse(raw);
102
- if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
103
- } catch {
104
- }
105
- return DEFAULT_PRICES;
106
- };
107
- var estimateCostUsd = (usage, model) => {
108
- const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
109
- const perTokenIn = price.in / 1e6;
110
- const perTokenOut = price.out / 1e6;
111
- return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
112
- };
113
- var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join(tmpdir(), "pushary-usage");
114
- var stateFile = (sessionId) => join(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
115
- var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
116
- var readState = (path) => {
117
- try {
118
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
119
- if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
120
- return {
121
- offset: parsed.offset,
122
- tokensIn: parsed.tokensIn,
123
- tokensOut: parsed.tokensOut,
124
- costUsd: parsed.costUsd,
125
- recentIds: parsed.recentIds.filter((id) => typeof id === "string")
126
- };
127
- }
128
- } catch {
129
- }
130
- return emptyState();
131
- };
132
- var readRange = (path, start, end) => {
133
- const fd = openSync(path, "r");
134
- try {
135
- const chunks = [];
136
- let position = start;
137
- while (position < end) {
138
- const length = Math.min(READ_CHUNK_BYTES, end - position);
139
- const buffer = Buffer.alloc(length);
140
- const bytesRead = readSync(fd, buffer, 0, length, position);
141
- if (bytesRead <= 0) break;
142
- chunks.push(buffer.subarray(0, bytesRead));
143
- position += bytesRead;
144
- }
145
- return Buffer.concat(chunks);
146
- } finally {
147
- closeSync(fd);
148
- }
149
- };
150
- var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
151
- var applyLine = (state, line) => {
152
- let parsed;
153
- try {
154
- parsed = JSON.parse(line);
155
- } catch {
156
- return 0;
157
- }
158
- if (parsed.type !== "assistant") return 0;
159
- const usage = parsed.message?.usage;
160
- if (!usage || typeof usage !== "object") return 0;
161
- const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
162
- if (model.includes("<synthetic>")) return 0;
163
- const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
164
- if (id) {
165
- if (state.recentIds.includes(id)) return 0;
166
- state.recentIds.push(id);
167
- if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
168
- }
169
- const messageUsage = {
170
- inputTokens: toCount(usage.input_tokens),
171
- outputTokens: toCount(usage.output_tokens),
172
- cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
173
- cacheReadTokens: toCount(usage.cache_read_input_tokens)
174
- };
175
- const cost = estimateCostUsd(messageUsage, model);
176
- state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
177
- state.tokensOut += messageUsage.outputTokens;
178
- state.costUsd += cost;
179
- return cost;
180
- };
181
- var readNewUsage = (transcriptPath, sessionId) => {
182
- try {
183
- const size = statSync(transcriptPath).size;
184
- const path = stateFile(sessionId);
185
- let state = readState(path);
186
- if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
187
- let deltaUsd = 0;
188
- if (size > state.offset) {
189
- const buffer = readRange(transcriptPath, state.offset, size);
190
- const lastNewline = buffer.lastIndexOf(10);
191
- if (lastNewline >= 0) {
192
- const complete = buffer.subarray(0, lastNewline + 1);
193
- for (const line of complete.toString("utf-8").split("\n")) {
194
- if (line.trim()) deltaUsd += applyLine(state, line);
195
- }
196
- state.offset += lastNewline + 1;
197
- }
198
- }
199
- mkdirSync(stateDir(), { recursive: true });
200
- writeFileSync(path, JSON.stringify(state), "utf-8");
201
- if (state.tokensIn === 0 && state.tokensOut === 0) return null;
202
- return {
203
- tokensIn: state.tokensIn,
204
- tokensOut: state.tokensOut,
205
- costUsd: state.costUsd,
206
- deltaUsd
207
- };
208
- } catch {
209
- return null;
210
- }
211
- };
212
-
213
- // src/events.ts
214
- import { basename, join as join2 } from "path";
215
- import { createHash } from "crypto";
216
- import { existsSync, readFileSync as readFileSync2 } from "fs";
217
- import { tmpdir as tmpdir2 } from "os";
218
- var cleanupPendingQuestions = async (sessionId) => {
219
- try {
220
- const files = listPendingQuestions(sessionId);
221
- const apiKey = getApiKey();
222
- for (const correlationId of files) {
223
- try {
224
- await cancelQuestion(apiKey, correlationId);
225
- } catch {
226
- }
227
- removePendingQuestion(sessionId, correlationId);
228
- }
229
- if (!isDefaultSession(sessionId)) removePendingSession(sessionId);
230
- } catch {
231
- }
232
- };
233
- var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
234
- var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
235
- var readFreshCachedPolicy = (apiKey) => {
236
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
237
- const path = join2(tmpdir2(), `pushary-policy-${hash}.json`);
238
- if (!existsSync(path)) return null;
239
- const cached = JSON.parse(readFileSync2(path, "utf-8"));
240
- if (!isPolicyConfig(cached)) return null;
241
- if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
242
- return cached;
243
- };
244
- var deriveDecisionSource = (toolName, toolInput, liveMode) => {
245
- try {
246
- if (liveMode.kill) return "terminal";
247
- const policy = readFreshCachedPolicy(getApiKey());
248
- if (!policy) return void 0;
249
- const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
250
- if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
251
- if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
252
- return "terminal";
253
- } catch {
254
- return void 0;
255
- }
256
- };
257
- var deriveUsage = (transcriptPath, sessionId) => {
258
- if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
259
- try {
260
- return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
261
- } catch {
262
- return void 0;
263
- }
264
- };
265
- var reportEvent = async (event, options = {}) => {
266
- const apiKey = getApiKey();
267
- const baseUrl = getBaseUrl();
268
- return withRetry(async () => {
269
- const res = await fetch(`${baseUrl}/api/agent/event`, {
270
- method: "POST",
271
- headers: {
272
- "Content-Type": "application/json",
273
- "Authorization": `Bearer ${apiKey}`
274
- },
275
- body: JSON.stringify({
276
- ...event,
277
- machineId: event.machineId ?? getMachineId()
278
- }),
279
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
280
- });
281
- try {
282
- return await res.json();
283
- } catch {
284
- return null;
285
- }
286
- }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
287
- };
288
- var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
289
- try {
290
- const projectName = basename(input.cwd ?? process.cwd());
291
- const action = describeToolCall(input.tool_name, input.tool_input, "event");
292
- const lookup = toPolicyLookup(input.tool_name, input.tool_input);
293
- const isError = isToolResultError(input.tool_result);
294
- const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
295
- const liveMode = await fetchModeState(getApiKey(), input.session_id);
296
- await Promise.allSettled([
297
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
298
- reportEvent({
299
- event: isError ? "tool_error" : "tool_complete",
300
- agentType: agent.type,
301
- agentName: `${agent.label} - ${projectName}`,
302
- action,
303
- sessionId: input.session_id,
304
- error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
305
- decisionSource: deriveDecisionSource(lookup.tool, lookup.input, liveMode),
306
- meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
307
- usage: deriveUsage(input.transcript_path, input.session_id)
308
- })
309
- ]);
310
- } catch {
311
- }
312
- };
313
- var TASK_TITLE_MAX_LENGTH = 120;
314
- var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
315
- try {
316
- const projectName = basename(input.cwd ?? process.cwd());
317
- const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
318
- const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
319
- await reportEvent({
320
- event: "user_prompt",
321
- agentType: agent.type,
322
- agentName: `${agent.label} - ${projectName}`,
323
- sessionId: input.session_id,
324
- taskTitle
325
- }, { maxAttempts: 1, timeoutMs: 800 });
326
- } catch {
327
- }
328
- };
329
- var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
330
- try {
331
- const projectName = basename(input.cwd ?? process.cwd());
332
- const [, reported] = await Promise.allSettled([
333
- cleanupPendingQuestions(input.session_id || DEFAULT_SESSION),
334
- reportEvent({
335
- event: "session_end",
336
- agentType: agent.type,
337
- agentName: `${agent.label} - ${projectName}`,
338
- action: "Session ended",
339
- sessionId: input.session_id,
340
- usage: deriveUsage(input.transcript_path, input.session_id)
341
- })
342
- ]);
343
- const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
344
- if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
345
- return {
346
- decision: "block",
347
- reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
348
- };
349
- }
350
- return void 0;
351
- } catch {
352
- return void 0;
353
- }
354
- };
355
- var handleNotification = async (input) => {
356
- try {
357
- const projectName = basename(input.cwd ?? process.cwd());
358
- await reportEvent({
359
- event: input.type === "error" ? "error" : "notification",
360
- agentType: "claude_code",
361
- agentName: `Claude Code - ${projectName}`,
362
- action: input.title ?? input.message ?? "Notification",
363
- sessionId: input.session_id,
364
- error: input.type === "error" ? input.message : void 0
365
- });
366
- } catch {
367
- }
368
- };
369
-
370
- export {
371
- CODEX_AGENT,
372
- codexAllow,
373
- codexDeny,
374
- codexPass,
375
- toCodexWire,
376
- toPolicyLookup,
377
- permissionTimeoutDecision,
378
- preToolUseTimeoutDecision,
379
- reportEvent,
380
- handlePostToolUse,
381
- handleUserPrompt,
382
- handleStop,
383
- handleNotification
384
- };