@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
@@ -0,0 +1,266 @@
1
+ import {
2
+ isBridgeLocator
3
+ } from "./chunk-GHCGSEPE.js";
4
+ import {
5
+ pusharyHookExecutable
6
+ } from "./chunk-5SJ54JJO.js";
7
+ import {
8
+ BELL_HOOK_BINARY
9
+ } from "./chunk-DSTLA2TC.js";
10
+ import {
11
+ parseFlags
12
+ } from "./chunk-GMXKITVA.js";
13
+ import {
14
+ UsageError
15
+ } from "./chunk-7QLSKOSU.js";
16
+ import {
17
+ isValidApiKey
18
+ } from "./chunk-Z6CP5ZZD.js";
19
+
20
+ // src/setup/options.ts
21
+ var AGENT_CHOICES = ["claude_code", "codex", "gemini_cli", "hermes", "cursor", "vscode", "opencode", "custom"];
22
+ var CONNECT_MODES = ["app", "browser", "web", "none"];
23
+ var CONNECT_ALIASES = { auto: "app", pwa: "web" };
24
+ var parseConnectMode = (raw) => {
25
+ const value = raw.trim().toLowerCase();
26
+ if (Object.hasOwn(CONNECT_ALIASES, value)) return CONNECT_ALIASES[value];
27
+ if (CONNECT_MODES.includes(value)) return value;
28
+ throw new UsageError(`--connect must be one of: ${CONNECT_MODES.join(", ")} (got ${raw})`);
29
+ };
30
+ var VERIFY_MODES = ["roundtrip", "push", "none"];
31
+ var parseVerifyMode = (raw) => {
32
+ const value = raw.trim().toLowerCase();
33
+ if (VERIFY_MODES.includes(value)) return value;
34
+ throw new UsageError(`--verify must be one of: ${VERIFY_MODES.join(", ")} (got ${raw})`);
35
+ };
36
+ var CONTROL_MODES = ["auto", "on", "off"];
37
+ var parseControlMode = (raw) => {
38
+ const value = raw.trim().toLowerCase();
39
+ if (CONTROL_MODES.includes(value)) return value;
40
+ throw new UsageError(`--control must be one of: ${CONTROL_MODES.join(", ")} (got ${raw})`);
41
+ };
42
+ var effectiveVerify = (options, context) => {
43
+ if (options.verifyExplicit) return options.verify;
44
+ if (options.verify === "roundtrip") return "roundtrip";
45
+ return context.paired ? "roundtrip" : options.verify;
46
+ };
47
+ var SETUP_FLAGS = {
48
+ bools: ["key-stdin", "skip-phone", "yes", "y", "json", "dry-run", "take-over-hooks", "help", "h"],
49
+ values: ["key", "connect", "agents", "verify", "control", "transcripts"]
50
+ };
51
+ var effectiveControlMode = (options, stored, configPresent) => options.controlExplicit ? options.control : stored ?? (configPresent ? null : options.control);
52
+ var isAgentChoice = (value) => AGENT_CHOICES.includes(value);
53
+ var parseAgentSelection = (raw, yes) => {
54
+ if (raw === void 0) {
55
+ return yes ? { kind: "auto" } : { kind: "ask" };
56
+ }
57
+ const value = raw.trim().toLowerCase();
58
+ if (value === "auto") return { kind: "auto" };
59
+ if (value === "none") return { kind: "none" };
60
+ const parts = value.split(",").map((part) => part.trim()).filter((part) => part !== "");
61
+ if (parts.length === 0) throw new UsageError("--agents needs a value");
62
+ const unknown = parts.filter((part) => !isAgentChoice(part));
63
+ if (unknown.length > 0) {
64
+ throw new UsageError(
65
+ `--agents does not know: ${unknown.join(", ")}. Use auto, none, or any of: ${AGENT_CHOICES.join(", ")}`
66
+ );
67
+ }
68
+ return { kind: "explicit", agents: [...new Set(parts)] };
69
+ };
70
+ var parseSetupOptions = (input) => {
71
+ const flags = parseFlags(input.argv, SETUP_FLAGS);
72
+ const stray = [
73
+ ...flags.command !== void 0 && flags.command !== "setup" ? [flags.command] : [],
74
+ ...flags.rest
75
+ ];
76
+ if (stray.length > 0) {
77
+ throw new UsageError(
78
+ `setup takes no positional arguments (got ${stray.join(", ")}). Did you mean --agents ${stray[0]}?`
79
+ );
80
+ }
81
+ const yes = flags.bools.has("yes") || flags.bools.has("y");
82
+ const help = flags.bools.has("help") || flags.bools.has("h");
83
+ const agentsFlag = flags.values.get("agents");
84
+ const agents = parseAgentSelection(agentsFlag, yes);
85
+ const connectRaw = flags.values.get("connect");
86
+ const connectMode = connectRaw === void 0 ? "app" : parseConnectMode(connectRaw);
87
+ const verifyRaw = flags.values.get("verify");
88
+ const controlRaw = flags.values.get("control");
89
+ const transcriptsRaw = flags.values.get("transcripts")?.trim().toLowerCase();
90
+ if (transcriptsRaw !== void 0 && transcriptsRaw !== "on" && transcriptsRaw !== "off") {
91
+ throw new UsageError(`--transcripts must be one of: on, off (got ${transcriptsRaw})`);
92
+ }
93
+ const nonInteractive = yes || agentsFlag !== void 0 || flags.bools.has("json") || !input.stdinIsTty;
94
+ const verify = verifyRaw !== void 0 ? parseVerifyMode(verifyRaw) : nonInteractive ? "push" : "roundtrip";
95
+ const key = flags.values.get("key")?.trim() || null;
96
+ const keyStdin = flags.bools.has("key-stdin");
97
+ if (key && keyStdin) {
98
+ throw new UsageError("Pass either --key or --key-stdin, not both");
99
+ }
100
+ if (key && !isValidApiKey(key)) {
101
+ throw new UsageError("--key is not a valid API key. Expected the pk_xxx.xxx shape from pushary.com/dashboard/agent/settings");
102
+ }
103
+ return {
104
+ connectMode,
105
+ connectExplicit: connectRaw !== void 0,
106
+ // `--connect none` and `--skip-phone` are the same instruction, so they
107
+ // resolve to the same field rather than being checked separately at the two
108
+ // call sites that would inevitably drift apart.
109
+ skipPhone: flags.bools.has("skip-phone") || connectMode === "none",
110
+ // Anything that means "there is nobody to answer a prompt". A non-TTY stdin
111
+ // is included because that is the case that used to hang: it is better to
112
+ // take the defaults and say so than to wait forever for a keypress.
113
+ //
114
+ // --json counts. Under it stdout carries exactly one object and every human
115
+ // line is redirected to stderr, so a prompt has nowhere to render: the
116
+ // question goes to stderr while the run blocks on a keypress the caller
117
+ // cannot see it is waiting for, and whatever is reading stdout waits forever
118
+ // for an object that never arrives. Asking for machine-readable output is
119
+ // itself a statement that no human is watching.
120
+ nonInteractive,
121
+ json: flags.bools.has("json"),
122
+ dryRun: flags.bools.has("dry-run"),
123
+ help,
124
+ agents,
125
+ key,
126
+ keyStdin,
127
+ verify,
128
+ verifyExplicit: verifyRaw !== void 0,
129
+ control: controlRaw === void 0 ? "auto" : parseControlMode(controlRaw),
130
+ controlExplicit: controlRaw !== void 0,
131
+ transcripts: transcriptsRaw === void 0 ? null : transcriptsRaw === "on",
132
+ takeOverHooks: flags.bools.has("take-over-hooks")
133
+ };
134
+ };
135
+
136
+ // src/setup/hook-ownership.ts
137
+ var commandsIn = (value) => {
138
+ if (Array.isArray(value)) return value.flatMap(commandsIn);
139
+ if (!value || typeof value !== "object") return [];
140
+ return Object.entries(value).flatMap(([key, item]) => key === "command" && typeof item === "string" ? [item] : commandsIn(item));
141
+ };
142
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
143
+ var hasPaidPusharyCommand = (value) => commandsIn(value).some((command) => {
144
+ const executable = pusharyHookExecutable(command);
145
+ const name = executable?.split(/[/\\]/).pop()?.replace(/\.(cmd|exe|mjs)$/i, "");
146
+ return executable !== null && !isBridgeLocator(executable) && name !== BELL_HOOK_BINARY;
147
+ });
148
+ var hasAppCommand = (value) => commandsIn(value).some((command) => {
149
+ const executable = pusharyHookExecutable(command);
150
+ return executable !== null && isBridgeLocator(executable);
151
+ });
152
+ var mcpBearerKey = (document, containerKey, headersKey) => {
153
+ const servers = isRecord(document?.[containerKey]) ? document[containerKey] : null;
154
+ const pushary = isRecord(servers?.pushary) ? servers.pushary : null;
155
+ const headers = isRecord(pushary?.[headersKey]) ? pushary[headersKey] : null;
156
+ const authorization = headers?.Authorization;
157
+ const match = typeof authorization === "string" ? authorization.trim().match(/^Bearer\s+(\S+)$/) : null;
158
+ return match?.[1] ?? null;
159
+ };
160
+ var captureMcpServer = (document, containerKey) => {
161
+ const container = document[containerKey];
162
+ const servers = isRecord(container) ? container : null;
163
+ if (!servers && Object.hasOwn(document, containerKey)) {
164
+ return { present: false, containerValue: structuredClone(container) };
165
+ }
166
+ return servers && Object.hasOwn(servers, "pushary") ? { present: true, value: structuredClone(servers.pushary) } : { present: false };
167
+ };
168
+ var restoreMcpServer = (document, containerKey, snapshot) => {
169
+ const before = JSON.stringify(document);
170
+ const existing = isRecord(document[containerKey]) ? document[containerKey] : null;
171
+ if (snapshot.present) {
172
+ const servers = existing ?? {};
173
+ servers.pushary = structuredClone(snapshot.value);
174
+ document[containerKey] = servers;
175
+ } else if (Object.hasOwn(snapshot, "containerValue")) {
176
+ document[containerKey] = structuredClone(snapshot.containerValue);
177
+ } else if (existing && Object.hasOwn(existing, "pushary")) {
178
+ delete existing.pushary;
179
+ if (Object.keys(existing).length === 0) delete document[containerKey];
180
+ }
181
+ return JSON.stringify(document) !== before;
182
+ };
183
+ var captureHookTakeover = (agent, document) => {
184
+ const hooks = isRecord(document?.hooks) ? document.hooks : null;
185
+ if (!hooks) return null;
186
+ const captured = {};
187
+ for (const [event, entries] of Object.entries(hooks)) {
188
+ if (!Array.isArray(entries)) continue;
189
+ const appEntries = entries.flatMap((value, index) => isRecord(value) && hasAppCommand(value) ? [{ index, value: structuredClone(value) }] : []);
190
+ if (appEntries.length > 0) captured[event] = appEntries;
191
+ }
192
+ return Object.keys(captured).length > 0 ? { version: 1, agent, hooks: captured } : null;
193
+ };
194
+ var isHookTakeoverReceipt = (value) => {
195
+ if (!isRecord(value) || value.version !== 1 || typeof value.agent !== "string" || !AGENT_CHOICES.includes(value.agent) || !isRecord(value.hooks)) return false;
196
+ const expectsMcp = ["claude_code", "codex", "gemini_cli", "vscode"].includes(value.agent);
197
+ if (value.mcpServer !== void 0 !== expectsMcp) return false;
198
+ if (value.codexTrust !== void 0 !== (value.agent === "codex")) return false;
199
+ if (value.codexTrust !== void 0 && !isRecord(value.codexTrust)) return false;
200
+ if (value.mcpServer !== void 0 && (!isRecord(value.mcpServer) || typeof value.mcpServer.present !== "boolean" || value.mcpServer.present && !Object.hasOwn(value.mcpServer, "value"))) return false;
201
+ return Object.values(value.hooks).every((entries) => Array.isArray(entries) && entries.length > 0 && entries.every((item) => isRecord(item) && Number.isInteger(item.index) && item.index >= 0 && isRecord(item.value)));
202
+ };
203
+ var restoreHookTakeover = (document, receipt) => {
204
+ const before = JSON.stringify(document);
205
+ const appOwnsNow = hookOwnerOf(document) === "app";
206
+ const hooks = isRecord(document.hooks) ? document.hooks : {};
207
+ for (const [event, value] of Object.entries(hooks)) {
208
+ if (!Array.isArray(value)) continue;
209
+ const kept = value.filter((entry) => !hasPaidPusharyCommand(entry));
210
+ if (kept.length === 0) delete hooks[event];
211
+ else hooks[event] = kept;
212
+ }
213
+ if (!appOwnsNow) {
214
+ for (const [event, snapshots] of Object.entries(receipt.hooks)) {
215
+ const entries = Array.isArray(hooks[event]) ? [...hooks[event]] : [];
216
+ for (const snapshot of snapshots) {
217
+ entries.splice(Math.min(snapshot.index, entries.length), 0, structuredClone(snapshot.value));
218
+ }
219
+ hooks[event] = entries;
220
+ }
221
+ }
222
+ document.hooks = hooks;
223
+ return JSON.stringify(document) !== before;
224
+ };
225
+ var hookOwnerOf = (document, appAvailable = true) => {
226
+ const hooks = document && typeof document === "object" ? document.hooks : void 0;
227
+ const executables = commandsIn(hooks).map(pusharyHookExecutable).filter((executable) => executable !== null);
228
+ if (appAvailable && executables.some(isBridgeLocator)) return "app";
229
+ if (executables.some((executable) => !isBridgeLocator(executable))) return "cli";
230
+ return "none";
231
+ };
232
+ var planHooks = (context) => {
233
+ if (context.owner !== "app") return "install";
234
+ if (context.takeOverHooks) return "install";
235
+ return "keep";
236
+ };
237
+ var describeAppOwnership = (agentName) => `The Pushary Mac app owns ${agentName}'s hooks.`;
238
+ var KEEP_HINT = "Kept with the app's account. Pass --take-over-hooks to have the CLI own them instead.";
239
+ var OWNER_LABELS = {
240
+ app: "the Pushary Mac app",
241
+ cli: "the CLI"
242
+ };
243
+ var describeHookOwnership = (entries, names) => {
244
+ const owned = entries.filter((entry) => entry.owner !== "none");
245
+ if (owned.length === 0) return null;
246
+ const parts = owned.map((entry) => `${names[entry.agent]} by ${OWNER_LABELS[entry.owner]}${entry.kept ? " (kept)" : ""}`);
247
+ return `Hooks: ${parts.join(", ")}.`;
248
+ };
249
+
250
+ export {
251
+ AGENT_CHOICES,
252
+ effectiveVerify,
253
+ effectiveControlMode,
254
+ parseSetupOptions,
255
+ mcpBearerKey,
256
+ captureMcpServer,
257
+ restoreMcpServer,
258
+ captureHookTakeover,
259
+ isHookTakeoverReceipt,
260
+ restoreHookTakeover,
261
+ hookOwnerOf,
262
+ planHooks,
263
+ describeAppOwnership,
264
+ KEEP_HINT,
265
+ describeHookOwnership
266
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  parseVersion
3
- } from "./chunk-RX75MRGC.js";
3
+ } from "./chunk-BMOFXRGS.js";
4
4
 
