@pushary/agent-hooks 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/bin/pushary-clean.js +1 -1
  2. package/dist/bin/pushary-codex-hook.js +1 -1
  3. package/dist/bin/pushary-codex.js +1 -1
  4. package/dist/bin/pushary-doctor.js +21 -9
  5. package/dist/bin/pushary-gemini-hook.js +1 -1
  6. package/dist/bin/pushary-hook.js +2 -2
  7. package/dist/bin/pushary-post-hook.js +1 -1
  8. package/dist/bin/pushary-prompt-hook.js +1 -1
  9. package/dist/bin/pushary-setup.js +7 -19
  10. package/dist/bin/pushary-stop-hook.js +1 -1
  11. package/dist/{chunk-GYPPVD3P.js → chunk-A7DQCA2N.js} +1 -1
  12. package/dist/{chunk-O2QL6U6G.js → chunk-SA4BDS7T.js} +1 -1
  13. package/dist/{chunk-JPRRYC5X.js → chunk-SLX4AONG.js} +25 -0
  14. package/dist/src/index.js +2 -2
  15. package/package.json +1 -1
  16. package/dist/chunk-22CV7V7A.js +0 -38
  17. package/dist/chunk-2BE2IPMO.js +0 -315
  18. package/dist/chunk-2CRLBMOX.js +0 -244
  19. package/dist/chunk-2HMNOZPY.js +0 -109
  20. package/dist/chunk-2I6DLXJN.js +0 -219
  21. package/dist/chunk-2Q6XPZ4Q.js +0 -395
  22. package/dist/chunk-3LC4YUMA.js +0 -194
  23. package/dist/chunk-3MIR7ODJ.js +0 -112
  24. package/dist/chunk-3QZESA66.js +0 -222
  25. package/dist/chunk-4Z4MB37G.js +0 -96
  26. package/dist/chunk-5GFUI5N6.js +0 -132
  27. package/dist/chunk-5JEDLXEC.js +0 -99
  28. package/dist/chunk-5LTQNC7R.js +0 -824
  29. package/dist/chunk-5QHQVXWN.js +0 -174
  30. package/dist/chunk-6A3WCJO2.js +0 -416
  31. package/dist/chunk-6QWFMVCD.js +0 -328
  32. package/dist/chunk-6SRXMZAN.js +0 -99
  33. package/dist/chunk-7PTU7TGE.js +0 -96
  34. package/dist/chunk-AB4KX4XT.js +0 -109
  35. package/dist/chunk-AC4UYAGX.js +0 -136
  36. package/dist/chunk-ACE77TKQ.js +0 -328
  37. package/dist/chunk-BHAMEPOP.js +0 -323
  38. package/dist/chunk-BYNYYZWW.js +0 -412
  39. package/dist/chunk-C5TFTNHG.js +0 -244
  40. package/dist/chunk-CH53PBQN.js +0 -265
  41. package/dist/chunk-DF3BM6BF.js +0 -195
  42. package/dist/chunk-DKZVKEOW.js +0 -175
  43. package/dist/chunk-EMPL27ZV.js +0 -96
  44. package/dist/chunk-EQJXMEIR.js +0 -175
  45. package/dist/chunk-FGZZRCOG.js +0 -194
  46. package/dist/chunk-FXYTRZHC.js +0 -177
  47. package/dist/chunk-GTJGZBTQ.js +0 -328
  48. package/dist/chunk-HJMFYDWY.js +0 -222
  49. package/dist/chunk-HRQEECB6.js +0 -315
  50. package/dist/chunk-HWEMAAOY.js +0 -370
  51. package/dist/chunk-IBWCHA5M.js +0 -10
  52. package/dist/chunk-KTM4ZQ3W.js +0 -96
  53. package/dist/chunk-KTP2EPVB.js +0 -27
  54. package/dist/chunk-KYARP7KP.js +0 -97
  55. package/dist/chunk-M2N5DYWN.js +0 -247
  56. package/dist/chunk-M4GDBGXF.js +0 -824
  57. package/dist/chunk-M5F2L4KF.js +0 -177
  58. package/dist/chunk-M6S3M6E3.js +0 -244
  59. package/dist/chunk-N7VXDBQU.js +0 -6
  60. package/dist/chunk-O6A5RHWY.js +0 -122
  61. package/dist/chunk-ODUXELPM.js +0 -219
  62. package/dist/chunk-OF5WIOYS.js +0 -129
  63. package/dist/chunk-OP4QAN23.js +0 -99
  64. package/dist/chunk-P4JH2Q7Z.js +0 -102
  65. package/dist/chunk-PMD5JSV3.js +0 -242
  66. package/dist/chunk-PSSHNBEL.js +0 -177
  67. package/dist/chunk-QEPRH7JB.js +0 -315
  68. package/dist/chunk-QRXWPZKN.js +0 -308
  69. package/dist/chunk-QY4L6XHN.js +0 -384
  70. package/dist/chunk-RNWPCELY.js +0 -176
  71. package/dist/chunk-RSHN2AQ7.js +0 -29
  72. package/dist/chunk-RZLVE57X.js +0 -38
  73. package/dist/chunk-SDCIKREA.js +0 -241
  74. package/dist/chunk-SDREQWNI.js +0 -175
  75. package/dist/chunk-SH26ZOHU.js +0 -159
  76. package/dist/chunk-TRLBBLSS.js +0 -176
  77. package/dist/chunk-U6OXZPYC.js +0 -384
  78. package/dist/chunk-UIBTFZUD.js +0 -314
  79. package/dist/chunk-USUCPCUC.js +0 -156
  80. package/dist/chunk-V4GLWPD7.js +0 -174
  81. package/dist/chunk-VC6U3QGF.js +0 -142
  82. package/dist/chunk-VIST7ACL.js +0 -88
  83. package/dist/chunk-VUNL35KE.js +0 -16
  84. package/dist/chunk-VWBNI4SC.js +0 -174
  85. package/dist/chunk-W5KRWUNE.js +0 -262
  86. package/dist/chunk-WCGKLHCL.js +0 -154
  87. package/dist/chunk-WNXGIEX7.js +0 -219
  88. package/dist/chunk-WPVL6VIT.js +0 -160
  89. package/dist/chunk-XPVSZIA3.js +0 -315
  90. package/dist/chunk-Y633ZIJF.js +0 -384
  91. package/dist/chunk-YCL4GUFR.js +0 -222
  92. package/dist/chunk-YTMKB44I.js +0 -220
  93. package/dist/chunk-ZWBS3T7Q.js +0 -244
  94. package/dist/pushary-mode-T7XOPI6Z.js +0 -83
