@pushary/agent-hooks 0.94.0 → 0.95.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 (60) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/data/cursor-plugin/CONTRIBUTING.md +31 -19
  3. package/data/vscode-plugin/CONTRIBUTING.md +31 -19
  4. package/dist/bin/pushary-bell-hook.js +22 -1
  5. package/dist/bin/pushary-bell.js +3 -3
  6. package/dist/bin/pushary-claude.js +335 -357
  7. package/dist/bin/pushary-clean.js +21 -16
  8. package/dist/bin/pushary-codex-bridge.js +6 -6
  9. package/dist/bin/pushary-codex-hook.js +20 -2
  10. package/dist/bin/pushary-codex.js +1 -1
  11. package/dist/bin/pushary-connect.js +3 -3
  12. package/dist/bin/pushary-daemon.js +33 -18
  13. package/dist/bin/pushary-disconnect.js +4 -2
  14. package/dist/bin/pushary-doctor.js +31 -28
  15. package/dist/bin/pushary-elicitation-hook.js +21 -1
  16. package/dist/bin/pushary-gemini-bridge.js +6 -6
  17. package/dist/bin/pushary-gemini-hook.js +20 -2
  18. package/dist/bin/pushary-hook.js +20 -3
  19. package/dist/bin/pushary-login.js +3 -3
  20. package/dist/bin/pushary-logout.js +3 -3
  21. package/dist/bin/pushary-mode.js +3 -3
  22. package/dist/bin/pushary-notification-hook.js +20 -2
  23. package/dist/bin/pushary-opencode-hook.js +20 -2
  24. package/dist/bin/pushary-permission-denied-hook.js +21 -3
  25. package/dist/bin/pushary-permission-hook.js +21 -3
  26. package/dist/bin/pushary-post-hook.js +20 -2
  27. package/dist/bin/pushary-prompt-hook.js +20 -2
  28. package/dist/bin/pushary-session-end-hook.js +24 -3
  29. package/dist/bin/pushary-session-start-hook.js +23 -8
  30. package/dist/bin/pushary-setup.js +47 -41
  31. package/dist/bin/pushary-status.js +3 -3
  32. package/dist/bin/pushary-stop-hook.js +20 -2
  33. package/dist/bin/pushary-stopfailure-hook.js +20 -2
  34. package/dist/bin/pushary-suggestions.js +3 -3
  35. package/dist/bin/pushary-transcript-register.d.ts +1 -0
  36. package/dist/bin/pushary-transcript-register.js +42 -0
  37. package/dist/bin/pushary-transcripts.js +1 -1
  38. package/dist/bin/pushary-upgrade.js +11 -10
  39. package/dist/bin/pushary-wait.js +3 -3
  40. package/dist/{chunk-6WYL3XIP.js → chunk-2WVDQVI5.js} +3 -2
  41. package/dist/{chunk-HSAVPZ46.js → chunk-5SJ54JJO.js} +1 -1
  42. package/dist/{chunk-QKNLW7H6.js → chunk-6LQAGVG2.js} +1 -1
  43. package/dist/{chunk-OB4RF2TF.js → chunk-AYJ7NH5S.js} +1 -1
  44. package/dist/chunk-BMOFXRGS.js +185 -0
  45. package/dist/chunk-FH3YLP5Z.js +194 -0
  46. package/dist/chunk-GHCGSEPE.js +86 -0
  47. package/dist/chunk-GI5UQSG7.js +266 -0
  48. package/dist/{chunk-ZO2XG3CX.js → chunk-LSXJH2HB.js} +1 -1
  49. package/dist/{chunk-YANV5TGK.js → chunk-MDQOBG5J.js} +1 -84
  50. package/dist/chunk-N6FAXQDD.js +276 -0
  51. package/dist/{chunk-5HGLZGI4.js → chunk-OXTRFRMD.js} +1 -0
  52. package/dist/chunk-PQ4K74WL.js +30 -0
  53. package/dist/{chunk-46P3VES5.js → chunk-Q5UFC2QK.js} +1 -0
  54. package/dist/{chunk-36LR2LOT.js → chunk-SFCGKE6U.js} +8 -6
  55. package/dist/{chunk-6CUUA7HO.js → chunk-XY4GSZ3K.js} +7 -1
  56. package/dist/chunk-YGZXYEVY.js +503 -0
  57. package/dist/src/index.js +5 -5
  58. package/package.json +3 -2
  59. package/dist/chunk-FYOIW5RV.js +0 -539
  60. package/dist/chunk-RX75MRGC.js +0 -368
