@pushary/agent-hooks 0.22.0 → 0.24.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 (91) hide show
  1. package/data/cursor-plugin/README.md +5 -1
  2. package/data/cursor-plugin/mcp.json +1 -1
  3. package/dist/bin/pushary-clean.js +1 -1
  4. package/dist/bin/pushary-codex-hook.js +2 -4
  5. package/dist/bin/pushary-codex.js +1 -2
  6. package/dist/bin/pushary-doctor.js +2 -2
  7. package/dist/bin/pushary-gemini-hook.js +2 -4
  8. package/dist/bin/pushary-hook.js +2 -3
  9. package/dist/bin/pushary-post-hook.js +1 -2
  10. package/dist/bin/pushary-prompt-hook.js +1 -2
  11. package/dist/bin/pushary-setup.js +39 -3
  12. package/dist/bin/pushary-stop-hook.js +1 -2
  13. package/dist/{chunk-BHAMEPOP.js → chunk-JPRRYC5X.js} +5 -0
  14. package/dist/{chunk-5LTQNC7R.js → chunk-OQZH5PVA.js} +242 -33
  15. package/dist/{chunk-3LC4YUMA.js → chunk-U4SSWRVM.js} +1 -1
  16. package/dist/src/index.d.ts +15 -10
  17. package/dist/src/index.js +2 -3
  18. package/package.json +1 -1
  19. package/dist/chunk-22CV7V7A.js +0 -38
  20. package/dist/chunk-2BE2IPMO.js +0 -315
  21. package/dist/chunk-2CRLBMOX.js +0 -244
  22. package/dist/chunk-2HMNOZPY.js +0 -109
  23. package/dist/chunk-2I6DLXJN.js +0 -219
  24. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  25. package/dist/chunk-3MIR7ODJ.js +0 -112
  26. package/dist/chunk-3QZESA66.js +0 -222
  27. package/dist/chunk-4Z4MB37G.js +0 -96
  28. package/dist/chunk-5GFUI5N6.js +0 -132
  29. package/dist/chunk-5JEDLXEC.js +0 -99
  30. package/dist/chunk-5QHQVXWN.js +0 -174
  31. package/dist/chunk-6A3WCJO2.js +0 -416
  32. package/dist/chunk-6QWFMVCD.js +0 -328
  33. package/dist/chunk-6SRXMZAN.js +0 -99
  34. package/dist/chunk-7PTU7TGE.js +0 -96
  35. package/dist/chunk-AB4KX4XT.js +0 -109
  36. package/dist/chunk-AC4UYAGX.js +0 -136
  37. package/dist/chunk-ACE77TKQ.js +0 -328
  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-FXYTRZHC.js +0 -177
  46. package/dist/chunk-GTJGZBTQ.js +0 -328
  47. package/dist/chunk-HJMFYDWY.js +0 -222
  48. package/dist/chunk-HRQEECB6.js +0 -315
  49. package/dist/chunk-HWEMAAOY.js +0 -370
  50. package/dist/chunk-IBWCHA5M.js +0 -10
  51. package/dist/chunk-KTM4ZQ3W.js +0 -96
  52. package/dist/chunk-KTP2EPVB.js +0 -27
  53. package/dist/chunk-KYARP7KP.js +0 -97
  54. package/dist/chunk-M2N5DYWN.js +0 -247
  55. package/dist/chunk-M5F2L4KF.js +0 -177
  56. package/dist/chunk-M6S3M6E3.js +0 -244
  57. package/dist/chunk-N7VXDBQU.js +0 -6
  58. package/dist/chunk-O6A5RHWY.js +0 -122
  59. package/dist/chunk-ODUXELPM.js +0 -219
  60. package/dist/chunk-OF5WIOYS.js +0 -129
  61. package/dist/chunk-OP4QAN23.js +0 -99
  62. package/dist/chunk-P4JH2Q7Z.js +0 -102
  63. package/dist/chunk-PMD5JSV3.js +0 -242
  64. package/dist/chunk-PSSHNBEL.js +0 -177
  65. package/dist/chunk-QEPRH7JB.js +0 -315
  66. package/dist/chunk-QRXWPZKN.js +0 -308
  67. package/dist/chunk-QY4L6XHN.js +0 -384
  68. package/dist/chunk-RNWPCELY.js +0 -176
  69. package/dist/chunk-RSHN2AQ7.js +0 -29
  70. package/dist/chunk-RZLVE57X.js +0 -38
  71. package/dist/chunk-SDCIKREA.js +0 -241
  72. package/dist/chunk-SDREQWNI.js +0 -175
  73. package/dist/chunk-SH26ZOHU.js +0 -159
  74. package/dist/chunk-TRLBBLSS.js +0 -176
  75. package/dist/chunk-U6OXZPYC.js +0 -384
  76. package/dist/chunk-UIBTFZUD.js +0 -314
  77. package/dist/chunk-USUCPCUC.js +0 -156
  78. package/dist/chunk-V4GLWPD7.js +0 -174
  79. package/dist/chunk-VC6U3QGF.js +0 -142
  80. package/dist/chunk-VIST7ACL.js +0 -88
  81. package/dist/chunk-VUNL35KE.js +0 -16
  82. package/dist/chunk-VWBNI4SC.js +0 -174
  83. package/dist/chunk-W5KRWUNE.js +0 -262
  84. package/dist/chunk-WCGKLHCL.js +0 -154
  85. package/dist/chunk-WNXGIEX7.js +0 -219
  86. package/dist/chunk-XPVSZIA3.js +0 -315
  87. package/dist/chunk-Y633ZIJF.js +0 -384
  88. package/dist/chunk-YCL4GUFR.js +0 -222
  89. package/dist/chunk-YTMKB44I.js +0 -220
  90. package/dist/chunk-ZWBS3T7Q.js +0 -244
  91. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