@@ -8,7 +8,7 @@ import {
8
8
  removeCodexHooks,
9
9
  removeGeminiSettings,
10
10
  removeInstructionBlock
11
- } from "../chunk-JPRRYC5X.js";
11
+ } from "../chunk-SLX4AONG.js";
12
12
 
13
13
  // bin/pushary-clean.ts
14
14
  import { existsSync, readFileSync, writeFileSync, rmSync } from "fs";
@@ -32,7 +32,7 @@ import {
32
32
  toCodexWire,
33
33
  toPolicyLookup,
34
34
  waitForAnswer
35
- } from "../chunk-GYPPVD3P.js";
35
+ } from "../chunk-A7DQCA2N.js";
36
36
  import "../chunk-DWED7BS3.js";
37
37
  import {
38
38
  getApiKey
@@ -4,7 +4,7 @@ import {
4
4
  getMachineId,
5
5
  reportEvent,
6
6
  waitForAnswer
7
- } from "../chunk-GYPPVD3P.js";
7
+ } from "../chunk-A7DQCA2N.js";
8
8
  import "../chunk-DWED7BS3.js";
9
9
  import {
10
10
  getApiKey
@@ -7,8 +7,9 @@ import {
7
7
  hasInstructionBlock,
8
8
  missingCodexHookEvents,
9
9
  missingGeminiHookEvents,
10
+ readCodexMcpAuth,
10
11
  untrustedCodexHookEvents
11
- } from "../chunk-JPRRYC5X.js";
12
+ } from "../chunk-SLX4AONG.js";
12
13
  import {
13
14
  callMcpTool,
14
15
  sendMcpRequest
@@ -171,22 +172,33 @@ var main = async () => {
171
172
  }
172
173
  const codexMcp = codexParsed.mcp_servers?.pushary;
173
174
  const codexTransport = !!codexMcp && (typeof codexMcp.url === "string" || typeof codexMcp.command === "string");
174
- const codexEnvVar = codexMcp && typeof codexMcp.bearer_token_env_var === "string" ? codexMcp.bearer_token_env_var : void 0;
175
- const codexHasCred = !!codexEnvVar || !!codexMcp && typeof codexMcp.bearer_token === "string";
176
- const codexMcpOk = !!codexMcp && codexTransport && codexHasCred;
177
- check(codexMcpOk, "Codex: MCP server configured", codexMcpOk ? void 0 : !codexMcp ? "no [mcp_servers.pushary] \u2014 re-run setup" : !codexTransport ? "entry has no url \u2014 `codex mcp add` likely failed, re-run setup" : "entry has no bearer_token/_env_var \u2014 re-run setup");
175
+ const codexAuth = readCodexMcpAuth(codexParsed);
176
+ const codexMcpOk = !!codexMcp && codexTransport && !!codexAuth;
177
+ check(codexMcpOk, "Codex: MCP server configured", codexMcpOk ? void 0 : !codexMcp ? "no [mcp_servers.pushary] \u2014 re-run setup" : !codexTransport ? "entry has no url \u2014 re-run setup" : "entry has no Authorization header or bearer token \u2014 re-run setup");
178
178
  if (codexMcp) {
179
179
  const hasAutoApprove = codexMcp.default_tools_approval_mode === "approve";
180
180
  check(hasAutoApprove, "Codex: tools auto-allowed", hasAutoApprove ? "default_tools_approval_mode = approve" : "missing \u2014 MCP calls will prompt for approval");
181
181
  if (codexMcp.tools && typeof codexMcp.tools === "object") {
182
182
  console.log(` ${warn} Codex: per-tool approval overrides detected ${dim("(redundant with default_tools_approval_mode)")}`);
183
183
  }
184
- if (codexEnvVar) {
185
- const envValue = process.env[codexEnvVar]?.trim();
186
- check(!!envValue, `Codex: MCP key available in shell ($${codexEnvVar})`, envValue ? "set" : `not set \u2014 Codex reads its key from your shell; the ~/.pushary/config.json fallback only covers hooks. Add the export to your profile or re-run setup`);
184
+ if (codexAuth?.method === "embedded") {
185
+ const keyMatches = !apiKey || codexAuth.key === apiKey;
186
+ check(keyMatches, "Codex: MCP key embedded (config.toml)", keyMatches ? "no shell export needed" : "differs from your active key \u2014 re-run setup");
187
+ } else if (codexAuth?.method === "env") {
188
+ const envValue = process.env[codexAuth.envVar]?.trim();
189
+ const exportedInProfile = SHELL_FILES.some((f) => {
190
+ try {
191
+ return readFileSync(f, "utf-8").includes(`export ${codexAuth.envVar}=`);
192
+ } catch {
193
+ return false;
194
+ }
195
+ });
196
+ check(!!envValue, `Codex: MCP key available in shell ($${codexAuth.envVar})`, envValue ? "set \u2014 re-run setup to embed the key and drop the shell dependency" : exportedInProfile ? "exported in your profile but not in this shell \u2014 restart the terminal, or re-run setup to embed the key in config.toml" : "not set \u2014 Codex reads its key from your shell; re-run setup to embed the key in config.toml");
187
197
  if (envValue && apiKey && envValue !== apiKey) {
188
- console.log(` ${warn} Codex: $${codexEnvVar} differs from your active key ${dim("(rotate or re-run setup so hooks and MCP match)")}`);
198
+ console.log(` ${warn} Codex: $${codexAuth.envVar} differs from your active key ${dim("(rotate or re-run setup so hooks and MCP match)")}`);
189
199
  }
200
+ } else if (codexAuth?.method === "legacy-bearer") {
201
+ console.log(` ${warn} Codex: legacy bearer_token entry ${dim("(re-run setup to embed the key as an Authorization header)")}`);
190
202
  }
191
203
  }
192
204
  const codexNotifyPath = codexConfig.match(/["']([^"']*pushary-codex[^"']*)["']/)?.[1] ?? null;
@@ -24,7 +24,7 @@ import {
24
24
  savePendingQuestion,
25
25
  sendNotification,
26
26
  waitForAnswer
27
- } from "../chunk-GYPPVD3P.js";
27
+ } from "../chunk-A7DQCA2N.js";
28
28
  import "../chunk-DWED7BS3.js";
29
29
  import {
30
30
  getApiKey
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handlePreToolUse
4
- } from "../chunk-O2QL6U6G.js";
4
+ } from "../chunk-SA4BDS7T.js";
5
5
  import "../chunk-KQYIHZ5E.js";
6
- import "../chunk-GYPPVD3P.js";
6
+ import "../chunk-A7DQCA2N.js";
7
7
  import "../chunk-DWED7BS3.js";
8
8
  import "../chunk-NKXSILEW.js";
9
9
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handlePostToolUse
4
- } from "../chunk-GYPPVD3P.js";
4
+ } from "../chunk-A7DQCA2N.js";
5
5
  import "../chunk-DWED7BS3.js";
