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