@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,177 +0,0 @@
1
- import {
2
- denyReasonFrom
3
- } from "./chunk-N7VXDBQU.js";
4
- import {
5
- DEFAULT_SESSION,
6
- askUser,
7
- deriveToolTarget,
8
- describeToolCall,
9
- fetchModeState,
10
- getMachineId,
11
- getPolicy,
12
- resolvePolicy,
13
- savePendingQuestion,
14
- sendNotification,
15
- waitForAnswer
16
- } from "./chunk-6QWFMVCD.js";
17
- import {
18
- getApiKey
19
- } from "./chunk-NKXSILEW.js";
20
-
21
- // src/hook.ts
22
- import { basename } from "path";
23
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
- var allow = () => ({
25
- hookSpecificOutput: {
26
- hookEventName: "PreToolUse",
27
- permissionDecision: "allow"
28
- }
29
- });
30
- var deny = (reason) => ({
31
- hookSpecificOutput: {
32
- hookEventName: "PreToolUse",
33
- permissionDecision: "deny",
34
- permissionDecisionReason: reason
35
- }
36
- });
37
- var ask = (reason) => ({
38
- hookSpecificOutput: {
39
- hookEventName: "PreToolUse",
40
- permissionDecision: "ask",
41
- ...reason ? { permissionDecisionReason: reason } : {}
42
- }
43
- });
44
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
45
- while (Date.now() < deadlineMs) {
46
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
47
- let answer;
48
- try {
49
- answer = await waitForAnswer(apiKey, correlationId, remaining);
50
- } catch {
51
- if (Date.now() + pollInterval >= deadlineMs) break;
52
- await sleep(pollInterval);
53
- continue;
54
- }
55
- if (answer.answered) return answer;
56
- if (Date.now() + pollInterval >= deadlineMs) break;
57
- await sleep(pollInterval);
58
- }
59
- return { answered: false };
60
- };
61
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction, sessionId, machineId, toolName, toolTarget) => {
62
- let result;
63
- try {
64
- result = await askUser(apiKey, {
65
- question: `Allow ${description}?`,
66
- type: "confirm",
67
- context: `Agent wants to run this in ${projectName}`,
68
- agentName: `Claude Code - ${projectName}`,
69
- sessionId,
70
- machineId,
71
- toolName,
72
- toolTarget
73
- });
74
- } catch {
75
- switch (timeoutAction) {
76
- case "approve":
77
- return allow();
78
- case "deny":
79
- return deny("Push notification failed, denying per policy");
80
- default:
81
- return ask("Push notification failed, asking in terminal");
82
- }
83
- }
84
- const deadline = Date.now() + timeoutSeconds * 1e3;
85
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
86
- if (answer.answered) {
87
- return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
88
- }
89
- switch (timeoutAction) {
90
- case "approve":
91
- return allow();
92
- case "deny":
93
- return deny("No response within timeout");
94
- default:
95
- return ask("No push response, asking in terminal");
96
- }
97
- };
98
- var handleTerminalOnly = () => {
99
- return ask();
100
- };
101
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds, sessionId, machineId, toolName, toolTarget) => {
102
- let result;
103
- try {
104
- result = await askUser(apiKey, {
105
- question: `Allow ${description}?`,
106
- type: "confirm",
107
- context: `Agent wants to run this in ${projectName}`,
108
- agentName: `Claude Code - ${projectName}`,
109
- sessionId,
110
- machineId,
111
- toolName,
112
- toolTarget
113
- });
114
- } catch {
115
- return ask("Push notification failed, asking in terminal");
116
- }
117
- const deadline = Date.now() + pushFirstSeconds * 1e3;
118
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
119
- if (answer.answered) {
120
- return answer.value === "yes" ? allow() : deny(denyReasonFrom(answer.value));
121
- }
122
- savePendingQuestion(sessionId || DEFAULT_SESSION, result.correlationId);
123
- return ask("Sent as push notification. You can also approve here.");
124
- };
125
- var handleNotifyOnly = async (apiKey, description, projectName, sessionId, machineId) => {
126
- try {
127
- await sendNotification(apiKey, {
128
- title: "Agent needs approval",
129
- body: description,
130
- agentName: `Claude Code - ${projectName}`,
131
- sessionId,
132
- machineId
133
- });
134
- } catch {
135
- }
136
- return ask();
137
- };
138
- var handlePreToolUse = async (input) => {
139
- try {
140
- const apiKey = getApiKey();
141
- const modeState = await fetchModeState(apiKey, input.session_id);
142
- const policy = await getPolicy(apiKey, modeState.policyVersion);
143
- if (modeState.kill) {
144
- return deny("Stopped by user \u2014 this agent was halted from Pushary");
145
- }
146
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeState.mode, input.tool_input);
147
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
148
- return allow();
149
- }
150
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "deny") {
151
- return deny(`Denied by policy for ${toolPolicy.tool}`);
152
- }
153
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
154
- const projectName = basename(input.cwd ?? process.cwd());
155
- const sessionId = input.session_id;
156
- const machineId = getMachineId();
157
- const toolTarget = deriveToolTarget(input.tool_name, input.tool_input);
158
- switch (toolPolicy.mode) {
159
- case "push_only":
160
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction, sessionId, machineId, input.tool_name, toolTarget);
161
- case "terminal_only":
162
- return handleTerminalOnly();
163
- case "push_first":
164
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
165
- case "notify_only":
166
- return handleNotifyOnly(apiKey, description, projectName, sessionId, machineId);
167
- default:
168
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds, sessionId, machineId, input.tool_name, toolTarget);
169
- }
170
- } catch {
171
- return ask("Pushary unavailable, falling back to terminal approval");
172
- }
173
- };
174
-
175
- export {
176
- handlePreToolUse
177
- };
@@ -1,244 +0,0 @@
1
- import {
2
- askUser,
3
- describeToolCall,
4
- isPolicyConfig,
5
- savePendingQuestion,
6
- sendNotification,
7
- waitForAnswer
8
- } from "./chunk-7PTU7TGE.js";
9
- import {
10
- withRetry
11
- } from "./chunk-3MIR7ODJ.js";
12
- import {
13
- getApiKey,
14
- getBaseUrl
15
- } from "./chunk-VUNL35KE.js";
16
-
17
- // src/policy.ts
18
- import { createHash } from "crypto";
19
- import { existsSync, readFileSync, writeFileSync } from "fs";
20
- import { join } from "path";
21
- import { tmpdir } from "os";
22
- var CACHE_TTL_MS = 5 * 60 * 1e3;
23
- var cacheFile = (apiKey) => {
24
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
25
- return join(tmpdir(), `pushary-policy-${hash}.json`);
26
- };
27
- var fetchPolicy = async (apiKey) => {
28
- return withRetry(async () => {
29
- const baseUrl = getBaseUrl();
30
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
31
- headers: { "Authorization": `Bearer ${apiKey}` },
32
- signal: AbortSignal.timeout(1e4)
33
- });
34
- if (!response.ok) {
35
- throw new Error(`Failed to fetch policy: ${response.status}`);
36
- }
37
- const raw = await response.json();
38
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
39
- return raw;
40
- }, { maxAttempts: 2 });
41
- };
42
- var getPolicy = async (apiKey) => {
43
- const path = cacheFile(apiKey);
44
- let staleCache = null;
45
- if (existsSync(path)) {
46
- try {
47
- const stat = readFileSync(path, "utf-8");
48
- const cached = JSON.parse(stat);
49
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
50
- if (!cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS) {
51
- return cached;
52
- }
53
- staleCache = cached;
54
- } catch {
55
- }
56
- }
57
- try {
58
- const policy = await fetchPolicy(apiKey);
59
- try {
60
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now() }), "utf-8");
61
- } catch {
62
- }
63
- return policy;
64
- } catch {
65
- if (staleCache) return staleCache;
66
- throw new Error("Failed to fetch policy and no cached policy available");
67
- }
68
- };
69
- var resolvePolicy = (config, toolName, modeOverride) => {
70
- const base = config.policies.find((p) => p.tool === toolName) ?? config.policies.find((p) => p.tool === "*") ?? {
71
- tool: toolName,
72
- timeoutSeconds: config.defaultTimeoutSeconds,
73
- timeoutAction: config.defaultTimeoutAction,
74
- mode: config.defaultMode ?? "push_first",
75
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
76
- };
77
- const effectiveOverride = modeOverride ?? config.modeOverride;
78
- if (effectiveOverride) {
79
- return { ...base, mode: effectiveOverride };
80
- }
81
- return base;
82
- };
83
- var fetchModeOverride = async (apiKey) => {
84
- try {
85
- const baseUrl = getBaseUrl();
86
- const response = await fetch(`${baseUrl}/api/mcp/mode`, {
87
- headers: { "Authorization": `Bearer ${apiKey}` },
88
- signal: AbortSignal.timeout(3e3)
89
- });
90
- if (!response.ok) return null;
91
- const data = await response.json();
92
- const mode = data.override?.mode;
93
- if (mode && ["push_only", "terminal_only", "push_first", "notify_only"].includes(mode)) {
94
- return mode;
95
- }
96
- return null;
97
- } catch {
98
- return null;
99
- }
100
- };
101
-
102
- // src/hook.ts
103
- import { basename } from "path";
104
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
105
- var allow = () => ({
106
- hookSpecificOutput: {
107
- hookEventName: "PreToolUse",
108
- permissionDecision: "allow"
109
- }
110
- });
111
- var deny = (reason) => ({
112
- hookSpecificOutput: {
113
- hookEventName: "PreToolUse",
114
- permissionDecision: "deny",
115
- permissionDecisionReason: reason
116
- }
117
- });
118
- var ask = (reason) => ({
119
- hookSpecificOutput: {
120
- hookEventName: "PreToolUse",
121
- permissionDecision: "ask",
122
- ...reason ? { permissionDecisionReason: reason } : {}
123
- }
124
- });
125
- var pollForAnswer = async (apiKey, correlationId, deadlineMs, pollInterval = 2e3) => {
126
- while (Date.now() < deadlineMs) {
127
- const remaining = Math.min(Math.max(deadlineMs - Date.now(), 1e3), 3e4);
128
- let answer;
129
- try {
130
- answer = await waitForAnswer(apiKey, correlationId, remaining);
131
- } catch {
132
- if (Date.now() + pollInterval >= deadlineMs) break;
133
- await sleep(pollInterval);
134
- continue;
135
- }
136
- if (answer.answered) return answer;
137
- if (Date.now() + pollInterval >= deadlineMs) break;
138
- await sleep(pollInterval);
139
- }
140
- return { answered: false };
141
- };
142
- var handlePushOnly = async (apiKey, description, projectName, timeoutSeconds, timeoutAction) => {
143
- let result;
144
- try {
145
- result = await askUser(apiKey, {
146
- question: `Allow ${description}?`,
147
- type: "confirm",
148
- context: `Agent wants to run this in ${projectName}`,
149
- agentName: `Claude Code - ${projectName}`
150
- });
151
- } catch {
152
- switch (timeoutAction) {
153
- case "approve":
154
- return allow();
155
- case "deny":
156
- return deny("Push notification failed, denying per policy");
157
- default:
158
- return ask("Push notification failed, asking in terminal");
159
- }
160
- }
161
- const deadline = Date.now() + timeoutSeconds * 1e3;
162
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline);
163
- if (answer.answered) {
164
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
165
- }
166
- switch (timeoutAction) {
167
- case "approve":
168
- return allow();
169
- case "deny":
170
- return deny("No response within timeout");
171
- default:
172
- return ask("No push response, asking in terminal");
173
- }
174
- };
175
- var handleTerminalOnly = () => {
176
- return ask();
177
- };
178
- var handlePushFirst = async (apiKey, description, projectName, pushFirstSeconds) => {
179
- let result;
180
- try {
181
- result = await askUser(apiKey, {
182
- question: `Allow ${description}?`,
183
- type: "confirm",
184
- context: `Agent wants to run this in ${projectName}`,
185
- agentName: `Claude Code - ${projectName}`
186
- });
187
- } catch {
188
- return ask("Push notification failed, asking in terminal");
189
- }
190
- const deadline = Date.now() + pushFirstSeconds * 1e3;
191
- const answer = await pollForAnswer(apiKey, result.correlationId, deadline, 1500);
192
- if (answer.answered) {
193
- return answer.value === "yes" ? allow() : deny("Denied via push notification");
194
- }
195
- savePendingQuestion(result.correlationId);
196
- return ask("Sent as push notification. You can also approve here.");
197
- };
198
- var handleNotifyOnly = async (apiKey, description, projectName) => {
199
- try {
200
- await sendNotification(apiKey, {
201
- title: "Agent needs approval",
202
- body: description,
203
- agentName: `Claude Code - ${projectName}`
204
- });
205
- } catch {
206
- }
207
- return ask();
208
- };
209
- var handlePreToolUse = async (input) => {
210
- try {
211
- const apiKey = getApiKey();
212
- const [policy, modeOverride] = await Promise.all([
213
- getPolicy(apiKey),
214
- fetchModeOverride(apiKey)
215
- ]);
216
- const toolPolicy = resolvePolicy(policy, input.tool_name, modeOverride);
217
- if (toolPolicy.timeoutSeconds === 0 && toolPolicy.timeoutAction === "approve") {
218
- return allow();
219
- }
220
- const description = describeToolCall(input.tool_name, input.tool_input, "hook");
221
- const projectName = basename(input.cwd ?? process.cwd());
222
- switch (toolPolicy.mode) {
223
- case "push_only":
224
- return handlePushOnly(apiKey, description, projectName, toolPolicy.timeoutSeconds, toolPolicy.timeoutAction);
225
- case "terminal_only":
226
- return handleTerminalOnly();
227
- case "push_first":
228
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
229
- case "notify_only":
230
- return handleNotifyOnly(apiKey, description, projectName);
231
- default:
232
- return handlePushFirst(apiKey, description, projectName, toolPolicy.pushFirstSeconds);
233
- }
234
- } catch {
235
- return ask("Pushary unavailable, falling back to terminal approval");
236
- }
237
- };
238
-
239
- export {
240
- getPolicy,
241
- resolvePolicy,
242
- fetchModeOverride,
243
- handlePreToolUse
244
- };
@@ -1,6 +0,0 @@
1
- // src/answer.ts
2
- var denyReasonFrom = (value) => value && value !== "no" && value !== "yes" ? `Denied from your phone: ${value}` : "Denied via push notification";
3
-
4
- export {
5
- denyReasonFrom
6
- };
@@ -1,122 +0,0 @@
1
- // src/config.ts
2
- var getApiKey = () => {
3
- const key = process.env.PUSHARY_API_KEY;
4
- if (!key) {
5
- throw new Error(
6
- "PUSHARY_API_KEY environment variable is not set. Get your API key at https://pushary.com/sign-up?from=ai-coding"
7
- );
8
- }
9
- return key;
10
- };
11
- var getBaseUrl = () => process.env.PUSHARY_BASE_URL ?? "https://pushary.com";
12
-
13
- // src/retry.ts
14
- var isRetryable = (err) => {
15
- if (!(err instanceof Error)) return false;
16
- const msg = err.message;
17
- return /\b(502|503|429)\b/.test(msg) || /ECONNRESET|ECONNREFUSED|ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT|fetch failed/i.test(msg) || msg.includes("AbortError");
18
- };
19
- var withRetry = async (fn, options = {}) => {
20
- const {
21
- maxAttempts = 3,
22
- baseDelayMs = 500,
23
- maxDelayMs = 5e3,
24
- shouldRetry = isRetryable
25
- } = options;
26
- let lastError;
27
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
28
- try {
29
- return await fn();
30
- } catch (err) {
31
- lastError = err;
32
- if (attempt + 1 >= maxAttempts || !shouldRetry(err)) throw err;
33
- const jitter = Math.random() * 0.3 + 0.85;
34
- const delay = Math.min(baseDelayMs * 2 ** attempt * jitter, maxDelayMs);
35
- await new Promise((r) => setTimeout(r, delay));
36
- }
37
- }
38
- throw lastError;
39
- };
40
-
41
- // src/mcp-http.ts
42
- var parseSseJson = (body) => {
43
- const messages = [];
44
- for (const event of body.split(/\r?\n\r?\n/)) {
45
- const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n").trim();
46
- if (!data) continue;
47
- try {
48
- messages.push(JSON.parse(data));
49
- } catch {
50
- }
51
- }
52
- const message = messages.at(-1);
53
- if (!message) throw new Error("Empty response from Pushary");
54
- return message;
55
- };
56
- var parseMcpResponse = (body, contentType) => {
57
- if (contentType?.includes("text/event-stream")) {
58
- return parseSseJson(body);
59
- }
60
- return JSON.parse(body);
61
- };
62
- var sendMcpRequest = async (apiKey, message, options = {}) => {
63
- return withRetry(async () => {
64
- const baseUrl = options.baseUrl ?? getBaseUrl();
65
- const fetchFn = options.fetchFn ?? fetch;
66
- const headers = {
67
- "Content-Type": "application/json",
68
- "Accept": "application/json, text/event-stream",
69
- "Authorization": `Bearer ${apiKey}`
70
- };
71
- if (options.sessionId) {
72
- headers["Mcp-Session-Id"] = options.sessionId;
73
- }
74
- const response = await fetchFn(`${baseUrl}/api/mcp/mcp`, {
75
- method: "POST",
76
- headers,
77
- body: JSON.stringify(message),
78
- signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0
79
- });
80
- const body = await response.text();
81
- const contentType = response.headers.get("content-type");
82
- let data = null;
83
- if (body.trim()) {
84
- try {
85
- data = parseMcpResponse(body, contentType);
86
- } catch (err) {
87
- if (response.ok) throw err;
88
- }
89
- }
90
- if (!response.ok) {
91
- const msg = data?.error?.message ?? (body.trim() || response.statusText);
92
- throw new Error(`Pushary MCP error: ${response.status} ${msg}`);
93
- }
94
- if (!data) throw new Error("Empty response from Pushary");
95
- if (data.error) throw new Error(data.error.message ?? "Pushary MCP error");
96
- return {
97
- data,
98
- sessionId: response.headers.get("mcp-session-id") ?? "",
99
- status: response.status,
100
- statusText: response.statusText
101
- };
102
- }, { maxAttempts: options.maxRetries ?? 1 });
103
- };
104
- var callMcpTool = async (apiKey, toolName, params, options = {}) => {
105
- const { data } = await sendMcpRequest(apiKey, {
106
- jsonrpc: "2.0",
107
- id: options.id ?? Date.now(),
108
- method: "tools/call",
109
- params: { name: toolName, arguments: params }
110
- }, options);
111
- const text = data.result?.content?.[0]?.text;
112
- if (!text) throw new Error("Empty response from Pushary");
113
- return JSON.parse(text);
114
- };
115
-
116
- export {
117
- getApiKey,
118
- getBaseUrl,
119
- withRetry,
120
- sendMcpRequest,
121
- callMcpTool
122
- };