6
6
  import "../chunk-NKXSILEW.js";
7
7
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handleUserPrompt
4
- } from "../chunk-GYPPVD3P.js";
4
+ } from "../chunk-A7DQCA2N.js";
5
5
  import "../chunk-DWED7BS3.js";
6
6
  import "../chunk-NKXSILEW.js";
7
7
 
@@ -8,6 +8,7 @@ import {
8
8
  GEMINI_HOOK_BINARY,
9
9
  addCodexHookTrust,
10
10
  addCodexHooks,
11
+ addCodexMcpServer,
11
12
  addGeminiHooks,
12
13
  addGeminiMcpServer,
13
14
  execNpm,
@@ -15,11 +16,11 @@ import {
15
16
  renderAgentInstructions,
16
17
  renderProjectAgentInstructions,
17
18
  writeInstructionBlock
18
- } from "../chunk-JPRRYC5X.js";
19
+ } from "../chunk-SLX4AONG.js";
19
20
  import {
20
21
  isValidApiKey,
21
22
  reportEvent
22
- } from "../chunk-GYPPVD3P.js";
23
+ } from "../chunk-A7DQCA2N.js";
23
24
  import "../chunk-DWED7BS3.js";
24
25
  import "../chunk-NKXSILEW.js";
25
26
 