@@ -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
- };
@@ -1,112 +0,0 @@
1
- import {
2
- getBaseUrl
3
- } from "./chunk-VUNL35KE.js";
4
-
5
- // src/retry.ts
6
- var isRetryable = (err) => {
7
- if (!(err instanceof Error)) return false;
8
- const msg = err.message;
9
- return /\b(502|503|429)\b/.test(msg) || /ECONNRESET|ECONNREFUSED|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|fetch failed/i.test(msg) || msg.includes("AbortError");
10
- };
11
- var withRetry = async (fn, options = {}) => {
12
- const {
13
- maxAttempts = 3,
14
- baseDelayMs = 500,
15
- maxDelayMs = 5e3,
16
- shouldRetry = isRetryable
17
- } = options;
18
- let lastError;
19
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
20
- try {
21
- return await fn();
22
- } catch (err) {
23
- lastError = err;
24
- if (attempt + 1 >= maxAttempts || !shouldRetry(err)) throw err;
25
- const jitter = Math.random() * 0.3 + 0.85;
26
- const delay = Math.min(baseDelayMs * 2 ** attempt * jitter, maxDelayMs);
27
- await new Promise((r) => setTimeout(r, delay));
28
- }
29
- }
30
- throw lastError;
31
- };
32
-
33
- // src/mcp-http.ts
34
- var parseSseJson = (body) => {
35
- const messages = [];
36
- for (const event of body.split(/\r?\n\r?\n/)) {
37
- const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n").trim();
38
- if (!data) continue;
39
- try {
40
- messages.push(JSON.parse(data));
41
- } catch {
42
- }
43
- }
44
- const message = messages.at(-1);
45
- if (!message) throw new Error("Empty response from Pushary");
46
- return message;
47
- };
48
- var parseMcpResponse = (body, contentType) => {
49
- if (contentType?.includes("text/event-stream")) {
50
- return parseSseJson(body);
51
- }
52
- return JSON.parse(body);
53
- };
54
- var sendMcpRequest = async (apiKey, message, options = {}) => {
55
- return withRetry(async () => {
56
- const baseUrl = options.baseUrl ?? getBaseUrl();
57
- const fetchFn = options.fetchFn ?? fetch;
58
- const headers = {
59
- "Content-Type": "application/json",
60
- "Accept": "application/json, text/event-stream",
61
- "Authorization": `Bearer ${apiKey}`
62
- };
63
- if (options.sessionId) {
64
- headers["Mcp-Session-Id"] = options.sessionId;
65
- }
66
- const response = await fetchFn(`${baseUrl}/api/mcp/mcp`, {
67
- method: "POST",
68
- headers,
69
- body: JSON.stringify(message),
70
- signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0
71
- });
72
- const body = await response.text();
73
- const contentType = response.headers.get("content-type");
74
- let data = null;
75
- if (body.trim()) {
76
- try {
77
- data = parseMcpResponse(body, contentType);
78
- } catch (err) {
79
- if (response.ok) throw err;
80
- }
81
- }
82
- if (!response.ok) {
83
- const msg = data?.error?.message ?? (body.trim() || response.statusText);
84
- throw new Error(`Pushary MCP error: ${response.status} ${msg}`);
85
- }
86
- if (!data) throw new Error("Empty response from Pushary");
87
- if (data.error) throw new Error(data.error.message ?? "Pushary MCP error");
88
- return {
89
- data,
90
- sessionId: response.headers.get("mcp-session-id") ?? "",
91
- status: response.status,
92
- statusText: response.statusText
93
- };
94
- }, { maxAttempts: options.maxRetries ?? 1 });
95
- };
96
- var callMcpTool = async (apiKey, toolName, params, options = {}) => {
97
- const { data } = await sendMcpRequest(apiKey, {
98
- jsonrpc: "2.0",
99
- id: options.id ?? Date.now(),
100
- method: "tools/call",
101
- params: { name: toolName, arguments: params }
102
- }, options);
103
- const text = data.result?.content?.[0]?.text;
104
- if (!text) throw new Error("Empty response from Pushary");
105
- return JSON.parse(text);
106
- };
107
-
108
- export {
109
- withRetry,
110
- sendMcpRequest,
111
- callMcpTool
112
- };