@pushary/agent-hooks 0.27.0 → 0.28.1

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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +111 -0
  3. package/dist/bin/pushary-clean.js +3 -3
  4. package/dist/bin/pushary-codex-hook.js +2 -2
  5. package/dist/bin/pushary-codex.js +2 -2
  6. package/dist/bin/pushary-doctor.js +2 -2
  7. package/dist/bin/pushary-gemini-hook.js +2 -2
  8. package/dist/bin/pushary-hook.js +3 -3
  9. package/dist/bin/pushary-post-hook.js +2 -2
  10. package/dist/bin/pushary-prompt-hook.js +2 -2
  11. package/dist/bin/pushary-setup.js +4 -4
  12. package/dist/bin/pushary-stop-hook.js +2 -2
  13. package/dist/chunk-22CV7V7A.js +38 -0
  14. package/dist/chunk-2BE2IPMO.js +315 -0
  15. package/dist/chunk-2CRLBMOX.js +244 -0
  16. package/dist/chunk-2HMNOZPY.js +109 -0
  17. package/dist/chunk-2I6DLXJN.js +219 -0
  18. package/dist/chunk-2Q6XPZ4Q.js +395 -0
  19. package/dist/chunk-3LC4YUMA.js +194 -0
  20. package/dist/chunk-3MIR7ODJ.js +112 -0
  21. package/dist/chunk-3QZESA66.js +222 -0
  22. package/dist/chunk-4Z4MB37G.js +96 -0
  23. package/dist/chunk-5GFUI5N6.js +132 -0
  24. package/dist/chunk-5JEDLXEC.js +99 -0
  25. package/dist/chunk-5LTQNC7R.js +824 -0
  26. package/dist/chunk-5MA3CPZB.js +141 -0
  27. package/dist/chunk-5QHQVXWN.js +174 -0
  28. package/dist/{chunk-WXWHRXDK.js → chunk-5V3XJ2ES.js} +1 -1
  29. package/dist/chunk-6A3WCJO2.js +416 -0
  30. package/dist/chunk-6QWFMVCD.js +328 -0
  31. package/dist/chunk-6SRXMZAN.js +99 -0
  32. package/dist/chunk-7OXL2QQ4.js +357 -0
  33. package/dist/chunk-7PTU7TGE.js +96 -0
  34. package/dist/chunk-AB4KX4XT.js +109 -0
  35. package/dist/chunk-AC4UYAGX.js +136 -0
  36. package/dist/chunk-ACE77TKQ.js +328 -0
  37. package/dist/chunk-BHAMEPOP.js +323 -0
  38. package/dist/chunk-BYNYYZWW.js +412 -0
  39. package/dist/{chunk-FDR5WYT7.js → chunk-C4BMEVK7.js} +1 -1
  40. package/dist/chunk-C5TFTNHG.js +244 -0
  41. package/dist/chunk-CH53PBQN.js +265 -0
  42. package/dist/chunk-DF3BM6BF.js +195 -0
  43. package/dist/chunk-DKZVKEOW.js +175 -0
  44. package/dist/chunk-EMPL27ZV.js +96 -0
  45. package/dist/chunk-EQJXMEIR.js +175 -0
  46. package/dist/{chunk-MVNOP5IZ.js → chunk-FB3N633T.js} +1 -1
  47. package/dist/chunk-FGZZRCOG.js +194 -0
  48. package/dist/chunk-FXYTRZHC.js +177 -0
  49. package/dist/chunk-GTJGZBTQ.js +328 -0
  50. package/dist/chunk-GYPPVD3P.js +1047 -0
  51. package/dist/chunk-HJMFYDWY.js +222 -0
  52. package/dist/chunk-HRQEECB6.js +315 -0
  53. package/dist/chunk-HWEMAAOY.js +370 -0
  54. package/dist/{chunk-VHD3GMZ3.js → chunk-I4GMPUYN.js} +2 -2
  55. package/dist/{chunk-TUILTFLS.js → chunk-IAOXM7X5.js} +1 -1
  56. package/dist/chunk-IBWCHA5M.js +10 -0
  57. package/dist/chunk-JPRRYC5X.js +328 -0
  58. package/dist/chunk-KTM4ZQ3W.js +96 -0
  59. package/dist/chunk-KTP2EPVB.js +27 -0
  60. package/dist/chunk-KYARP7KP.js +97 -0
  61. package/dist/chunk-LXUHXG2X.js +937 -0
  62. package/dist/chunk-M2N5DYWN.js +247 -0
  63. package/dist/chunk-M4GDBGXF.js +824 -0
  64. package/dist/chunk-M5F2L4KF.js +177 -0
  65. package/dist/chunk-M6S3M6E3.js +244 -0
  66. package/dist/chunk-N7VXDBQU.js +6 -0
  67. package/dist/chunk-O2QL6U6G.js +194 -0
  68. package/dist/chunk-O6A5RHWY.js +122 -0
  69. package/dist/chunk-ODUXELPM.js +219 -0
  70. package/dist/chunk-OF5WIOYS.js +129 -0
  71. package/dist/chunk-OP4QAN23.js +99 -0
  72. package/dist/chunk-P4JH2Q7Z.js +102 -0
  73. package/dist/chunk-P6QBZS27.js +231 -0
  74. package/dist/chunk-PMD5JSV3.js +242 -0
  75. package/dist/chunk-PSSHNBEL.js +177 -0
  76. package/dist/chunk-PZO7RZ5W.js +145 -0
  77. package/dist/chunk-QEPRH7JB.js +315 -0
  78. package/dist/chunk-QNEYHDKR.js +145 -0
  79. package/dist/chunk-QRXWPZKN.js +308 -0
  80. package/dist/chunk-QY4L6XHN.js +384 -0
  81. package/dist/chunk-RNWPCELY.js +176 -0
  82. package/dist/chunk-RSHN2AQ7.js +29 -0
  83. package/dist/chunk-RZLVE57X.js +38 -0
  84. package/dist/chunk-SDCIKREA.js +241 -0
  85. package/dist/chunk-SDREQWNI.js +175 -0
  86. package/dist/chunk-SH26ZOHU.js +159 -0
  87. package/dist/chunk-SJ5MC36D.js +882 -0
  88. package/dist/chunk-TRLBBLSS.js +176 -0
  89. package/dist/chunk-U6OXZPYC.js +384 -0
  90. package/dist/chunk-UDQZNO5H.js +231 -0
  91. package/dist/chunk-UIBTFZUD.js +314 -0
  92. package/dist/chunk-USUCPCUC.js +156 -0
  93. package/dist/chunk-UTK3TJC4.js +882 -0
  94. package/dist/chunk-V4GLWPD7.js +174 -0
  95. package/dist/chunk-VC6U3QGF.js +142 -0
  96. package/dist/chunk-VIST7ACL.js +88 -0
  97. package/dist/chunk-VUNL35KE.js +16 -0
  98. package/dist/chunk-VWBNI4SC.js +174 -0
  99. package/dist/chunk-W5KRWUNE.js +262 -0
  100. package/dist/chunk-WCGKLHCL.js +154 -0
  101. package/dist/chunk-WNXGIEX7.js +219 -0
  102. package/dist/chunk-WPVL6VIT.js +160 -0
  103. package/dist/chunk-X3YCHQQK.js +357 -0
  104. package/dist/chunk-X6LV22NZ.js +229 -0
  105. package/dist/chunk-XHTZ2DWC.js +206 -0
  106. package/dist/chunk-XPVSZIA3.js +315 -0
  107. package/dist/chunk-Y633ZIJF.js +384 -0
  108. package/dist/chunk-YCL4GUFR.js +222 -0
  109. package/dist/chunk-YTMKB44I.js +220 -0
  110. package/dist/chunk-Z5PL3K7C.js +322 -0
  111. package/dist/chunk-ZWBS3T7Q.js +244 -0
  112. package/dist/pushary-mode-T7XOPI6Z.js +83 -0
  113. package/dist/pushary-wait-4BUC6ZM6.js +93 -0
  114. package/dist/src/index.js +3 -3
  115. package/package.json +25 -1