@@ -1,539 +0,0 @@
1
- import {
2
- isBridgeLocator
3
- } from "./chunk-YANV5TGK.js";
4
- import {
5
- pusharyHookExecutable
6
- } from "./chunk-HSAVPZ46.js";
7
- import {
8
- BELL_HOOK_BINARY
9
- } from "./chunk-DSTLA2TC.js";
10
- import {
11
- resolvePathBinary
12
- } from "./chunk-L4ZCFMWW.js";
13
- import {
14
- parseFlags
15
- } from "./chunk-GMXKITVA.js";
16
- import {
17
- UsageError
18
- } from "./chunk-7QLSKOSU.js";
19
- import {
20
- isValidApiKey
21
- } from "./chunk-Z6CP5ZZD.js";
22
-
23
- // src/hermes-config.ts
24
- import { execFileSync } from "child_process";
25
- import { existsSync, readFileSync, rmSync, writeFileSync } from "fs";
26
- import { homedir, tmpdir } from "os";
27
- import { join } from "path";
28
- var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
29
- var isSnapshot = (value) => isRecord(value) && typeof value.present === "boolean" && Object.hasOwn(value, "value");
30
- var isHermesConfigReceipt = (value) => {
31
- if (!isRecord(value)) return false;
32
- return ["security", "approval", "transport", "fallback", "plugins", "enabled", "agent", "disabled"].every((key) => isSnapshot(value[key])) && typeof value.pushary_enabled === "boolean" && typeof value.clarify_disabled === "boolean";
33
- };
34
- var HERMES_PIP_PACKAGE = "hermes-plugin-pushary";
35
- var HERMES_CONFIG_SCRIPT = String.raw`
36
- import json, os, sys
37
- from hermes_cli.config import load_config, save_config
38
-
39
- mode, receipt_path = sys.argv[1], sys.argv[2]
40
- c = load_config()
41
-
42
- def snap(obj, key):
43
- return {"present": key in obj, "value": obj.get(key)}
44
-
45
- restore_conflicts = []
46
-
47
- def restore(obj, key, before, ours):
48
- if before.get("present") and before.get("value") == ours:
49
- return
50
- if before.get("present"):
51
- if key in obj and obj.get(key) == before.get("value"):
52
- return
53
- elif key not in obj:
54
- return
55
- if obj.get(key) != ours:
56
- restore_conflicts.append(key)
57
- return
58
- if before.get("present"):
59
- obj[key] = before.get("value")
60
- else:
61
- obj.pop(key, None)
62
-
63
- def restore_container(obj, key, before, current, changed):
64
- raw = obj.get(key)
65
- if isinstance(before.get("value"), dict):
66
- if not isinstance(raw, dict):
67
- if changed:
68
- restore_conflicts.append(key)
69
- return
70
- if current or before.get("present"):
71
- obj[key] = current
72
- else:
73
- obj.pop(key, None)
74
- elif isinstance(raw, dict) and current:
75
- restore_conflicts.append(key)
76
- else:
77
- restore(obj, key, before, {})
78
-
79
- def restore_list_member(obj, key, before, ours, ours_before):
80
- raw = obj.get(key)
81
- if isinstance(before.get("value"), list):
82
- if ours_before:
83
- return
84
- if not isinstance(raw, list):
85
- restore_conflicts.append(key)
86
- return
87
- remaining = [item for item in raw if item != ours]
88
- if remaining or before.get("present"):
89
- obj[key] = remaining
90
- else:
91
- obj.pop(key, None)
92
- return
93
- if before.get("present") and raw == before.get("value"):
94
- return
95
- if not before.get("present") and key not in obj:
96
- return
97
- if not isinstance(raw, list):
98
- restore_conflicts.append(key)
99
- return
100
- remaining = [item for item in raw if item != ours]
101
- if remaining:
102
- restore_conflicts.append(key)
103
- else:
104
- restore(obj, key, before, raw)
105
-
106
- def valid_snapshot(value):
107
- return isinstance(value, dict) and isinstance(value.get("present"), bool) and "value" in value
108
-
109
- def valid_receipt(value):
110
- snapshots = ["security", "approval", "transport", "fallback", "plugins", "enabled", "agent", "disabled"]
111
- return (isinstance(value, dict)
112
- and all(valid_snapshot(value.get(key)) for key in snapshots)
113
- and isinstance(value.get("pushary_enabled"), bool)
114
- and isinstance(value.get("clarify_disabled"), bool))
115
-
116
- if mode == "setup":
117
- security_before = snap(c, "security")
118
- s = c.get("security") if isinstance(c.get("security"), dict) else {}
119
- approval_before = snap(s, "approval")
120
- ap = s.get("approval") if isinstance(s.get("approval"), dict) else {}
121
- plugins_before = snap(c, "plugins")
122
- p = c.get("plugins") if isinstance(c.get("plugins"), dict) else {}
123
- agent_before = snap(c, "agent")
124
- a = c.get("agent") if isinstance(c.get("agent"), dict) else {}
125
- enabled = p.get("enabled") if isinstance(p.get("enabled"), list) else []
126
- disabled = a.get("disabled_toolsets") if isinstance(a.get("disabled_toolsets"), list) else []
127
- receipt = {
128
- "security": security_before,
129
- "approval": approval_before,
130
- "transport": snap(ap, "transport"),
131
- "fallback": snap(ap, "transport_fallback"),
132
- "plugins": plugins_before,
133
- "enabled": snap(p, "enabled"),
134
- "pushary_enabled": "pushary" in enabled,
135
- "agent": agent_before,
136
- "disabled": snap(a, "disabled_toolsets"),
137
- "clarify_disabled": "clarify" in disabled,
138
- }
139
- if os.path.exists(receipt_path):
140
- with open(receipt_path, encoding="utf-8") as handle:
141
- existing_receipt = json.load(handle)
142
- if not valid_receipt(existing_receipt):
143
- raise ValueError("invalid Pushary Hermes setup receipt")
144
- else:
145
- os.makedirs(os.path.dirname(receipt_path), exist_ok=True)
146
- temp = receipt_path + ".tmp"
147
- with open(temp, "x", encoding="utf-8") as handle:
148
- json.dump(receipt, handle)
149
- os.chmod(temp, 0o600)
150
- os.replace(temp, receipt_path)
151
- ap["transport"] = "pushary"
152
- ap["transport_fallback"] = "builtin"
153
- s["approval"] = ap
154
- c["security"] = s
155
- p["enabled"] = enabled if "pushary" in enabled else enabled + ["pushary"]
156
- c["plugins"] = p
157
- a["disabled_toolsets"] = disabled if "clarify" in disabled else disabled + ["clarify"]
158
- c["agent"] = a
159
- else:
160
- receipt_exists = os.path.exists(receipt_path)
161
- try:
162
- with open(receipt_path, encoding="utf-8") as handle:
163
- receipt = json.load(handle)
164
- except (OSError, ValueError):
165
- if receipt_exists:
166
- raise
167
- receipt = None
168
- s = c.get("security") if isinstance(c.get("security"), dict) else {}
169
- ap = s.get("approval") if isinstance(s.get("approval"), dict) else {}
170
- if receipt:
171
- if not valid_receipt(receipt):
172
- raise ValueError("invalid Pushary Hermes setup receipt")
173
- approval_changed = (not receipt["transport"].get("present")
174
- or receipt["transport"].get("value") != "pushary"
175
- or not receipt["fallback"].get("present")
176
- or receipt["fallback"].get("value") != "builtin")
177
- plugins_changed = not (isinstance(receipt["enabled"].get("value"), list)
178
- and receipt["pushary_enabled"])
179
- agent_changed = not (isinstance(receipt["disabled"].get("value"), list)
180
- and receipt["clarify_disabled"])
181
- restore(ap, "transport", receipt["transport"], "pushary")
182
- restore(ap, "transport_fallback", receipt["fallback"], "builtin")
183
- else:
184
- if ap.get("transport") == "pushary": ap.pop("transport", None)
185
- if ap.get("transport_fallback") == "builtin": ap.pop("transport_fallback", None)
186
- if receipt:
187
- restore_container(s, "approval", receipt["approval"], ap, approval_changed)
188
- restore_container(c, "security", receipt["security"], s, approval_changed)
189
- else:
190
- if ap: s["approval"] = ap
191
- else: s.pop("approval", None)
192
- if s: c["security"] = s
193
- else: c.pop("security", None)
194
-
195
- p = c.get("plugins") if isinstance(c.get("plugins"), dict) else {}
196
- if receipt:
197
- restore_list_member(p, "enabled", receipt["enabled"], "pushary", receipt["pushary_enabled"])
198
- restore_container(c, "plugins", receipt["plugins"], p, plugins_changed)
199
- else:
200
- enabled = p.get("enabled") if isinstance(p.get("enabled"), list) else []
201
- enabled = [item for item in enabled if item != "pushary"]
202
- if enabled: p["enabled"] = enabled
203
- else: p.pop("enabled", None)
204
- if p: c["plugins"] = p
205
- else: c.pop("plugins", None)
206
-
207
- a = c.get("agent") if isinstance(c.get("agent"), dict) else {}
208
- if receipt:
209
- restore_list_member(a, "disabled_toolsets", receipt["disabled"], "clarify", receipt["clarify_disabled"])
210
- restore_container(c, "agent", receipt["agent"], a, agent_changed)
211
- else:
212
- disabled = a.get("disabled_toolsets") if isinstance(a.get("disabled_toolsets"), list) else []
213
- disabled = [item for item in disabled if item != "clarify"]
214
- if disabled: a["disabled_toolsets"] = disabled
215
- else: a.pop("disabled_toolsets", None)
216
- if a: c["agent"] = a
217
- else: c.pop("agent", None)
218
-
219
- if receipt and restore_conflicts:
220
- raise ValueError("Hermes config changed after Pushary setup")
221
-
222
- save_config(c)
223
- `;
224
- var resolveHermesPython = () => {
225
- const launcher = resolvePathBinary("hermes");
226
- if (launcher && process.platform !== "win32") {
227
- try {
228
- const shebang = readFileSync(launcher, "utf-8").split("\n", 1)[0];
229
- const interpreter = shebang?.startsWith("#!") ? shebang.slice(2).trim().split(/\s+/)[0] : void 0;
230
- if (interpreter && /python/i.test(interpreter) && existsSync(interpreter)) return interpreter;
231
- } catch {
232
- }
233
- }
234
- const root = join(homedir(), ".hermes", "hermes-agent", "venv");
235
- const candidates = process.platform === "win32" ? [join(root, "Scripts", "python.exe"), join(root, "Scripts", "python3.exe")] : [join(root, "bin", "python3"), join(root, "bin", "python")];
236
- return candidates.find(existsSync) ?? null;
237
- };
238
- var runHermesPythonScript = (python, script, ...args) => {
239
- const path = join(tmpdir(), `pushary-hermes-${process.pid}-${Date.now()}.py`);
240
- try {
241
- writeFileSync(path, script, { encoding: "utf-8", mode: 384 });
242
- execFileSync(python, [path, ...args], { env: { ...process.env }, stdio: "pipe", timeout: 15e3 });
243
- return true;
244
- } catch {
245
- return false;
246
- } finally {
247
- try {
248
- rmSync(path, { force: true });
249
- } catch {
250
- }
251
- }
252
- };
253
-
254
- // src/cli/dry-run.ts
255
- import { execSync } from "child_process";
256
- import { rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
257
- var createGuards = (isDryRun, note) => ({
258
- write: (path, contents) => {
259
- if (isDryRun()) return note("rewrite", path);
260
- writeFileSync2(path, contents, "utf-8");
261
- },
262
- remove: (path, options = {}) => {
263
- if (isDryRun()) return note("remove ", path);
264
- rmSync2(path, { recursive: true, force: options.force ?? false });
265
- },
266
- exec: (command, options, describe) => {
267
- if (isDryRun()) return note("run ", describe);
268
- execSync(command, options);
269
- }
270
- });
271
- var describeService = (effects) => {
272
- if (effects.controlMode === "off") return "skip the phone-start background service (--control off)";
273
- const where = effects.serviceDefinitionPath ?? "the phone-start service definition";
274
- const condition = effects.controlMode === "on" ? "" : ", when a supported agent and a service manager are present";
275
- return `write ${where} and register it with the OS${condition}`;
276
- };
277
- var describeSetupSideEffects = (effects) => [
278
- `run npm install -g @pushary/agent-hooks@${effects.version} (the hooks run from the global copy; up to two minutes)`,
279
- `write ${effects.configFile} (the API key, mode 600)`,
280
- effects.rcPath ? `edit ${effects.rcPath} (export PUSHARY_API_KEY)` : "print the export line for your shell, since no rc file was found",
281
- describeService(effects),
282
- "ask Add Pushary instructions to this project's CLAUDE.md/AGENTS.md? (default no)",
283
- "ask Alias claude to pushary claude? (default no)"
284
- ];
285
-
286
- // src/setup/options.ts
287
- var AGENT_CHOICES = ["claude_code", "codex", "gemini_cli", "hermes", "cursor", "vscode", "opencode", "custom"];
288
- var CONNECT_MODES = ["app", "browser", "web", "none"];
289
- var CONNECT_ALIASES = { auto: "app", pwa: "web" };
290
- var parseConnectMode = (raw) => {
291
- const value = raw.trim().toLowerCase();
292
- if (Object.hasOwn(CONNECT_ALIASES, value)) return CONNECT_ALIASES[value];
293
- if (CONNECT_MODES.includes(value)) return value;
294
- throw new UsageError(`--connect must be one of: ${CONNECT_MODES.join(", ")} (got ${raw})`);
295
- };
296
- var VERIFY_MODES = ["roundtrip", "push", "none"];
297
- var parseVerifyMode = (raw) => {
298
- const value = raw.trim().toLowerCase();
299
- if (VERIFY_MODES.includes(value)) return value;
300
- throw new UsageError(`--verify must be one of: ${VERIFY_MODES.join(", ")} (got ${raw})`);
301
- };
302
- var CONTROL_MODES = ["auto", "on", "off"];
303
- var parseControlMode = (raw) => {
304
- const value = raw.trim().toLowerCase();
305
- if (CONTROL_MODES.includes(value)) return value;
306
- throw new UsageError(`--control must be one of: ${CONTROL_MODES.join(", ")} (got ${raw})`);
307
- };
308
- var effectiveVerify = (options, context) => {
309
- if (options.verifyExplicit) return options.verify;
310
- if (options.verify === "roundtrip") return "roundtrip";
311
- return context.paired ? "roundtrip" : options.verify;
312
- };
313
- var SETUP_FLAGS = {
314
- bools: ["key-stdin", "skip-phone", "yes", "y", "json", "dry-run", "take-over-hooks", "help", "h"],
315
- values: ["key", "connect", "agents", "verify", "control", "transcripts"]
316
- };
317
- var effectiveControlMode = (options, stored, configPresent) => options.controlExplicit ? options.control : stored ?? (configPresent ? null : options.control);
318
- var isAgentChoice = (value) => AGENT_CHOICES.includes(value);
319
- var parseAgentSelection = (raw, yes) => {
320
- if (raw === void 0) {
321
- return yes ? { kind: "auto" } : { kind: "ask" };
322
- }
323
- const value = raw.trim().toLowerCase();
324
- if (value === "auto") return { kind: "auto" };
325
- if (value === "none") return { kind: "none" };
326
- const parts = value.split(",").map((part) => part.trim()).filter((part) => part !== "");
327
- if (parts.length === 0) throw new UsageError("--agents needs a value");
328
- const unknown = parts.filter((part) => !isAgentChoice(part));
329
- if (unknown.length > 0) {
330
- throw new UsageError(
331
- `--agents does not know: ${unknown.join(", ")}. Use auto, none, or any of: ${AGENT_CHOICES.join(", ")}`
332
- );
333
- }
334
- return { kind: "explicit", agents: [...new Set(parts)] };
335
- };
336
- var parseSetupOptions = (input) => {
337
- const flags = parseFlags(input.argv, SETUP_FLAGS);
338
- const stray = [
339
- ...flags.command !== void 0 && flags.command !== "setup" ? [flags.command] : [],
340
- ...flags.rest
341
- ];
342
- if (stray.length > 0) {
343
- throw new UsageError(
344
- `setup takes no positional arguments (got ${stray.join(", ")}). Did you mean --agents ${stray[0]}?`
345
- );
346
- }
347
- const yes = flags.bools.has("yes") || flags.bools.has("y");
348
- const help = flags.bools.has("help") || flags.bools.has("h");
349
- const agentsFlag = flags.values.get("agents");
350
- const agents = parseAgentSelection(agentsFlag, yes);
351
- const connectRaw = flags.values.get("connect");
352
- const connectMode = connectRaw === void 0 ? "app" : parseConnectMode(connectRaw);
353
- const verifyRaw = flags.values.get("verify");
354
- const controlRaw = flags.values.get("control");
355
- const transcriptsRaw = flags.values.get("transcripts")?.trim().toLowerCase();
356
- if (transcriptsRaw !== void 0 && transcriptsRaw !== "on" && transcriptsRaw !== "off") {
357
- throw new UsageError(`--transcripts must be one of: on, off (got ${transcriptsRaw})`);
358
- }
359
- const nonInteractive = yes || agentsFlag !== void 0 || flags.bools.has("json") || !input.stdinIsTty;
360
- const verify = verifyRaw !== void 0 ? parseVerifyMode(verifyRaw) : nonInteractive ? "push" : "roundtrip";
361
- const key = flags.values.get("key")?.trim() || null;
362
- const keyStdin = flags.bools.has("key-stdin");
363
- if (key && keyStdin) {
364
- throw new UsageError("Pass either --key or --key-stdin, not both");
365
- }
366
- if (key && !isValidApiKey(key)) {
367
- throw new UsageError("--key is not a valid API key. Expected the pk_xxx.xxx shape from pushary.com/dashboard/agent/settings");
368
- }
369
- return {
370
- connectMode,
371
- connectExplicit: connectRaw !== void 0,
372
- // `--connect none` and `--skip-phone` are the same instruction, so they
373
- // resolve to the same field rather than being checked separately at the two
374
- // call sites that would inevitably drift apart.
375
- skipPhone: flags.bools.has("skip-phone") || connectMode === "none",
376
- // Anything that means "there is nobody to answer a prompt". A non-TTY stdin
377
- // is included because that is the case that used to hang: it is better to
378
- // take the defaults and say so than to wait forever for a keypress.
379
- //
380
- // --json counts. Under it stdout carries exactly one object and every human
381
- // line is redirected to stderr, so a prompt has nowhere to render: the
382
- // question goes to stderr while the run blocks on a keypress the caller
383
- // cannot see it is waiting for, and whatever is reading stdout waits forever
384
- // for an object that never arrives. Asking for machine-readable output is
385
- // itself a statement that no human is watching.
386
- nonInteractive,
387
- json: flags.bools.has("json"),
388
- dryRun: flags.bools.has("dry-run"),
389
- help,
390
- agents,
391
- key,
392
- keyStdin,
393
- verify,
394
- verifyExplicit: verifyRaw !== void 0,
395
- control: controlRaw === void 0 ? "auto" : parseControlMode(controlRaw),
396
- controlExplicit: controlRaw !== void 0,
397
- transcripts: transcriptsRaw === void 0 ? null : transcriptsRaw === "on",
398
- takeOverHooks: flags.bools.has("take-over-hooks")
399
- };
400
- };
401
-
402
- // src/setup/hook-ownership.ts
403
- var commandsIn = (value) => {
404
- if (Array.isArray(value)) return value.flatMap(commandsIn);
405
- if (!value || typeof value !== "object") return [];
406
- return Object.entries(value).flatMap(([key, item]) => key === "command" && typeof item === "string" ? [item] : commandsIn(item));
407
- };
408
- var isRecord2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
409
- var hasPaidPusharyCommand = (value) => commandsIn(value).some((command) => {
410
- const executable = pusharyHookExecutable(command);
411
- const name = executable?.split(/[/\\]/).pop()?.replace(/\.(cmd|exe|mjs)$/i, "");
412
- return executable !== null && !isBridgeLocator(executable) && name !== BELL_HOOK_BINARY;
413
- });
414
- var hasAppCommand = (value) => commandsIn(value).some((command) => {
415
- const executable = pusharyHookExecutable(command);
416
- return executable !== null && isBridgeLocator(executable);
417
- });
418
- var mcpBearerKey = (document, containerKey, headersKey) => {
419
- const servers = isRecord2(document?.[containerKey]) ? document[containerKey] : null;
420
- const pushary = isRecord2(servers?.pushary) ? servers.pushary : null;
421
- const headers = isRecord2(pushary?.[headersKey]) ? pushary[headersKey] : null;
422
- const authorization = headers?.Authorization;
423
- const match = typeof authorization === "string" ? authorization.trim().match(/^Bearer\s+(\S+)$/) : null;
424
- return match?.[1] ?? null;
425
- };
426
- var captureMcpServer = (document, containerKey) => {
427
- const container = document[containerKey];
428
- const servers = isRecord2(container) ? container : null;
429
- if (!servers && Object.hasOwn(document, containerKey)) {
430
- return { present: false, containerValue: structuredClone(container) };
431
- }
432
- return servers && Object.hasOwn(servers, "pushary") ? { present: true, value: structuredClone(servers.pushary) } : { present: false };
433
- };
434
- var restoreMcpServer = (document, containerKey, snapshot) => {
435
- const before = JSON.stringify(document);
436
- const existing = isRecord2(document[containerKey]) ? document[containerKey] : null;
437
- if (snapshot.present) {
438
- const servers = existing ?? {};
439
- servers.pushary = structuredClone(snapshot.value);
440
- document[containerKey] = servers;
441
- } else if (Object.hasOwn(snapshot, "containerValue")) {
442
- document[containerKey] = structuredClone(snapshot.containerValue);
443
- } else if (existing && Object.hasOwn(existing, "pushary")) {
444
- delete existing.pushary;
445
- if (Object.keys(existing).length === 0) delete document[containerKey];
446
- }
447
- return JSON.stringify(document) !== before;
448
- };
449
- var captureHookTakeover = (agent, document) => {
450
- const hooks = isRecord2(document?.hooks) ? document.hooks : null;
451
- if (!hooks) return null;
452
- const captured = {};
453
- for (const [event, entries] of Object.entries(hooks)) {
454
- if (!Array.isArray(entries)) continue;
455
- const appEntries = entries.flatMap((value, index) => isRecord2(value) && hasAppCommand(value) ? [{ index, value: structuredClone(value) }] : []);
456
- if (appEntries.length > 0) captured[event] = appEntries;
457
- }
458
- return Object.keys(captured).length > 0 ? { version: 1, agent, hooks: captured } : null;
459
- };
460
- var isHookTakeoverReceipt = (value) => {
461
- if (!isRecord2(value) || value.version !== 1 || typeof value.agent !== "string" || !AGENT_CHOICES.includes(value.agent) || !isRecord2(value.hooks)) return false;
462
- const expectsMcp = ["claude_code", "codex", "gemini_cli", "vscode"].includes(value.agent);
463
- if (value.mcpServer !== void 0 !== expectsMcp) return false;
464
- if (value.codexTrust !== void 0 !== (value.agent === "codex")) return false;
465
- if (value.codexTrust !== void 0 && !isRecord2(value.codexTrust)) return false;
466
- if (value.mcpServer !== void 0 && (!isRecord2(value.mcpServer) || typeof value.mcpServer.present !== "boolean" || value.mcpServer.present && !Object.hasOwn(value.mcpServer, "value"))) return false;
467
- return Object.values(value.hooks).every((entries) => Array.isArray(entries) && entries.length > 0 && entries.every((item) => isRecord2(item) && Number.isInteger(item.index) && item.index >= 0 && isRecord2(item.value)));
468
- };
469
- var restoreHookTakeover = (document, receipt) => {
470
- const before = JSON.stringify(document);
471
- const appOwnsNow = hookOwnerOf(document) === "app";
472
- const hooks = isRecord2(document.hooks) ? document.hooks : {};
473
- for (const [event, value] of Object.entries(hooks)) {
474
- if (!Array.isArray(value)) continue;
475
- const kept = value.filter((entry) => !hasPaidPusharyCommand(entry));
476
- if (kept.length === 0) delete hooks[event];
477
- else hooks[event] = kept;
478
- }
479
- if (!appOwnsNow) {
480
- for (const [event, snapshots] of Object.entries(receipt.hooks)) {
481
- const entries = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
482
- for (const snapshot of snapshots) {
483
- entries.splice(Math.min(snapshot.index, entries.length), 0, structuredClone(snapshot.value));
484
- }
485
- hooks[event] = entries;
486
- }
487
- }
488
- document.hooks = hooks;
489
- return JSON.stringify(document) !== before;
490
- };
491
- var hookOwnerOf = (document, appAvailable = true) => {
492
- const hooks = document && typeof document === "object" ? document.hooks : void 0;
493
- const executables = commandsIn(hooks).map(pusharyHookExecutable).filter((executable) => executable !== null);
494
- if (appAvailable && executables.some(isBridgeLocator)) return "app";
495
- if (executables.some((executable) => !isBridgeLocator(executable))) return "cli";
496
- return "none";
497
- };
498
- var planHooks = (context) => {
499
- if (context.owner !== "app") return "install";
500
- if (context.takeOverHooks) return "install";
501
- return "keep";
502
- };
503
- var describeAppOwnership = (agentName) => `The Pushary Mac app owns ${agentName}'s hooks.`;
504
- var KEEP_HINT = "Kept with the app's account. Pass --take-over-hooks to have the CLI own them instead.";
505
- var OWNER_LABELS = {
506
- app: "the Pushary Mac app",
507
- cli: "the CLI"
508
- };
509
- var describeHookOwnership = (entries, names) => {
510
- const owned = entries.filter((entry) => entry.owner !== "none");
511
- if (owned.length === 0) return null;
512
- const parts = owned.map((entry) => `${names[entry.agent]} by ${OWNER_LABELS[entry.owner]}${entry.kept ? " (kept)" : ""}`);
513
- return `Hooks: ${parts.join(", ")}.`;
514
- };
515
-
516
- export {
517
- isHermesConfigReceipt,
518
- HERMES_PIP_PACKAGE,
519
- HERMES_CONFIG_SCRIPT,
520
- resolveHermesPython,
521
- runHermesPythonScript,
522
- createGuards,
523
- describeSetupSideEffects,
524
- AGENT_CHOICES,
525
- effectiveVerify,
526
- effectiveControlMode,
527
- parseSetupOptions,
528
- mcpBearerKey,
529
- captureMcpServer,
530
- restoreMcpServer,
531
- captureHookTakeover,
532
- isHookTakeoverReceipt,
533
- restoreHookTakeover,
534
- hookOwnerOf,
535
- planHooks,
536
- describeAppOwnership,
537
- KEEP_HINT,
538
- describeHookOwnership
539
- };