5
5
  // src/setup/agent-probe.ts
6
6
  import { execSync } from "child_process";
@@ -4,9 +4,6 @@ import {
4
4
  import {
5
5
  codexHomeFrom
6
6
  } from "./chunk-Y6XXFXVB.js";
7
- import {
8
- HOOK_LOCATOR_BINARY
9
- } from "./chunk-Z6CP5ZZD.js";
10
7
 
11
8
  // src/vscode-config.ts
12
9
  import { homedir } from "os";
@@ -332,82 +329,6 @@ var hasInstructionBlock = (filePath) => {
332
329
  // src/hooks-spec.ts
333
330
  var CURSOR_GATE_SCRIPT = "pushary-gate.mjs";
334
331
 
335
- // src/diagnostics/bridge.ts
336
- import { execFileSync } from "child_process";
337
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
338
- import { homedir as homedir3 } from "os";
339
- import { dirname as dirname3, join as join3 } from "path";
340
- var BRIDGE_BUNDLE_IDENTIFIER = "com.pushary.app";
341
- var BRIDGE_HELPER_SUFFIX = "/Contents/Helpers/pushary-bridge";
342
- var BRIDGE_BUNDLE_ROOTS = ["/Applications/Pushary.app", "$HOME/Applications/Pushary.app"];
343
- var expandHome = (path, home) => path.replaceAll("$HOME", home);
344
- var parseBridgeStub = (contents, stubPath) => {
345
- const helperSuffix = contents.match(/^H=(\S+)$/m)?.[1] ?? BRIDGE_HELPER_SUFFIX;
346
- const cachePath = contents.match(/^C="([^"\n]+)"$/m)?.[1] ?? join3(dirname3(stubPath), ".bridge-cache");
347
- const rootsLine = contents.match(/^for P in ((?:"[^"\n]*"\s*)+); do$/m)?.[1];
348
- const bundleRoots = rootsLine ? [...rootsLine.matchAll(/"([^"]*)"/g)].map((match) => match[1]) : BRIDGE_BUNDLE_ROOTS;
349
- const bundleIdentifier = contents.match(/kMDItemCFBundleIdentifier == "([^"]+)"/)?.[1] ?? BRIDGE_BUNDLE_IDENTIFIER;
350
- return { helperSuffix, cachePath, bundleRoots, bundleIdentifier };
351
- };
352
- var resolveBridgeStub = (stubPath, probe) => {
353
- const contents = probe.readFile(stubPath);
354
- if (contents === null) return { kind: "no-stub", stub: stubPath };
355
- const shape = parseBridgeStub(contents, stubPath);
356
- const helperIn = (bundle) => `${bundle}${shape.helperSuffix}`;
357
- const looked = [];
358
- for (const root of shape.bundleRoots.map((root2) => expandHome(root2, probe.home))) {
359
- looked.push(root);
360
- if (probe.exists(helperIn(root))) return { kind: "bundle", helper: helperIn(root), via: "root" };
361
- }
362
- const cached = shape.cachePath ? probe.readFile(shape.cachePath)?.split("\n")[0]?.trim() : void 0;
363
- if (cached) {
364
- looked.push(cached);
365
- if (probe.exists(helperIn(cached))) return { kind: "bundle", helper: helperIn(cached), via: "cache" };
366
- }
367
- for (const found of probe.mdfind(shape.bundleIdentifier)) {
368
- looked.push(found);
369
- if (probe.exists(helperIn(found))) return { kind: "bundle", helper: helperIn(found), via: "spotlight" };
370
- }
371
- return { kind: "missing", stub: stubPath, looked };
372
- };
373
- var BRIDGE_GONE_MESSAGE = "the Mac app is gone but its hooks remain; run pushary setup or reinstall the app";
374
- var describeBridgeResolution = (resolution) => {
375
- switch (resolution.kind) {
376
- case "bundle":
377
- return `${resolution.helper} (${resolution.via === "root" ? "installed" : resolution.via === "cache" ? "cached path" : "found by Spotlight"})`;
378
- case "missing":
379
- return BRIDGE_GONE_MESSAGE;
380
- case "no-stub":
381
- return `${resolution.stub} is not there; ${BRIDGE_GONE_MESSAGE}`;
382
- }
383
- };
384
- var isBridgeLocator = (executable) => executable !== null && executable.split(/[/\\]/).pop() === HOOK_LOCATOR_BINARY;
385
- var spotlight = (bundleIdentifier) => {
386
- if (process.platform !== "darwin") return [];
387
- try {
388
- return execFileSync("/usr/bin/mdfind", [`kMDItemCFBundleIdentifier == "${bundleIdentifier}"`], {
389
- encoding: "utf-8",
390
- timeout: 5e3,
391
- stdio: ["ignore", "pipe", "ignore"]
392
- }).split("\n").map((line) => line.trim()).filter((line) => line !== "");
393
- } catch {
394
- return [];
395
- }
396
- };
397
- var readOrNull = (path) => {
398
- try {
399
- return readFileSync2(path, "utf-8");
400
- } catch {
401
- return null;
402
- }
403
- };
404
- var liveBridgeProbe = () => ({
405
- exists: existsSync3,
406
- readFile: readOrNull,
407
- mdfind: spotlight,
408
- home: homedir3()
409
- });
410
-
411
332
  export {
412
333
  registerPluginLocation,
413
334
  unregisterPluginLocation,
@@ -425,9 +346,5 @@ export {
425
346
  writeInstructionBlock,
426
347
  removeInstructionBlock,
427
348
  hasInstructionBlock,
428
- CURSOR_GATE_SCRIPT,
429
- resolveBridgeStub,
430
- describeBridgeResolution,
431
- isBridgeLocator,
432
- liveBridgeProbe
349
+ CURSOR_GATE_SCRIPT
433
350
  };
@@ -0,0 +1,276 @@
1
+ import {
2
+ resolvePathBinary
3
+ } from "./chunk-L4ZCFMWW.js";
4
+
5
+ // src/hermes-config.ts
6
+ import { execFileSync } from "child_process";
7
+ import { existsSync, readFileSync, rmSync, writeFileSync } from "fs";
8
+ import { homedir, tmpdir } from "os";
9
+ import { join } from "path";
10
+ var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
11
+ var isSnapshot = (value) => isRecord(value) && typeof value.present === "boolean" && Object.hasOwn(value, "value");
12
+ var isHermesConfigReceipt = (value) => {
13
+ if (!isRecord(value)) return false;
14
+ return ["security", "approval", "transport", "fallback", "plugins", "enabled", "agent", "disabled"].every((key) => isSnapshot(value[key])) && typeof value.pushary_enabled === "boolean" && typeof value.clarify_disabled === "boolean";
15
+ };
16
+ var HERMES_PIP_PACKAGE = "hermes-plugin-pushary";
17
+ var HERMES_CONFIG_SCRIPT = String.raw`
18
+ import json, os, sys
19
+ from hermes_cli.config import load_config, save_config
20
+
21
+ mode, receipt_path = sys.argv[1], sys.argv[2]
22
+ c = load_config()
23
+
24
+ def snap(obj, key):
25
+ return {"present": key in obj, "value": obj.get(key)}
26
+
27
+ restore_conflicts = []
28
+
29
+ def restore(obj, key, before, ours):
30
+ if before.get("present") and before.get("value") == ours:
31
+ return
32
+ if before.get("present"):
33
+ if key in obj and obj.get(key) == before.get("value"):
34
+ return
35
+ elif key not in obj:
36
+ return
37
+ if obj.get(key) != ours:
38
+ restore_conflicts.append(key)
39
+ return
40
+ if before.get("present"):
41
+ obj[key] = before.get("value")
42
+ else:
43
+ obj.pop(key, None)
44
+
45
+ def restore_container(obj, key, before, current, changed):
46
+ raw = obj.get(key)
47
+ if isinstance(before.get("value"), dict):
48
+ if not isinstance(raw, dict):
49
+ if changed:
50
+ restore_conflicts.append(key)
51
+ return
52
+ if current or before.get("present"):
53
+ obj[key] = current
54
+ else:
55
+ obj.pop(key, None)
56
+ elif isinstance(raw, dict) and current:
57
+ restore_conflicts.append(key)
58
+ else:
59
+ restore(obj, key, before, {})
60
+
61
+ def restore_list_member(obj, key, before, ours, ours_before):
62
+ raw = obj.get(key)
63
+ if isinstance(before.get("value"), list):
64
+ if ours_before:
65
+ return
66
+ if not isinstance(raw, list):
67
+ restore_conflicts.append(key)
68
+ return
69
+ remaining = [item for item in raw if item != ours]
70
+ if remaining or before.get("present"):
71
+ obj[key] = remaining
72
+ else:
73
+ obj.pop(key, None)
74
+ return
75
+ if before.get("present") and raw == before.get("value"):
76
+ return
77
+ if not before.get("present") and key not in obj:
78
+ return
79
+ if not isinstance(raw, list):
80
+ restore_conflicts.append(key)
81
+ return
82
+ remaining = [item for item in raw if item != ours]
83
+ if remaining:
84
+ restore_conflicts.append(key)
85
+ else:
86
+ restore(obj, key, before, raw)
87
+
88
+ def valid_snapshot(value):
89
+ return isinstance(value, dict) and isinstance(value.get("present"), bool) and "value" in value
90
+
91
+ def valid_receipt(value):
92
+ snapshots = ["security", "approval", "transport", "fallback", "plugins", "enabled", "agent", "disabled"]
93
+ return (isinstance(value, dict)
94
+ and all(valid_snapshot(value.get(key)) for key in snapshots)
95
+ and isinstance(value.get("pushary_enabled"), bool)
96
+ and isinstance(value.get("clarify_disabled"), bool))
97
+
98
+ if mode == "setup":
99
+ security_before = snap(c, "security")
100
+ s = c.get("security") if isinstance(c.get("security"), dict) else {}
101
+ approval_before = snap(s, "approval")
102
+ ap = s.get("approval") if isinstance(s.get("approval"), dict) else {}
103
+ plugins_before = snap(c, "plugins")
104
+ p = c.get("plugins") if isinstance(c.get("plugins"), dict) else {}
105
+ agent_before = snap(c, "agent")
106
+ a = c.get("agent") if isinstance(c.get("agent"), dict) else {}
107
+ enabled = p.get("enabled") if isinstance(p.get("enabled"), list) else []
108
+ disabled = a.get("disabled_toolsets") if isinstance(a.get("disabled_toolsets"), list) else []
109
+ receipt = {
110
+ "security": security_before,
111
+ "approval": approval_before,
112
+ "transport": snap(ap, "transport"),
113
+ "fallback": snap(ap, "transport_fallback"),
114
+ "plugins": plugins_before,
115
+ "enabled": snap(p, "enabled"),
116
+ "pushary_enabled": "pushary" in enabled,
117
+ "agent": agent_before,
118
+ "disabled": snap(a, "disabled_toolsets"),
119
+ "clarify_disabled": "clarify" in disabled,
120
+ }
121
+ if os.path.exists(receipt_path):
122
+ with open(receipt_path, encoding="utf-8") as handle:
123
+ existing_receipt = json.load(handle)
124
+ if not valid_receipt(existing_receipt):
125
+ raise ValueError("invalid Pushary Hermes setup receipt")
126
+ else:
127
+ os.makedirs(os.path.dirname(receipt_path), exist_ok=True)
128
+ temp = receipt_path + ".tmp"
129
+ with open(temp, "x", encoding="utf-8") as handle:
130
+ json.dump(receipt, handle)
131
+ os.chmod(temp, 0o600)
132
+ os.replace(temp, receipt_path)
133
+ ap["transport"] = "pushary"
134
+ ap["transport_fallback"] = "builtin"
135
+ s["approval"] = ap
136
+ c["security"] = s
137
+ p["enabled"] = enabled if "pushary" in enabled else enabled + ["pushary"]
138
+ c["plugins"] = p
139
+ a["disabled_toolsets"] = disabled if "clarify" in disabled else disabled + ["clarify"]
140
+ c["agent"] = a
141
+ else:
142
+ receipt_exists = os.path.exists(receipt_path)
143
+ try:
144
+ with open(receipt_path, encoding="utf-8") as handle:
145
+ receipt = json.load(handle)
146
+ except (OSError, ValueError):
147
+ if receipt_exists:
148
+ raise
149
+ receipt = None
150
+ s = c.get("security") if isinstance(c.get("security"), dict) else {}
151
+ ap = s.get("approval") if isinstance(s.get("approval"), dict) else {}
152
+ if receipt:
153
+ if not valid_receipt(receipt):
154
+ raise ValueError("invalid Pushary Hermes setup receipt")
155
+ approval_changed = (not receipt["transport"].get("present")
156
+ or receipt["transport"].get("value") != "pushary"
157
+ or not receipt["fallback"].get("present")
158
+ or receipt["fallback"].get("value") != "builtin")
159
+ plugins_changed = not (isinstance(receipt["enabled"].get("value"), list)
160
+ and receipt["pushary_enabled"])
161
+ agent_changed = not (isinstance(receipt["disabled"].get("value"), list)
162
+ and receipt["clarify_disabled"])
163
+ restore(ap, "transport", receipt["transport"], "pushary")
164
+ restore(ap, "transport_fallback", receipt["fallback"], "builtin")
165
+ else:
166
+ if ap.get("transport") == "pushary": ap.pop("transport", None)
167
+ if ap.get("transport_fallback") == "builtin": ap.pop("transport_fallback", None)
168
+ if receipt:
169
+ restore_container(s, "approval", receipt["approval"], ap, approval_changed)
170
+ restore_container(c, "security", receipt["security"], s, approval_changed)
171
+ else:
172
+ if ap: s["approval"] = ap
173
+ else: s.pop("approval", None)
174
+ if s: c["security"] = s
175
+ else: c.pop("security", None)
176
+
177
+ p = c.get("plugins") if isinstance(c.get("plugins"), dict) else {}
178
+ if receipt:
179
+ restore_list_member(p, "enabled", receipt["enabled"], "pushary", receipt["pushary_enabled"])
180
+ restore_container(c, "plugins", receipt["plugins"], p, plugins_changed)
181
+ else:
182
+ enabled = p.get("enabled") if isinstance(p.get("enabled"), list) else []
183
+ enabled = [item for item in enabled if item != "pushary"]
184
+ if enabled: p["enabled"] = enabled
185
+ else: p.pop("enabled", None)
186
+ if p: c["plugins"] = p
187
+ else: c.pop("plugins", None)
188
+
189
+ a = c.get("agent") if isinstance(c.get("agent"), dict) else {}
190
+ if receipt:
191
+ restore_list_member(a, "disabled_toolsets", receipt["disabled"], "clarify", receipt["clarify_disabled"])
192
+ restore_container(c, "agent", receipt["agent"], a, agent_changed)
193
+ else:
194
+ disabled = a.get("disabled_toolsets") if isinstance(a.get("disabled_toolsets"), list) else []
195
+ disabled = [item for item in disabled if item != "clarify"]
196
+ if disabled: a["disabled_toolsets"] = disabled
197
+ else: a.pop("disabled_toolsets", None)
198
+ if a: c["agent"] = a
199
+ else: c.pop("agent", None)
200
+
201
+ if receipt and restore_conflicts:
202
+ raise ValueError("Hermes config changed after Pushary setup")
203
+
204
+ save_config(c)
205
+ `;
206
+ var resolveHermesPython = () => {
207
+ const launcher = resolvePathBinary("hermes");
208
+ if (launcher && process.platform !== "win32") {
209
+ try {
210
+ const shebang = readFileSync(launcher, "utf-8").split("\n", 1)[0];
211
+ const interpreter = shebang?.startsWith("#!") ? shebang.slice(2).trim().split(/\s+/)[0] : void 0;
212
+ if (interpreter && /python/i.test(interpreter) && existsSync(interpreter)) return interpreter;
213
+ } catch {
214
+ }
215
+ }
216
+ const root = join(homedir(), ".hermes", "hermes-agent", "venv");
217
+ const candidates = process.platform === "win32" ? [join(root, "Scripts", "python.exe"), join(root, "Scripts", "python3.exe")] : [join(root, "bin", "python3"), join(root, "bin", "python")];
218
+ return candidates.find(existsSync) ?? null;
219
+ };
220
+ var runHermesPythonScript = (python, script, ...args) => {
221
+ const path = join(tmpdir(), `pushary-hermes-${process.pid}-${Date.now()}.py`);
222
+ try {
223
+ writeFileSync(path, script, { encoding: "utf-8", mode: 384 });
224
+ execFileSync(python, [path, ...args], { env: { ...process.env }, stdio: "pipe", timeout: 15e3 });
225
+ return true;
226
+ } catch {
227
+ return false;
228
+ } finally {
229
+ try {
230
+ rmSync(path, { force: true });
231
+ } catch {
232
+ }
233
+ }
234
+ };
235
+
236
+ // src/cli/dry-run.ts
237
+ import { execSync } from "child_process";
238
+ import { rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
239
+ var createGuards = (isDryRun, note) => ({
240
+ write: (path, contents) => {
241
+ if (isDryRun()) return note("rewrite", path);
242
+ writeFileSync2(path, contents, "utf-8");
243
+ },
244
+ remove: (path, options = {}) => {
245
+ if (isDryRun()) return note("remove ", path);
246
+ rmSync2(path, { recursive: true, force: options.force ?? false });
247
+ },
248
+ exec: (command, options, describe) => {
249
+ if (isDryRun()) return note("run ", describe);
250
+ execSync(command, options);
251
+ }
252
+ });
253
+ var describeService = (effects) => {
254
+ if (effects.controlMode === "off") return "skip the phone-start background service (--control off)";
255
+ const where = effects.serviceDefinitionPath ?? "the phone-start service definition";
256
+ const condition = effects.controlMode === "on" ? "" : ", when a supported agent and a service manager are present";
257
+ return `write ${where} and register it with the OS${condition}`;
258
+ };
259
+ var describeSetupSideEffects = (effects) => [
260
+ `run npm install -g @pushary/agent-hooks@${effects.version} (the hooks run from the global copy; up to two minutes)`,
261
+ `write ${effects.configFile} (the API key, mode 600)`,
262
+ effects.rcPath ? `edit ${effects.rcPath} (export PUSHARY_API_KEY)` : "print the export line for your shell, since no rc file was found",
263
+ describeService(effects),
264
+ "ask Add Pushary instructions to this project's CLAUDE.md/AGENTS.md? (default no)",
265
+ "ask Alias claude to pushary claude? (default no)"
266
+ ];
267
+
268
+ export {
269
+ isHermesConfigReceipt,
270
+ HERMES_PIP_PACKAGE,
271
+ HERMES_CONFIG_SCRIPT,
272
+ resolveHermesPython,
273
+ runHermesPythonScript,
274
+ createGuards,
275
+ describeSetupSideEffects
276
+ };
@@ -1028,6 +1028,7 @@ var handleSessionEnd = async (input, agent = CLAUDE_CODE_AGENT, options = {}) =>
1028
1028
  }
1029
1029
  }
1030
1030
  if (!isDefaultSession(sessionKey)) removePendingSession(sessionKey);
1031
+ if (options.reportClosed === false) return;
1031
1032
  await reportEvent({
1032
1033
  event: "session_closed",
1033
1034
  agentType: agent.type,