@@ -0,0 +1,937 @@
1
+ import {
2
+ callMcpTool,
3
+ withRetry
4
+ } from "./chunk-DWED7BS3.js";
5
+ import {
6
+ ACTION_BODY_MAX,
7
+ DECISION_LINE_MAX,
8
+ extractPolicyArg,
9
+ isApprovalMode,
10
+ isSafeReadOnlyCommand,
11
+ matchRankWeight,
12
+ matchToolPattern,
13
+ redactSecrets,
14
+ redactSecretsDeep
15
+ } from "./chunk-C4BMEVK7.js";
16
+ import {
17
+ getApiKey,
18
+ getBaseUrl
19
+ } from "./chunk-NKXSILEW.js";
20
+
21
+ // src/validate.ts
22
+ var isPolicyConfig = (data) => {
23
+ if (!data || typeof data !== "object") return false;
24
+ const d = data;
25
+ return Array.isArray(d.policies) && typeof d.defaultTimeoutSeconds === "number" && typeof d.defaultTimeoutAction === "string";
26
+ };
27
+ var isAskUserResponse = (data) => {
28
+ if (!data || typeof data !== "object") return false;
29
+ const d = data;
30
+ return typeof d.correlationId === "string" && typeof d.status === "string";
31
+ };
32
+ var isWaitForAnswerResponse = (data) => {
33
+ if (!data || typeof data !== "object") return false;
34
+ const d = data;
35
+ return typeof d.answered === "boolean";
36
+ };
37
+
38
+ // src/api.ts
39
+ var askUser = async (apiKey, params, timeoutMs = 15e3) => {
40
+ const result = await callMcpTool(apiKey, "ask_user", { ...params, wait: false }, { maxRetries: 3, timeoutMs });
41
+ if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
42
+ return result;
43
+ };
44
+ var waitForAnswer = async (apiKey, correlationId, timeoutMs = 3e4) => {
45
+ const result = await callMcpTool(apiKey, "wait_for_answer", {
46
+ correlationId,
47
+ timeoutMs
48
+ }, { timeoutMs: timeoutMs + 1e4 });
49
+ if (!isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
50
+ return result;
51
+ };
52
+ var cancelQuestion = async (apiKey, correlationId) => {
53
+ await callMcpTool(apiKey, "cancel_question", { correlationId });
54
+ };
55
+ var sendNotification = async (apiKey, params, timeoutMs = 15e3) => {
56
+ await callMcpTool(apiKey, "send_notification", { ...params }, { maxRetries: 3, timeoutMs });
57
+ };
58
+
59
+ // src/policy.ts
60
+ import { createHash } from "crypto";
61
+ import { existsSync, readFileSync, writeFileSync } from "fs";
62
+ import { join } from "path";
63
+ import { tmpdir } from "os";
64
+ var CACHE_TTL_MS = 60 * 1e3;
65
+ var cacheFile = (apiKey) => {
66
+ const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
67
+ return join(tmpdir(), `pushary-policy-${hash}.json`);
68
+ };
69
+ var fetchPolicy = async (apiKey) => {
70
+ return withRetry(async () => {
71
+ const baseUrl = getBaseUrl();
72
+ const response = await fetch(`${baseUrl}/api/mcp/policy`, {
73
+ headers: { "Authorization": `Bearer ${apiKey}` },
74
+ signal: AbortSignal.timeout(1e4)
75
+ });
76
+ if (!response.ok) {
77
+ throw new Error(`Failed to fetch policy: ${response.status}`);
78
+ }
79
+ const raw = await response.json();
80
+ if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
81
+ return raw;
82
+ }, { maxAttempts: 2 });
83
+ };
84
+ var getPolicy = async (apiKey, expectedVersion) => {
85
+ const path = cacheFile(apiKey);
86
+ let staleCache = null;
87
+ if (existsSync(path)) {
88
+ try {
89
+ const stat = readFileSync(path, "utf-8");
90
+ const cached = JSON.parse(stat);
91
+ if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
92
+ const versionStale = expectedVersion != null && (cached._policyVersion ?? null) !== expectedVersion;
93
+ const ttlFresh = !cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS;
94
+ if (ttlFresh && !versionStale) {
95
+ return cached;
96
+ }
97
+ staleCache = cached;
98
+ } catch {
99
+ }
100
+ }
101
+ try {
102
+ const policy = await fetchPolicy(apiKey);
103
+ try {
104
+ writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now(), _policyVersion: expectedVersion ?? null }), "utf-8");
105
+ } catch {
106
+ }
107
+ return policy;
108
+ } catch {
109
+ if (staleCache) return staleCache;
110
+ throw new Error("Failed to fetch policy and no cached policy available");
111
+ }
112
+ };
113
+ var findBestMatch = (policies, toolName, arg) => {
114
+ let best;
115
+ let bestWeight = 0;
116
+ let bestLength = -1;
117
+ for (const candidate of policies) {
118
+ const rank = matchToolPattern(candidate.tool, toolName, arg);
119
+ if (rank === "none") continue;
120
+ const weight = matchRankWeight(rank);
121
+ const length = rank === "prefix" ? candidate.tool.length : -1;
122
+ if (weight > bestWeight || weight === bestWeight && length > bestLength) {
123
+ best = { policy: candidate, rank };
124
+ bestWeight = weight;
125
+ bestLength = length;
126
+ }
127
+ }
128
+ return best;
129
+ };
130
+ var autoApprove = (tool) => ({
131
+ tool,
132
+ timeoutSeconds: 0,
133
+ timeoutAction: "approve",
134
+ mode: "terminal_only",
135
+ pushFirstSeconds: 0
136
+ });
137
+ var resolveAutoResolveOrigin = (config, toolName, toolInput) => {
138
+ const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
139
+ const match = findBestMatch(config.policies, toolName, arg);
140
+ const governedBySpecificRule = match?.rank === "exact" || match?.rank === "prefix";
141
+ if (!governedBySpecificRule && toolName === "Bash" && typeof arg === "string" && isSafeReadOnlyCommand(arg)) {
142
+ return "safe_readonly";
143
+ }
144
+ return "policy_timeout";
145
+ };
146
+ var resolvePolicy = (config, toolName, modeOverride, toolInput) => {
147
+ const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
148
+ const match = findBestMatch(config.policies, toolName, arg);
149
+ let base = match?.policy ?? config.policies.find((p) => p.tool === "*") ?? {
150
+ tool: toolName,
151
+ timeoutSeconds: config.defaultTimeoutSeconds,
152
+ timeoutAction: config.defaultTimeoutAction,
153
+ mode: config.defaultMode ?? "push_first",
154
+ pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
155
+ };
156
+ const governedBySpecificRule = match?.rank === "exact" || match?.rank === "prefix";
157
+ if (!governedBySpecificRule && toolName === "Bash" && typeof arg === "string" && isSafeReadOnlyCommand(arg)) {
158
+ base = autoApprove(base.tool);
159
+ }
160
+ const effectiveOverride = modeOverride ?? config.modeOverride;
161
+ if (effectiveOverride) {
162
+ return { ...base, mode: effectiveOverride };
163
+ }
164
+ return base;
165
+ };
166
+ var toPolicyVersion = (value) => typeof value === "string" || typeof value === "number" ? String(value) : null;
167
+ var fetchModeState = async (apiKey, sessionId) => {
168
+ try {
169
+ const baseUrl = getBaseUrl();
170
+ const url = sessionId ? `${baseUrl}/api/mcp/mode?session=${encodeURIComponent(sessionId)}` : `${baseUrl}/api/mcp/mode`;
171
+ const response = await fetch(url, {
172
+ headers: { "Authorization": `Bearer ${apiKey}` },
173
+ signal: AbortSignal.timeout(3e3)
174
+ });
175
+ if (!response.ok) return { mode: null, kill: false, policyVersion: null };
176
+ const data = await response.json();
177
+ const mode = data.override?.mode;
178
+ return {
179
+ mode: isApprovalMode(mode) ? mode : null,
180
+ kill: data.kill === true,
181
+ policyVersion: toPolicyVersion(data.policyVersion)
182
+ };
183
+ } catch {
184
+ return { mode: null, kill: false, policyVersion: null };
185
+ }
186
+ };
187
+ var fetchModeOverride = async (apiKey) => (await fetchModeState(apiKey)).mode;
188
+
189
+ // src/describe.ts
190
+ import { isAbsolute, relative } from "path";
191
+ var hookPrefixes = {
192
+ Bash: (input) => `bash: ${input.command ?? "(no command)"}`,
193
+ Write: (input) => `write file: ${input.file_path ?? "(unknown path)"}`,
194
+ Edit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
195
+ Read: (input) => `read file: ${input.file_path ?? "(unknown path)"}`
196
+ };
197
+ var eventPrefixes = {
198
+ Bash: (input) => `ran: ${String(input.command ?? "")}`,
199
+ Write: (input) => `wrote: ${input.file_path ?? "unknown"}`,
200
+ Edit: (input) => `edited: ${input.file_path ?? "unknown"}`,
201
+ Read: (input) => `read: ${input.file_path ?? "unknown"}`
202
+ };
203
+ var EVENT_ACTION_MAX = 120;
204
+ var HOOK_FALLBACK_MAX = 200;
205
+ var describeToolCall = (toolName, toolInput, format = "hook") => {
206
+ const prefixes = format === "hook" ? hookPrefixes : eventPrefixes;
207
+ const builder = prefixes[toolName];
208
+ const raw = builder ? builder(toolInput) : format === "hook" ? `${toolName}: ${JSON.stringify(toolInput)}` : `${toolName}: done`;
209
+ const redacted = redactSecrets(raw);
210
+ if (format === "event") return redacted.slice(0, EVENT_ACTION_MAX);
211
+ return builder ? redacted : redacted.slice(0, HOOK_FALLBACK_MAX);
212
+ };
213
+ var TOOL_TARGET_MAX_LENGTH = 80;
214
+ var deriveCommandHead = (command) => {
215
+ if (typeof command !== "string") return void 0;
216
+ const head = command.trim().split(/\s+/).slice(0, 2).join(" ");
217
+ return head ? head.slice(0, TOOL_TARGET_MAX_LENGTH) : void 0;
218
+ };
219
+ var deriveToolTarget = (toolName, toolInput) => {
220
+ if (toolName === "Bash") {
221
+ return deriveCommandHead(toolInput.command);
222
+ }
223
+ if (toolName === "Edit" || toolName === "Write") {
224
+ const filePath = toolInput.file_path;
225
+ if (typeof filePath !== "string") return void 0;
226
+ const separator = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
227
+ const base = filePath.slice(separator + 1);
228
+ const dot = base.lastIndexOf(".");
229
+ if (dot <= 0) return void 0;
230
+ return base.slice(dot).slice(0, TOOL_TARGET_MAX_LENGTH);
231
+ }
232
+ return void 0;
233
+ };
234
+ var RECEIPT_TARGET_MAX_LENGTH = 256;
235
+ var isToolResultError = (toolResult) => {
236
+ try {
237
+ return Boolean(toolResult && ("error" in toolResult || "is_error" in toolResult));
238
+ } catch {
239
+ return false;
240
+ }
241
+ };
242
+ var relativizeReceiptPath = (filePath, cwd) => {
243
+ if (!cwd || !isAbsolute(filePath)) return filePath;
244
+ return relative(cwd, filePath);
245
+ };
246
+ var deriveReceiptMeta = (toolName, toolInput, toolResult, cwd) => {
247
+ try {
248
+ const ok = !isToolResultError(toolResult);
249
+ if (toolName === "Edit" || toolName === "Write") {
250
+ const filePath = toolInput.file_path;
251
+ if (typeof filePath !== "string" || !filePath) return void 0;
252
+ return {
253
+ kind: toolName === "Edit" ? "edit" : "write",
254
+ target: relativizeReceiptPath(filePath, cwd).slice(0, RECEIPT_TARGET_MAX_LENGTH),
255
+ ok
256
+ };
257
+ }
258
+ if (toolName === "Bash") {
259
+ const head = deriveCommandHead(toolInput.command);
260
+ if (!head) return void 0;
261
+ return {
262
+ kind: head === "git commit" ? "commit" : "bash",
263
+ target: head,
264
+ ok
265
+ };
266
+ }
267
+ return void 0;
268
+ } catch {
269
+ return void 0;
270
+ }
271
+ };
272
+ var firstString = (...values) => values.find((v) => typeof v === "string" && v.length > 0);
273
+ var ACTION_BODY_TRUNCATION_MARKER = "\n\u2026 [truncated]";
274
+ var capActionBody = (text) => text.length <= ACTION_BODY_MAX ? text : `${text.slice(0, ACTION_BODY_MAX - ACTION_BODY_TRUNCATION_MARKER.length)}${ACTION_BODY_TRUNCATION_MARKER}`;
275
+ var rawActionBody = (toolName, toolInput) => {
276
+ if (toolName === "Edit" || toolName === "replace") {
277
+ const before = firstString(toolInput.old_string);
278
+ const after = firstString(toolInput.new_string);
279
+ if (before === void 0 && after === void 0) return void 0;
280
+ return `- ${before ?? ""}
281
+ + ${after ?? ""}`;
282
+ }
283
+ if (toolName === "Write" || toolName === "write_file") return firstString(toolInput.content);
284
+ if (toolName === "Bash" || toolName === "run_shell_command" || toolName === "shell" || toolName === "apply_patch") {
285
+ return firstString(toolInput.command);
286
+ }
287
+ return void 0;
288
+ };
289
+ var deriveActionBody = (toolName, toolInput) => {
290
+ try {
291
+ const raw = rawActionBody(toolName, toolInput);
292
+ if (!raw) return void 0;
293
+ return capActionBody(redactSecretsDeep(raw));
294
+ } catch {
295
+ return void 0;
296
+ }
297
+ };
298
+ var deriveAction = (toolName, toolInput) => describeToolCall(toolName, toolInput, "hook").slice(0, DECISION_LINE_MAX);
299
+ var BLOCKER_BY_MODE = {
300
+ push_only: "Approval required before this runs",
301
+ push_first: "Paused for your approval before continuing",
302
+ escalate: "Escalated to you after the approval timeout"
303
+ };
304
+ var deriveBlocker = (mode, reason) => {
305
+ const text = reason?.replace(/\s+/g, " ").trim() || BLOCKER_BY_MODE[mode] || "Waiting for your approval";
306
+ return text.slice(0, DECISION_LINE_MAX);
307
+ };
308
+
309
+ // src/identity.ts
310
+ import { createHash as createHash2 } from "crypto";
311
+ import { hostname } from "os";
312
+ var deriveMachineId = (host) => createHash2("sha256").update(host).digest("hex").slice(0, 8);
313
+ var getMachineId = () => deriveMachineId(hostname());
314
+
315
+ // src/pending.ts
316
+ import { join as join2 } from "path";
317
+ import { tmpdir as tmpdir2 } from "os";
318
+ import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2, readdirSync, unlinkSync, rmSync, statSync } from "fs";
319
+ var PENDING_DIR = join2(tmpdir2(), "pushary-pending");
320
+ var DEFAULT_SESSION = "_no_session";
321
+ var GRACE_MS = 10 * 60 * 1e3;
322
+ var sanitize = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
323
+ var dirFor = (sessionId) => join2(PENDING_DIR, sanitize(sessionId));
324
+ var isDefaultSession = (sessionId) => sanitize(sessionId) === DEFAULT_SESSION;
325
+ var savePendingQuestion = (sessionId, correlationId) => {
326
+ const dir = dirFor(sessionId);
327
+ if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
328
+ writeFileSync2(join2(dir, correlationId), "", "utf-8");
329
+ };
330
+ var listPendingQuestions = (sessionId) => {
331
+ const dir = dirFor(sessionId);
332
+ let files;
333
+ try {
334
+ files = readdirSync(dir);
335
+ } catch {
336
+ return [];
337
+ }
338
+ if (!isDefaultSession(sessionId)) return files;
339
+ const cutoff = Date.now() - GRACE_MS;
340
+ return files.filter((name) => {
341
+ try {
342
+ return statSync(join2(dir, name)).mtimeMs < cutoff;
343
+ } catch {
344
+ return false;
345
+ }
346
+ });
347
+ };
348
+ var removePendingQuestion = (sessionId, correlationId) => {
349
+ try {
350
+ unlinkSync(join2(dirFor(sessionId), correlationId));
351
+ } catch {
352
+ }
353
+ };
354
+ var removePendingSession = (sessionId) => {
355
+ try {
356
+ rmSync(dirFor(sessionId), { recursive: true, force: true });
357
+ } catch {
358
+ }
359
+ };
360
+
361
+ // src/usage.ts
362
+ import { closeSync, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync2, readSync, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
363
+ import { join as join3 } from "path";
364
+ import { tmpdir as tmpdir3 } from "os";
365
+ var DEFAULT_PRICES = [
366
+ { match: "opus-4-1", in: 15, out: 75 },
367
+ { match: "opus-4-0", in: 15, out: 75 },
368
+ { match: "3-opus", in: 15, out: 75 },
369
+ { match: "opus", in: 5, out: 25 },
370
+ { match: "haiku", in: 1, out: 5 },
371
+ { match: "sonnet", in: 3, out: 15 }
372
+ ];
373
+ var FALLBACK_PRICE = { match: "", in: 3, out: 15 };
374
+ var CACHE_WRITE_MULTIPLIER = 1.25;
375
+ var CACHE_READ_MULTIPLIER = 0.1;
376
+ var RECENT_ID_LIMIT = 200;
377
+ var READ_CHUNK_BYTES = 1024 * 1024;
378
+ var isModelPrice = (value) => {
379
+ if (!value || typeof value !== "object") return false;
380
+ const candidate = value;
381
+ return typeof candidate.match === "string" && typeof candidate.in === "number" && typeof candidate.out === "number";
382
+ };
383
+ var priceTable = () => {
384
+ const raw = process.env.PUSHARY_MODEL_PRICING?.trim();
385
+ if (!raw) return DEFAULT_PRICES;
386
+ try {
387
+ const parsed = JSON.parse(raw);
388
+ if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(isModelPrice)) return parsed;
389
+ } catch {
390
+ }
391
+ return DEFAULT_PRICES;
392
+ };
393
+ var estimateCostUsd = (usage, model) => {
394
+ const price = priceTable().find((p) => model.includes(p.match)) ?? FALLBACK_PRICE;
395
+ const perTokenIn = price.in / 1e6;
396
+ const perTokenOut = price.out / 1e6;
397
+ return usage.inputTokens * perTokenIn + usage.outputTokens * perTokenOut + usage.cacheCreationTokens * perTokenIn * CACHE_WRITE_MULTIPLIER + usage.cacheReadTokens * perTokenIn * CACHE_READ_MULTIPLIER;
398
+ };
399
+ var stateDir = () => process.env.PUSHARY_USAGE_DIR?.trim() || join3(tmpdir3(), "pushary-usage");
400
+ var stateFile = (sessionId) => join3(stateDir(), sessionId.replace(/[^a-zA-Z0-9_-]/g, "_"));
401
+ var emptyState = () => ({ offset: 0, tokensIn: 0, tokensOut: 0, costUsd: 0, recentIds: [] });
402
+ var readState = (path) => {
403
+ try {
404
+ const parsed = JSON.parse(readFileSync2(path, "utf-8"));
405
+ if (typeof parsed.offset === "number" && parsed.offset >= 0 && typeof parsed.tokensIn === "number" && typeof parsed.tokensOut === "number" && typeof parsed.costUsd === "number" && Array.isArray(parsed.recentIds)) {
406
+ return {
407
+ offset: parsed.offset,
408
+ tokensIn: parsed.tokensIn,
409
+ tokensOut: parsed.tokensOut,
410
+ costUsd: parsed.costUsd,
411
+ recentIds: parsed.recentIds.filter((id) => typeof id === "string")
412
+ };
413
+ }
414
+ } catch {
415
+ }
416
+ return emptyState();
417
+ };
418
+ var readRange = (path, start, end) => {
419
+ const fd = openSync(path, "r");
420
+ try {
421
+ const chunks = [];
422
+ let position = start;
423
+ while (position < end) {
424
+ const length = Math.min(READ_CHUNK_BYTES, end - position);
425
+ const buffer = Buffer.alloc(length);
426
+ const bytesRead = readSync(fd, buffer, 0, length, position);
427
+ if (bytesRead <= 0) break;
428
+ chunks.push(buffer.subarray(0, bytesRead));
429
+ position += bytesRead;
430
+ }
431
+ return Buffer.concat(chunks);
432
+ } finally {
433
+ closeSync(fd);
434
+ }
435
+ };
436
+ var toCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
437
+ var applyLine = (state, line) => {
438
+ let parsed;
439
+ try {
440
+ parsed = JSON.parse(line);
441
+ } catch {
442
+ return 0;
443
+ }
444
+ if (parsed.type !== "assistant") return 0;
445
+ const usage = parsed.message?.usage;
446
+ if (!usage || typeof usage !== "object") return 0;
447
+ const model = typeof parsed.message?.model === "string" ? parsed.message.model : "";
448
+ if (model.includes("<synthetic>")) return 0;
449
+ const id = typeof parsed.message?.id === "string" ? parsed.message.id : null;
450
+ if (id) {
451
+ if (state.recentIds.includes(id)) return 0;
452
+ state.recentIds.push(id);
453
+ if (state.recentIds.length > RECENT_ID_LIMIT) state.recentIds.splice(0, state.recentIds.length - RECENT_ID_LIMIT);
454
+ }
455
+ const messageUsage = {
456
+ inputTokens: toCount(usage.input_tokens),
457
+ outputTokens: toCount(usage.output_tokens),
458
+ cacheCreationTokens: toCount(usage.cache_creation_input_tokens),
459
+ cacheReadTokens: toCount(usage.cache_read_input_tokens)
460
+ };
461
+ const cost = estimateCostUsd(messageUsage, model);
462
+ state.tokensIn += messageUsage.inputTokens + messageUsage.cacheCreationTokens + messageUsage.cacheReadTokens;
463
+ state.tokensOut += messageUsage.outputTokens;
464
+ state.costUsd += cost;
465
+ return cost;
466
+ };
467
+ var USER_PROMPT_TAIL_BYTES = 256 * 1024;
468
+ var USER_PROMPT_MAX = 2048;
469
+ var extractUserText = (content) => {
470
+ if (typeof content === "string") return content.replace(/\s+/g, " ").trim() || void 0;
471
+ if (Array.isArray(content)) {
472
+ const text = content.filter((block) => Boolean(block) && typeof block === "object").filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ").replace(/\s+/g, " ").trim();
473
+ return text || void 0;
474
+ }
475
+ return void 0;
476
+ };
477
+ var readLastUserPrompt = (transcriptPath) => {
478
+ try {
479
+ const size = statSync2(transcriptPath).size;
480
+ const start = Math.max(0, size - USER_PROMPT_TAIL_BYTES);
481
+ const lines = readRange(transcriptPath, start, size).toString("utf-8").split("\n");
482
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
483
+ const line = lines[i].trim();
484
+ if (!line) continue;
485
+ let parsed;
486
+ try {
487
+ parsed = JSON.parse(line);
488
+ } catch {
489
+ continue;
490
+ }
491
+ if (parsed.type !== "user") continue;
492
+ const text = extractUserText(parsed.message?.content);
493
+ if (text) return text.slice(0, USER_PROMPT_MAX);
494
+ }
495
+ return void 0;
496
+ } catch {
497
+ return void 0;
498
+ }
499
+ };
500
+ var readNewUsage = (transcriptPath, sessionId) => {
501
+ try {
502
+ const size = statSync2(transcriptPath).size;
503
+ const path = stateFile(sessionId);
504
+ let state = readState(path);
505
+ if (size < state.offset) state = { ...emptyState(), recentIds: state.recentIds };
506
+ let deltaUsd = 0;
507
+ if (size > state.offset) {
508
+ const buffer = readRange(transcriptPath, state.offset, size);
509
+ const lastNewline = buffer.lastIndexOf(10);
510
+ if (lastNewline >= 0) {
511
+ const complete = buffer.subarray(0, lastNewline + 1);
512
+ for (const line of complete.toString("utf-8").split("\n")) {
513
+ if (line.trim()) deltaUsd += applyLine(state, line);
514
+ }
515
+ state.offset += lastNewline + 1;
516
+ }
517
+ }
518
+ mkdirSync2(stateDir(), { recursive: true });
519
+ writeFileSync3(path, JSON.stringify(state), "utf-8");
520
+ if (state.tokensIn === 0 && state.tokensOut === 0) return null;
521
+ return {
522
+ tokensIn: state.tokensIn,
523
+ tokensOut: state.tokensOut,
524
+ costUsd: state.costUsd,
525
+ deltaUsd
526
+ };
527
+ } catch {
528
+ return null;
529
+ }
530
+ };
531
+
532
+ // src/codex-adapter.ts
533
+ import { resolve } from "path";
534
+ var CODEX_AGENT = { type: "codex", label: "Codex" };
535
+ var codexAllow = () => ({ kind: "allow" });
536
+ var codexDeny = (reason) => ({ kind: "deny", reason });
537
+ var codexPass = () => ({ kind: "pass" });
538
+ var toCodexWire = (event, decision) => {
539
+ if (event === "PermissionRequest") {
540
+ if (decision.kind === "allow") {
541
+ return {
542
+ hookSpecificOutput: {
543
+ hookEventName: "PermissionRequest",
544
+ decision: { behavior: "allow" }
545
+ }
546
+ };
547
+ }
548
+ if (decision.kind === "deny") {
549
+ return {
550
+ hookSpecificOutput: {
551
+ hookEventName: "PermissionRequest",
552
+ decision: { behavior: "deny", message: decision.reason }
553
+ }
554
+ };
555
+ }
556
+ return null;
557
+ }
558
+ if (event === "PreToolUse" && decision.kind === "deny") {
559
+ return {
560
+ hookSpecificOutput: {
561
+ hookEventName: "PreToolUse",
562
+ permissionDecision: "deny",
563
+ permissionDecisionReason: decision.reason
564
+ }
565
+ };
566
+ }
567
+ return null;
568
+ };
569
+ var parseApplyPatchOps = (command) => {
570
+ if (typeof command !== "string") return [];
571
+ const ops = [];
572
+ for (const line of command.split("\n")) {
573
+ const file = line.match(/^\*\*\*\s+(Add|Update|Delete) File:\s+(.+?)\s*$/);
574
+ if (file) {
575
+ ops.push({ op: file[1].toLowerCase(), path: file[2] });
576
+ continue;
577
+ }
578
+ const move = line.match(/^\*\*\*\s+Move to:\s+(.+?)\s*$/);
579
+ if (move) ops.push({ op: "move", path: move[1] });
580
+ }
581
+ return ops;
582
+ };
583
+ var parseApplyPatchFiles = (command) => [...new Set(parseApplyPatchOps(command).map((entry) => entry.path))];
584
+ var describeApplyPatch = (command) => {
585
+ const ops = parseApplyPatchOps(command);
586
+ if (ops.length === 0) return null;
587
+ const files = [...new Set(ops.map((entry) => entry.path))];
588
+ if (files.length === 1) {
589
+ const verb = ops[0].op === "add" ? "create" : ops[0].op === "delete" ? "delete" : ops[0].op === "move" ? "move" : "edit";
590
+ return `${verb} file: ${files[0]}`;
591
+ }
592
+ return `apply patch to ${files.length} files`;
593
+ };
594
+ var toPolicyLookup = (toolName, toolInput, cwd) => {
595
+ if (toolName !== "apply_patch") return { tool: toolName, input: toolInput };
596
+ const command = toolInput.command;
597
+ const files = parseApplyPatchFiles(command);
598
+ if (files.length === 1) {
599
+ return { tool: "Edit", input: { file_path: cwd ? resolve(cwd, files[0]) : files[0] } };
600
+ }
601
+ return { tool: "Edit", input: typeof command === "string" ? { file_path: command } : {} };
602
+ };
603
+ var permissionTimeoutDecision = (timeoutAction) => {
604
+ if (timeoutAction === "approve") return codexAllow();
605
+ if (timeoutAction === "deny") return codexDeny("No response within timeout");
606
+ return codexPass();
607
+ };
608
+ var preToolUseTimeoutDecision = (timeoutAction, denyReason = "No response within timeout") => timeoutAction === "deny" ? codexDeny(denyReason) : codexPass();
609
+
610
+ // src/throttle.ts
611
+ import { join as join4 } from "path";
612
+ import { tmpdir as tmpdir4 } from "os";
613
+ import { createHash as createHash3 } from "crypto";
614
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "fs";
615
+ var THROTTLE_DIR = join4(tmpdir4(), "pushary-throttle");
616
+ var markerPath = (key) => join4(THROTTLE_DIR, createHash3("sha256").update(key).digest("hex").slice(0, 16));
617
+ var throttlePass = (key, windowMs) => {
618
+ try {
619
+ const path = markerPath(key);
620
+ if (existsSync3(path) && Date.now() - statSync3(path).mtimeMs < windowMs) return false;
621
+ mkdirSync3(THROTTLE_DIR, { recursive: true });
622
+ writeFileSync4(path, "", "utf-8");
623
+ return true;
624
+ } catch {
625
+ return false;
626
+ }
627
+ };
628
+
629
+ // src/events.ts
630
+ import { basename, join as join5 } from "path";
631
+ import { createHash as createHash4 } from "crypto";
632
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync3, statSync as statSync4, writeFileSync as writeFileSync5 } from "fs";
633
+ import { tmpdir as tmpdir5 } from "os";
634
+ var INTENT_DIR = join5(tmpdir5(), "pushary-intent");
635
+ var INTENT_MAX_BYTES = 2048;
636
+ var INTENT_GRACE_MS = 10 * 60 * 1e3;
637
+ var sanitizeSession = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
638
+ var intentFile = (sessionId) => join5(INTENT_DIR, sanitizeSession(sessionId));
639
+ var saveLastPrompt = (sessionId, prompt) => {
640
+ try {
641
+ const trimmed = prompt.replace(/\s+/g, " ").trim().slice(0, INTENT_MAX_BYTES);
642
+ if (!trimmed) return;
643
+ mkdirSync4(INTENT_DIR, { recursive: true });
644
+ writeFileSync5(intentFile(sessionId), trimmed, "utf-8");
645
+ } catch {
646
+ }
647
+ };
648
+ var readLastPrompt = (sessionId) => {
649
+ try {
650
+ const path = intentFile(sessionId);
651
+ if (isDefaultSession(sessionId) && statSync4(path).mtimeMs < Date.now() - INTENT_GRACE_MS) return void 0;
652
+ const value = readFileSync3(path, "utf-8").trim();
653
+ return value.length > 0 ? value : void 0;
654
+ } catch {
655
+ return void 0;
656
+ }
657
+ };
658
+ var reconcilePendingQuestions = async (sessionId) => {
659
+ const late = [];
660
+ try {
661
+ const files = listPendingQuestions(sessionId);
662
+ if (files.length === 0) return late;
663
+ const apiKey = getApiKey();
664
+ for (const correlationId of files) {
665
+ try {
666
+ const answer = await waitForAnswer(apiKey, correlationId, 1e3);
667
+ if (answer.answered) {
668
+ late.push({ correlationId, value: answer.value });
669
+ continue;
670
+ }
671
+ await cancelQuestion(apiKey, correlationId).catch(() => {
672
+ });
673
+ } catch {
674
+ continue;
675
+ }
676
+ removePendingQuestion(sessionId, correlationId);
677
+ }
678
+ } catch {
679
+ }
680
+ return late;
681
+ };
682
+ var describeLateAnswer = (value) => {
683
+ const v = (value ?? "").trim();
684
+ if (v === "yes") return "approved it";
685
+ if (v === "no") return "rejected it";
686
+ if (v === "defer") return "chose to handle it on this machine";
687
+ return v ? `answered "${v.slice(0, 200)}"` : "responded";
688
+ };
689
+ var buildLateAnswerContext = (late) => {
690
+ if (late.length === 0) return void 0;
691
+ const parts = late.map((l) => `you ${describeLateAnswer(l.value)} on your phone`);
692
+ return `Pushary: a permission prompt you were sent was answered late \u2014 ${parts.join("; ")} \u2014 after the terminal already took over. Treat this as the user's latest intent; do not assume the earlier terminal decision matched it.`;
693
+ };
694
+ var notifyLateAnswers = async (apiKey, late, agentName, sessionId) => {
695
+ if (late.length === 0) return;
696
+ const summary = late.map((l) => describeLateAnswer(l.value)).join(", ");
697
+ await sendNotification(apiKey, {
698
+ title: "Answer arrived late",
699
+ body: `You ${summary} after the agent had already moved on.`,
700
+ agentName,
701
+ sessionId
702
+ }, 2500).catch(() => {
703
+ });
704
+ };
705
+ var CLAUDE_CODE_AGENT = { type: "claude_code", label: "Claude Code" };
706
+ var POLICY_CACHE_TTL_MS = 5 * 60 * 1e3;
707
+ var readFreshCachedPolicy = (apiKey) => {
708
+ const hash = createHash4("sha256").update(apiKey).digest("hex").slice(0, 12);
709
+ const path = join5(tmpdir5(), `pushary-policy-${hash}.json`);
710
+ if (!existsSync4(path)) return null;
711
+ const cached = JSON.parse(readFileSync3(path, "utf-8"));
712
+ if (!isPolicyConfig(cached)) return null;
713
+ if (!cached._cachedAt || Date.now() - cached._cachedAt >= POLICY_CACHE_TTL_MS) return null;
714
+ return cached;
715
+ };
716
+ var deriveDecisionSource = (toolName, toolInput, liveMode) => {
717
+ try {
718
+ if (liveMode.kill) return "terminal";
719
+ const policy = readFreshCachedPolicy(getApiKey());
720
+ if (!policy) return void 0;
721
+ const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
722
+ if (resolved.timeoutSeconds === 0 && resolved.timeoutAction === "approve") return "policy_auto";
723
+ if (resolved.mode === "push_only" || resolved.mode === "push_first") return "human";
724
+ return "terminal";
725
+ } catch {
726
+ return void 0;
727
+ }
728
+ };
729
+ var deriveAutoDecisionBeacon = (toolName, toolInput, liveMode) => {
730
+ try {
731
+ if (liveMode.kill) return void 0;
732
+ const policy = readFreshCachedPolicy(getApiKey());
733
+ if (!policy) return void 0;
734
+ const resolved = resolvePolicy(policy, toolName, liveMode.mode, toolInput);
735
+ if (resolved.timeoutSeconds !== 0 || resolved.timeoutAction !== "approve") return void 0;
736
+ return {
737
+ decisionOrigin: resolveAutoResolveOrigin(policy, toolName, toolInput),
738
+ toolName,
739
+ toolTarget: deriveToolTarget(toolName, toolInput)
740
+ };
741
+ } catch {
742
+ return void 0;
743
+ }
744
+ };
745
+ var AUTO_DECISION_WINDOW_MS = 15 * 60 * 1e3;
746
+ var HOOK_ACTIVE_WINDOW_MS = 30 * 60 * 1e3;
747
+ var deriveUsage = (transcriptPath, sessionId) => {
748
+ if (!transcriptPath || process.env.PUSHARY_COST_TRACKING === "off") return void 0;
749
+ try {
750
+ return readNewUsage(transcriptPath, sessionId || DEFAULT_SESSION) ?? void 0;
751
+ } catch {
752
+ return void 0;
753
+ }
754
+ };
755
+ var detectInstallMode = () => (process.argv[1] ?? "").includes("_npx") ? "npx" : "cli";
756
+ var reportEvent = async (event, options = {}) => {
757
+ const apiKey = getApiKey();
758
+ const baseUrl = getBaseUrl();
759
+ return withRetry(async () => {
760
+ const res = await fetch(`${baseUrl}/api/agent/event`, {
761
+ method: "POST",
762
+ headers: {
763
+ "Content-Type": "application/json",
764
+ "Authorization": `Bearer ${apiKey}`
765
+ },
766
+ body: JSON.stringify({
767
+ ...event,
768
+ machineId: event.machineId ?? getMachineId(),
769
+ installMode: detectInstallMode()
770
+ }),
771
+ signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
772
+ });
773
+ try {
774
+ return await res.json();
775
+ } catch {
776
+ return null;
777
+ }
778
+ }, { maxAttempts: options.maxAttempts ?? 2, baseDelayMs: 300 });
779
+ };
780
+ var handlePostToolUse = async (input, agent = CLAUDE_CODE_AGENT) => {
781
+ try {
782
+ const projectName = basename(input.cwd ?? process.cwd());
783
+ const action = describeToolCall(input.tool_name, input.tool_input, "event");
784
+ const lookup = toPolicyLookup(input.tool_name, input.tool_input);
785
+ const isError = isToolResultError(input.tool_result);
786
+ const receiptsEnabled = process.env.PUSHARY_RECEIPTS !== "off";
787
+ const sessionKey = input.session_id || DEFAULT_SESSION;
788
+ const liveMode = await fetchModeState(getApiKey(), input.session_id);
789
+ const late = await reconcilePendingQuestions(sessionKey);
790
+ let additionalContext;
791
+ if (late.length > 0 && agent.type === CLAUDE_CODE_AGENT.type) {
792
+ additionalContext = buildLateAnswerContext(late);
793
+ for (const l of late) removePendingQuestion(sessionKey, l.correlationId);
794
+ }
795
+ const decisionSource = deriveDecisionSource(lookup.tool, lookup.input, liveMode);
796
+ const beacon = decisionSource === "policy_auto" && throttlePass(`autodecision:${sessionKey}:${lookup.tool}`, AUTO_DECISION_WINDOW_MS) ? deriveAutoDecisionBeacon(lookup.tool, lookup.input, liveMode) : void 0;
797
+ const reports = [
798
+ reportEvent({
799
+ event: isError ? "tool_error" : "tool_complete",
800
+ agentType: agent.type,
801
+ agentName: `${agent.label} - ${projectName}`,
802
+ action,
803
+ sessionId: input.session_id,
804
+ error: isError ? String(input.tool_result?.error ?? input.tool_result?.stderr ?? "").slice(0, 500) : void 0,
805
+ decisionSource,
806
+ ...beacon ? { decisionOrigin: beacon.decisionOrigin, toolName: beacon.toolName, toolTarget: beacon.toolTarget } : {},
807
+ meta: receiptsEnabled ? deriveReceiptMeta(lookup.tool, lookup.input, input.tool_result, input.cwd ?? process.cwd()) : void 0,
808
+ usage: deriveUsage(input.transcript_path, input.session_id)
809
+ })
810
+ ];
811
+ if (throttlePass(`hookactive:${sessionKey}`, HOOK_ACTIVE_WINDOW_MS)) {
812
+ reports.push(
813
+ reportEvent(
814
+ {
815
+ event: "agent_hook_active",
816
+ agentType: agent.type,
817
+ agentName: `${agent.label} - ${projectName}`,
818
+ sessionId: input.session_id
819
+ },
820
+ { maxAttempts: 1, timeoutMs: 800 }
821
+ )
822
+ );
823
+ }
824
+ await Promise.allSettled(reports);
825
+ return additionalContext;
826
+ } catch {
827
+ return void 0;
828
+ }
829
+ };
830
+ var TASK_TITLE_MAX_LENGTH = 120;
831
+ var handleUserPrompt = async (input, agent = CLAUDE_CODE_AGENT) => {
832
+ try {
833
+ const projectName = basename(input.cwd ?? process.cwd());
834
+ const sessionKey = input.session_id || DEFAULT_SESSION;
835
+ const titlesEnabled = process.env.PUSHARY_TASK_TITLES !== "off";
836
+ const taskTitle = titlesEnabled ? input.prompt?.replace(/\s+/g, " ").trim().slice(0, TASK_TITLE_MAX_LENGTH) || void 0 : void 0;
837
+ if (input.prompt) saveLastPrompt(sessionKey, input.prompt);
838
+ const late = await reconcilePendingQuestions(sessionKey);
839
+ let additionalContext;
840
+ if (late.length > 0 && agent.type === CLAUDE_CODE_AGENT.type) {
841
+ additionalContext = buildLateAnswerContext(late);
842
+ for (const l of late) removePendingQuestion(sessionKey, l.correlationId);
843
+ }
844
+ await reportEvent({
845
+ event: "user_prompt",
846
+ agentType: agent.type,
847
+ agentName: `${agent.label} - ${projectName}`,
848
+ sessionId: input.session_id,
849
+ taskTitle
850
+ }, { maxAttempts: 1, timeoutMs: 800 });
851
+ return additionalContext;
852
+ } catch {
853
+ return void 0;
854
+ }
855
+ };
856
+ var handleStop = async (input, agent = CLAUDE_CODE_AGENT) => {
857
+ try {
858
+ const projectName = basename(input.cwd ?? process.cwd());
859
+ const sessionKey = input.session_id || DEFAULT_SESSION;
860
+ const late = await reconcilePendingQuestions(sessionKey);
861
+ const tasks = [
862
+ reportEvent({
863
+ event: "session_end",
864
+ agentType: agent.type,
865
+ agentName: `${agent.label} - ${projectName}`,
866
+ action: "Session ended",
867
+ sessionId: input.session_id,
868
+ usage: deriveUsage(input.transcript_path, input.session_id)
869
+ })
870
+ ];
871
+ if (late.length > 0) {
872
+ tasks.push(notifyLateAnswers(getApiKey(), late, `${agent.label} - ${projectName}`, input.session_id));
873
+ for (const l of late) removePendingQuestion(sessionKey, l.correlationId);
874
+ }
875
+ if (!isDefaultSession(sessionKey)) removePendingSession(sessionKey);
876
+ const [reported] = await Promise.allSettled(tasks);
877
+ const pendingCommand = reported.status === "fulfilled" ? reported.value?.pendingCommand : void 0;
878
+ if (typeof pendingCommand === "string" && pendingCommand.trim().length > 0) {
879
+ return {
880
+ decision: "block",
881
+ reason: `The user sent a new instruction from their phone via Pushary: ${pendingCommand.trim()}`
882
+ };
883
+ }
884
+ return void 0;
885
+ } catch {
886
+ return void 0;
887
+ }
888
+ };
889
+ var handleNotification = async (input) => {
890
+ try {
891
+ const projectName = basename(input.cwd ?? process.cwd());
892
+ await reportEvent({
893
+ event: input.type === "error" ? "error" : "notification",
894
+ agentType: "claude_code",
895
+ agentName: `Claude Code - ${projectName}`,
896
+ action: input.title ?? input.message ?? "Notification",
897
+ sessionId: input.session_id,
898
+ error: input.type === "error" ? input.message : void 0
899
+ });
900
+ } catch {
901
+ }
902
+ };
903
+
904
+ export {
905
+ askUser,
906
+ waitForAnswer,
907
+ cancelQuestion,
908
+ sendNotification,
909
+ getPolicy,
910
+ resolvePolicy,
911
+ fetchModeState,
912
+ fetchModeOverride,
913
+ describeToolCall,
914
+ deriveToolTarget,
915
+ deriveActionBody,
916
+ deriveAction,
917
+ deriveBlocker,
918
+ getMachineId,
919
+ DEFAULT_SESSION,
920
+ savePendingQuestion,
921
+ readLastUserPrompt,
922
+ CODEX_AGENT,
923
+ codexAllow,
924
+ codexDeny,
925
+ codexPass,
926
+ toCodexWire,
927
+ describeApplyPatch,
928
+ toPolicyLookup,
929
+ permissionTimeoutDecision,
930
+ preToolUseTimeoutDecision,
931
+ readLastPrompt,
932
+ reportEvent,
933
+ handlePostToolUse,
934
+ handleUserPrompt,
935
+ handleStop,
936
+ handleNotification
937
+ };