@@ -602,7 +603,7 @@ var addCodexNotifyEntry = (codexConfig) => {
602
603
  writeFileSync(codexConfig, stringifyTOML(config), "utf-8");
603
604
  }
604
605
  };
605
- var setupCodex = async (_apiKey) => {
606
+ var setupCodex = async (apiKey) => {
606
607
  console.log(`
607
608
  ${bold2("Setting up Codex")}
608
609
  `);
@@ -613,28 +614,14 @@ var setupCodex = async (_apiKey) => {
613
614
  }
614
615
  await installGlobally();
615
616
  const codexConfig = join(homedir(), ".codex", "config.toml");
616
- await spinner("Adding Pushary MCP server to Codex", async () => {
617
- try {
618
- execSync(
619
- "codex mcp add pushary --url https://pushary.com/api/mcp/mcp --bearer-token-env-var PUSHARY_API_KEY",
620
- { stdio: "ignore", timeout: 15e3 }
621
- );
622
- } catch {
623
- }
624
- });
625
- await spinner("Auto-allowing all Pushary tools", async () => {
617
+ await spinner("Adding Pushary MCP server (key embedded, auto-allowed)", async () => {
626
618
  let raw = "";
627
619
  try {
628
620
  raw = readFileSync(codexConfig, "utf-8");
629
621
  } catch {
630
622
  }
631
623
  const config = raw ? parseTOML(raw) : {};
632
- const mcpServers = config.mcp_servers ?? {};
633
- const pushary = mcpServers.pushary ?? {};
634
- pushary.default_tools_approval_mode = "approve";
635
- delete pushary.tools;
636
- mcpServers.pushary = pushary;
637
- config.mcp_servers = mcpServers;
624
+ addCodexMcpServer(config, apiKey);
638
625
  writeFileSync(codexConfig, stringifyTOML(config), "utf-8");
639
626
  });
640
627
  const codexVersion = readCodexVersion();
@@ -681,6 +668,7 @@ var setupCodex = async (_apiKey) => {
681
668
  console.log();
682
669
  console.log(` ${dim2("What this configured:")}`);
683
670
  console.log(` ${dim2("\u2022")} MCP server: Codex can send notifications and ask questions`);
671
+ console.log(` ${dim2("\u2022")} API key embedded in config.toml: works without a shell reload or export`);
684
672
  console.log(` ${dim2("\u2022")} Proactive instructions: ~/.codex/AGENTS.md tells Codex to ask via push, not the terminal`);
685
673
  console.log(` ${dim2("\u2022")} Auto-allowed tools: no permission prompts for Pushary MCP calls`);
686
674
  if (hooksSupported) {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  handleStop
4
- } from "../chunk-GYPPVD3P.js";
4
+ } from "../chunk-A7DQCA2N.js";
5
5
  import "../chunk-DWED7BS3.js";
6
6
  import "../chunk-NKXSILEW.js";
7
7
 
@@ -7,7 +7,7 @@ import {
7
7
  getBaseUrl
8
8
  } from "./chunk-NKXSILEW.js";
9
9
 
10
- // ../contracts/src/index.ts
10
+ // ../../../../../packages/contracts/src/index.ts
11
11
  var APPROVAL_MODES = ["push_only", "terminal_only", "push_first", "notify_only"];
12
12
  var isApprovalMode = (value) => typeof value === "string" && APPROVAL_MODES.includes(value);
13
13
  var MATCH_RANKS = ["none", "tool", "prefix", "exact"];
@@ -19,7 +19,7 @@ import {
19
19
  savePendingQuestion,
20
20
  sendNotification,
21
21
  waitForAnswer
22
- } from "./chunk-GYPPVD3P.js";
22
+ } from "./chunk-A7DQCA2N.js";
23
23
  import {
24
24
  getApiKey
25
25
  } from "./chunk-NKXSILEW.js";
@@ -25,6 +25,29 @@ var ensureRecord = (target, key) => {
25
25
  target[key] = created;
26
26
  return created;
27
27
  };
28
+ var CODEX_MCP_URL = "https://pushary.com/api/mcp/mcp";
29
+ var addCodexMcpServer = (config, apiKey) => {
30
+ const servers = ensureRecord(config, "mcp_servers");
31
+ const pushary = ensureRecord(servers, "pushary");
32
+ pushary.url = CODEX_MCP_URL;
33
+ ensureRecord(pushary, "http_headers").Authorization = `Bearer ${apiKey}`;
34
+ pushary.default_tools_approval_mode = "approve";
35
+ delete pushary.bearer_token_env_var;
36
+ delete pushary.tools;
37
+ };
38
+ var readCodexMcpAuth = (config) => {
39
+ const pushary = asRecord(asRecord(config.mcp_servers)?.pushary);
40
+ if (!pushary) return void 0;
41
+ const authorization = asRecord(pushary.http_headers)?.Authorization;
42
+ if (typeof authorization === "string" && authorization.startsWith("Bearer ")) {
43
+ return { method: "embedded", key: authorization.slice("Bearer ".length).trim() };
44
+ }
45
+ if (typeof pushary.bearer_token_env_var === "string") {
46
+ return { method: "env", envVar: pushary.bearer_token_env_var };
47
+ }
48
+ if (typeof pushary.bearer_token === "string") return { method: "legacy-bearer" };
49
+ return void 0;
50
+ };
28
51
  var isPusharyCodexHook = (entry) => {
29
52
  const hooks = asRecord(entry)?.hooks;
30
53
  if (!Array.isArray(hooks)) return false;
@@ -306,6 +329,8 @@ var execNpm = (args, options = {}) => {
306
329
  };
307
330
 
308
331
  export {
332
+ addCodexMcpServer,
333
+ readCodexMcpAuth,
309
334
  addCodexHooks,
310
335
  removeCodexHooks,
311
336
  hasCodexHooks,
package/dist/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  handlePreToolUse
3
- } from "../chunk-O2QL6U6G.js";
3
+ } from "../chunk-SA4BDS7T.js";
4
4
  import "../chunk-KQYIHZ5E.js";
5
5
  import {
6
6
  askUser,
@@ -14,7 +14,7 @@ import {
14
14
  reportEvent,
15
15
  resolvePolicy,
16
16
  waitForAnswer
17
- } from "../chunk-GYPPVD3P.js";
17
+ } from "../chunk-A7DQCA2N.js";
18
18
  import "../chunk-DWED7BS3.js";
19
19
  import {
20
20
  getApiKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/agent-hooks",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Permission hooks for AI coding agents: route tool approvals through Pushary push notifications",
5
5
  "author": "Pushary <business@pushary.com>",
6
6
  "homepage": "https://pushary.com",
@@ -1,38 +0,0 @@
1
- // ../contracts/src/index.ts
2
- var APPROVAL_MODES = ["push_only", "terminal_only", "push_first", "notify_only"];
3
- var isApprovalMode = (value) => typeof value === "string" && APPROVAL_MODES.includes(value);
4
- var MATCH_RANKS = ["none", "tool", "prefix", "exact"];
5
- var matchRankWeight = (rank) => MATCH_RANKS.indexOf(rank);
6
- var matchToolPattern = (pattern, toolName, arg) => {
7
- const open = pattern.indexOf("(");
8
- if (open === -1 || !pattern.endsWith(")")) {
9
- return pattern === toolName ? "tool" : "none";
10
- }
11
- if (pattern.slice(0, open) !== toolName || arg === void 0) return "none";
12
- const inner = pattern.slice(open + 1, -1);
13
- if (inner.endsWith(":*")) {
14
- return arg.startsWith(inner.slice(0, -2)) ? "prefix" : "none";
15
- }
16
- return arg === inner ? "exact" : "none";
17
- };
18
- var POLICY_ARG_KEYS = {
19
- Bash: "command",
20
- Edit: "file_path",
21
- Write: "file_path"
22
- };
23
- var extractPolicyArg = (toolName, toolInput) => {
24
- const key = POLICY_ARG_KEYS[toolName];
25
- if (!key) return void 0;
26
- const value = toolInput[key];
27
- return typeof value === "string" ? value : void 0;
28
- };
29
- var API_KEY_PATTERN = /^pk_[a-f0-9]+\.[a-f0-9]+$/;
30
- var isValidApiKey = (value) => API_KEY_PATTERN.test(value);
31
-
32
- export {
33
- isApprovalMode,
34
- matchRankWeight,
35
- matchToolPattern,
36
- extractPolicyArg,
37
- isValidApiKey
38
- };
@@ -1,315 +0,0 @@
1
- import {
2
- extractPolicyArg,
3
- isApprovalMode,
4
- matchRankWeight,
5
- matchToolPattern
6
- } from "./chunk-RZLVE57X.js";
7
- import {
8
- callMcpTool,
9
- withRetry
10
- } from "./chunk-DWED7BS3.js";
11
- import {
12
- getBaseUrl
13
- } from "./chunk-NKXSILEW.js";
14
-
15
- // src/validate.ts
16
- var isPolicyConfig = (data) => {
17
- if (!data || typeof data !== "object") return false;
18
- const d = data;
19
- return Array.isArray(d.policies) && typeof d.defaultTimeoutSeconds === "number" && typeof d.defaultTimeoutAction === "string";
20
- };
21
- var isAskUserResponse = (data) => {
22
- if (!data || typeof data !== "object") return false;
23
- const d = data;
24
- return typeof d.correlationId === "string" && typeof d.status === "string";
25
- };
26
- var isWaitForAnswerResponse = (data) => {
27
- if (!data || typeof data !== "object") return false;
28
- const d = data;
29
- return typeof d.answered === "boolean";
30
- };
31
-
32
- // src/api.ts
33
- var askUser = async (apiKey, params) => {
34
- const result = await callMcpTool(apiKey, "ask_user", { ...params, wait: false }, { maxRetries: 3 });
35
- if (!isAskUserResponse(result)) throw new Error("Invalid ask_user response");
36
- return result;
37
- };
38
- var waitForAnswer = async (apiKey, correlationId, timeoutMs = 3e4) => {
39
- const result = await callMcpTool(apiKey, "wait_for_answer", {
40
- correlationId,
41
- timeoutMs
42
- });
43
- if (!isWaitForAnswerResponse(result)) throw new Error("Invalid wait_for_answer response");
44
- return result;
45
- };
46
- var cancelQuestion = async (apiKey, correlationId) => {
47
- await callMcpTool(apiKey, "cancel_question", { correlationId });
48
- };
49
- var sendNotification = async (apiKey, params) => {
50
- await callMcpTool(apiKey, "send_notification", { ...params }, { maxRetries: 3 });
51
- };
52
-
53
- // src/policy.ts
54
- import { createHash } from "crypto";
55
- import { existsSync, readFileSync, writeFileSync } from "fs";
56
- import { join } from "path";
57
- import { tmpdir } from "os";
58
- var CACHE_TTL_MS = 60 * 1e3;
59
- var cacheFile = (apiKey) => {
60
- const hash = createHash("sha256").update(apiKey).digest("hex").slice(0, 12);
61
- return join(tmpdir(), `pushary-policy-${hash}.json`);
62
- };
63
- var fetchPolicy = async (apiKey) => {
64
- return withRetry(async () => {
65
- const baseUrl = getBaseUrl();
66
- const response = await fetch(`${baseUrl}/api/mcp/policy`, {
67
- headers: { "Authorization": `Bearer ${apiKey}` },
68
- signal: AbortSignal.timeout(1e4)
69
- });
70
- if (!response.ok) {
71
- throw new Error(`Failed to fetch policy: ${response.status}`);
72
- }
73
- const raw = await response.json();
74
- if (!isPolicyConfig(raw)) throw new Error("Invalid policy response");
75
- return raw;
76
- }, { maxAttempts: 2 });
77
- };
78
- var getPolicy = async (apiKey, expectedVersion) => {
79
- const path = cacheFile(apiKey);
80
- let staleCache = null;
81
- if (existsSync(path)) {
82
- try {
83
- const stat = readFileSync(path, "utf-8");
84
- const cached = JSON.parse(stat);
85
- if (!isPolicyConfig(cached)) throw new Error("Corrupted cache");
86
- const versionStale = expectedVersion != null && (cached._policyVersion ?? null) !== expectedVersion;
87
- const ttlFresh = !cached._cachedAt || Date.now() - cached._cachedAt < CACHE_TTL_MS;
88
- if (ttlFresh && !versionStale) {
89
- return cached;
90
- }
91
- staleCache = cached;
92
- } catch {
93
- }
94
- }
95
- try {
96
- const policy = await fetchPolicy(apiKey);
97
- try {
98
- writeFileSync(path, JSON.stringify({ ...policy, _cachedAt: Date.now(), _policyVersion: expectedVersion ?? null }), "utf-8");
99
- } catch {
100
- }
101
- return policy;
102
- } catch {
103
- if (staleCache) return staleCache;
104
- throw new Error("Failed to fetch policy and no cached policy available");
105
- }
106
- };
107
- var findBestMatch = (policies, toolName, arg) => {
108
- let best;
109
- let bestWeight = 0;
110
- let bestLength = -1;
111
- for (const candidate of policies) {
112
- const rank = matchToolPattern(candidate.tool, toolName, arg);
113
- if (rank === "none") continue;
114
- const weight = matchRankWeight(rank);
115
- const length = rank === "prefix" ? candidate.tool.length : -1;
116
- if (weight > bestWeight || weight === bestWeight && length > bestLength) {
117
- best = candidate;
118
- bestWeight = weight;
119
- bestLength = length;
120
- }
121
- }
122
- return best;
123
- };
124
- var resolvePolicy = (config, toolName, modeOverride, toolInput) => {
125
- const arg = toolInput ? extractPolicyArg(toolName, toolInput) : void 0;
126
- const base = findBestMatch(config.policies, toolName, arg) ?? config.policies.find((p) => p.tool === "*") ?? {
127
- tool: toolName,
128
- timeoutSeconds: config.defaultTimeoutSeconds,
129
- timeoutAction: config.defaultTimeoutAction,
130
- mode: config.defaultMode ?? "push_first",
131
- pushFirstSeconds: config.defaultPushFirstSeconds ?? 20
132
- };
133
- const effectiveOverride = modeOverride ?? config.modeOverride;
134
- if (effectiveOverride) {
135
- return { ...base, mode: effectiveOverride };
136
- }
137
- return base;
138
- };
139
- var toPolicyVersion = (value) => typeof value === "string" || typeof value === "number" ? String(value) : null;
140
- var fetchModeState = async (apiKey, sessionId) => {
141
- try {
142
- const baseUrl = getBaseUrl();
143
- const url = sessionId ? `${baseUrl}/api/mcp/mode?session=${encodeURIComponent(sessionId)}` : `${baseUrl}/api/mcp/mode`;
144
- const response = await fetch(url, {
145
- headers: { "Authorization": `Bearer ${apiKey}` },
146
- signal: AbortSignal.timeout(3e3)
147
- });
148
- if (!response.ok) return { mode: null, kill: false, policyVersion: null };
149
- const data = await response.json();
150
- const mode = data.override?.mode;
151
- return {
152
- mode: isApprovalMode(mode) ? mode : null,
153
- kill: data.kill === true,
154
- policyVersion: toPolicyVersion(data.policyVersion)
155
- };
156
- } catch {
157
- return { mode: null, kill: false, policyVersion: null };
158
- }
159
- };
160
- var fetchModeOverride = async (apiKey) => (await fetchModeState(apiKey)).mode;
161
-
162
- // src/describe.ts
163
- import { isAbsolute, relative } from "path";
164
- var hookPrefixes = {
165
- Bash: (input) => `bash: ${input.command ?? "(no command)"}`,
166
- Write: (input) => `write file: ${input.file_path ?? "(unknown path)"}`,
167
- Edit: (input) => `edit file: ${input.file_path ?? "(unknown path)"}`,
168
- Read: (input) => `read file: ${input.file_path ?? "(unknown path)"}`
169
- };
170
- var eventPrefixes = {
171
- Bash: (input) => `ran: ${String(input.command ?? "").slice(0, 120)}`,
172
- Write: (input) => `wrote: ${input.file_path ?? "unknown"}`,
173
- Edit: (input) => `edited: ${input.file_path ?? "unknown"}`,
174
- Read: (input) => `read: ${input.file_path ?? "unknown"}`
175
- };
176
- var describeToolCall = (toolName, toolInput, format = "hook") => {
177
- const prefixes = format === "hook" ? hookPrefixes : eventPrefixes;
178
- const builder = prefixes[toolName];
179
- if (builder) return builder(toolInput);
180
- return format === "hook" ? `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}` : `${toolName}: done`;
181
- };
182
- var TOOL_TARGET_MAX_LENGTH = 80;
183
- var deriveCommandHead = (command) => {
184
- if (typeof command !== "string") return void 0;
185
- const head = command.trim().split(/\s+/).slice(0, 2).join(" ");
186
- return head ? head.slice(0, TOOL_TARGET_MAX_LENGTH) : void 0;
187
- };
188
- var deriveToolTarget = (toolName, toolInput) => {
189
- if (toolName === "Bash") {
190
- return deriveCommandHead(toolInput.command);
191
- }
192
- if (toolName === "Edit" || toolName === "Write") {
193
- const filePath = toolInput.file_path;
194
- if (typeof filePath !== "string") return void 0;
195
- const separator = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
196
- const base = filePath.slice(separator + 1);
197
- const dot = base.lastIndexOf(".");
198
- if (dot <= 0) return void 0;
199
- return base.slice(dot).slice(0, TOOL_TARGET_MAX_LENGTH);
200
- }
201
- return void 0;
202
- };
203
- var RECEIPT_TARGET_MAX_LENGTH = 256;
204
- var isToolResultError = (toolResult) => {
205
- try {
206
- return Boolean(toolResult && ("error" in toolResult || "is_error" in toolResult));
207
- } catch {
208
- return false;
209
- }
210
- };
211
- var relativizeReceiptPath = (filePath, cwd) => {
212
- if (!cwd || !isAbsolute(filePath)) return filePath;
213
- return relative(cwd, filePath);
214
- };
215
- var deriveReceiptMeta = (toolName, toolInput, toolResult, cwd) => {
216
- try {
217
- const ok = !isToolResultError(toolResult);
218
- if (toolName === "Edit" || toolName === "Write") {
219
- const filePath = toolInput.file_path;
220
- if (typeof filePath !== "string" || !filePath) return void 0;
221
- return {
222
- kind: toolName === "Edit" ? "edit" : "write",
223
- target: relativizeReceiptPath(filePath, cwd).slice(0, RECEIPT_TARGET_MAX_LENGTH),
224
- ok
225
- };
226
- }
227
- if (toolName === "Bash") {
228
- const head = deriveCommandHead(toolInput.command);
229
- if (!head) return void 0;
230
- return {
231
- kind: head === "git commit" ? "commit" : "bash",
232
- target: head,
233
- ok
234
- };
235
- }
236
- return void 0;
237
- } catch {
238
- return void 0;
239
- }
240
- };
241
-
242
- // src/identity.ts
243
- import { createHash as createHash2 } from "crypto";
244
- import { hostname } from "os";
245
- var deriveMachineId = (host) => createHash2("sha256").update(host).digest("hex").slice(0, 8);
246
- var getMachineId = () => deriveMachineId(hostname());
247
-
248
- // src/pending.ts
249
- import { join as join2 } from "path";
250
- import { tmpdir as tmpdir2 } from "os";
251
- import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2, readdirSync, unlinkSync, rmSync, statSync } from "fs";
252
- var PENDING_DIR = join2(tmpdir2(), "pushary-pending");
253
- var DEFAULT_SESSION = "_no_session";
254
- var GRACE_MS = 10 * 60 * 1e3;
255
- var sanitize = (sessionId) => sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || DEFAULT_SESSION;
256
- var dirFor = (sessionId) => join2(PENDING_DIR, sanitize(sessionId));
257
- var isDefaultSession = (sessionId) => sanitize(sessionId) === DEFAULT_SESSION;
258
- var savePendingQuestion = (sessionId, correlationId) => {
259
- const dir = dirFor(sessionId);
260
- if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
261
- writeFileSync2(join2(dir, correlationId), "", "utf-8");
262
- };
263
- var listPendingQuestions = (sessionId) => {
264
- const dir = dirFor(sessionId);
265
- let files;
266
- try {
267
- files = readdirSync(dir);
268
- } catch {
269
- return [];
270
- }
271
- if (!isDefaultSession(sessionId)) return files;
272
- const cutoff = Date.now() - GRACE_MS;
273
- return files.filter((name) => {
274
- try {
275
- return statSync(join2(dir, name)).mtimeMs < cutoff;
276
- } catch {
277
- return false;
278
- }
279
- });
280
- };
281
- var removePendingQuestion = (sessionId, correlationId) => {
282
- try {
283
- unlinkSync(join2(dirFor(sessionId), correlationId));
284
- } catch {
285
- }
286
- };
287
- var removePendingSession = (sessionId) => {
288
- try {
289
- rmSync(dirFor(sessionId), { recursive: true, force: true });
290
- } catch {
291
- }
292
- };
293
-
294
- export {
295
- isPolicyConfig,
296
- askUser,
297
- waitForAnswer,
298
- cancelQuestion,
299
- sendNotification,
300
- getPolicy,
301
- resolvePolicy,
302
- fetchModeState,
303
- fetchModeOverride,
304
- describeToolCall,
305
- deriveToolTarget,
306
- isToolResultError,
307
- deriveReceiptMeta,
308
- getMachineId,
309
- DEFAULT_SESSION,
310
- isDefaultSession,
311
- savePendingQuestion,
312
- listPendingQuestions,
313
- removePendingQuestion,
314
- removePendingSession
315
- };