@agentsoc/beacon 0.0.7 → 0.0.8

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.
package/README.md CHANGED
@@ -102,6 +102,8 @@ On macOS the plist is written under `/Library/LaunchDaemons/`, and on Linux the
102
102
 
103
103
  **`sudo beacon` says “command not found”:** sudo resets `PATH`, so it often cannot see npm/nvm global bins. Use `sudo "$(command -v beacon)" install` (as above), or `sudo env "PATH=$PATH" beacon install`, or the full path from `which beacon`.
104
104
 
105
+ **`Beacon is not configured` under sudo:** the install command reads **`config.json` from the user who invoked sudo** (`SUDO_USER`, e.g. `/home/ubuntu/.config/...`), not from `/root`, so it matches `beacon config` run as your normal account.
106
+
105
107
  ### Status and stats
106
108
 
107
109
  Show whether the systemd/launchd service is present, resolve **organization name and API key label** via the platform API (`GET /api/v1/siem/beacon/validate/key` using your ingest key), and print forwarding counters from the local stats file:
package/dist/cli.js CHANGED
@@ -1,243 +1,104 @@
1
1
  #!/usr/bin/env node
2
- import { execFileSync } from "node:child_process";
3
- import { Command } from "commander";
4
- import { BEACON_CONFIG_REQUIRED_MESSAGE, coerceBeaconEnvironment, loadConfig, parseBeaconEnvironment, resolveBeaconApiKey, resolveSiemBeaconValidateKeyUrl, resolveIngestUrl, saveConfig, } from "./config.js";
5
- import { fetchBeaconContext } from "./beacon-context.js";
6
- import { fetchBeaconUpdateFromNpm } from "./beacon-update-info.js";
7
- import { readBeaconCliVersion, semverLessThan } from "./beacon-version.js";
8
- import { runBeacon } from "./run-beacon.js";
9
- import { installService } from "./service-install.js";
10
- import { probeServiceStatus } from "./service-status.js";
11
- import { getStatsFilePath, readStats } from "./stats.js";
12
- const BEACON_VERSION = readBeaconCliVersion();
13
- const program = new Command();
14
- program
15
- .name("beacon")
16
- .description("AgentSOC Syslog Beacon - Lightweight background log forwarder")
17
- .version(BEACON_VERSION, "-v, --version");
18
- program
19
- .command("config")
20
- .description("Configure the AgentSOC connection")
21
- .option("-e, --env <env>", "Environment: production (default) or development")
22
- .option("-k, --key <key>", "AgentSOC API Key")
23
- .action(async (options) => {
24
- if (!options.key) {
25
- console.log("\n[beacon] Missing required option.\n");
26
- console.log("Usage: beacon config --key <key> [--env production|development]\n");
27
- console.log("Examples:");
28
- console.log(" beacon config --key sk_1234567890abcdef");
29
- console.log(" beacon config --key sk_1234567890abcdef --env development\n");
30
- console.log("Options:");
31
- console.log(" -k, --key <key> AgentSOC API Key (required)");
32
- console.log(" -e, --env <env> production (default) or development; sets ingest + platform API defaults\n");
33
- process.exit(1);
34
- }
35
- const existing = await loadConfig();
36
- let environment;
37
- try {
38
- environment =
39
- options.env !== undefined
40
- ? parseBeaconEnvironment(options.env)
41
- : (coerceBeaconEnvironment(existing.environment) ?? "production");
42
- }
43
- catch (e) {
44
- console.error("[beacon]", e instanceof Error ? e.message : String(e));
45
- process.exit(1);
46
- }
47
- await saveConfig({
48
- apiKey: options.key,
49
- environment,
50
- agentId: existing.agentId,
51
- });
52
- console.log("[beacon] Config saved.");
53
- console.log(`[beacon] Environment: ${environment}`);
54
- });
55
- program
56
- .command("install")
57
- .description("Install the background service daemon")
58
- .action(async () => {
59
- try {
60
- await installService();
61
- }
62
- catch (err) {
63
- const message = err instanceof Error ? err.message : String(err);
64
- console.error(`[beacon] Install failed:\n\n${message}\n`);
65
- process.exit(1);
66
- }
67
- });
68
- program
69
- .command("status")
70
- .description("Show service state and forwarding statistics")
71
- .option("--json", "Print machine-readable JSON on stdout")
72
- .action(async (opts) => {
73
- const svc = probeServiceStatus();
74
- const stats = await readStats();
75
- const statsPath = getStatsFilePath();
76
- const cfg = await loadConfig();
77
- const apiKey = resolveBeaconApiKey(cfg);
78
- const validateKeyUrl = resolveSiemBeaconValidateKeyUrl(cfg);
79
- const context = apiKey
80
- ? await fetchBeaconContext(validateKeyUrl, apiKey)
81
- : ({
82
- ok: false,
83
- message: BEACON_CONFIG_REQUIRED_MESSAGE,
84
- });
85
- if (opts.json) {
86
- console.log(JSON.stringify({
87
- service: svc,
88
- stats,
89
- statsPath,
90
- validateKeyUrl,
91
- context: context.ok
92
- ? {
93
- organizationName: context.organizationName,
94
- organizationSlug: context.organizationSlug,
95
- apiKeyName: context.apiKeyName,
96
- }
97
- : { error: context.message },
98
- }, null, 2));
99
- return;
100
- }
101
- const labelW = 26;
102
- const line = (label, value) => {
103
- console.log(` ${label.padEnd(labelW)}${value}`);
104
- };
105
- console.log("\n AgentSOC Beacon — Status\n");
106
- console.log(" Account");
107
- if (context.ok) {
108
- line("Organization", context.organizationName ??
109
- "(name unavailable — check platform API / database)");
110
- line("API key", context.apiKeyName);
111
- }
112
- else {
113
- line("Connection", context.message);
114
- }
115
- console.log("\n Service");
116
- line(`Daemon (${svc.manager})`, svc.installed ? svc.stateLabel : "not installed");
117
- if (svc.active === true)
118
- line("Running", "yes");
119
- else if (svc.active === false)
120
- line("Running", "no");
121
- else
122
- line("Running", "n/a");
123
- if (svc.detail)
124
- line("Note", svc.detail);
125
- console.log("\n Forwarding (this machine)");
126
- line("Log entries forwarded", String(stats.logsForwarded));
127
- line("Successful batches", String(stats.batchesSucceeded));
128
- line("Failed batches", String(stats.batchesFailed));
129
- if (stats.updatedAt && stats.updatedAt !== new Date(0).toISOString()) {
130
- line("Last stats update", stats.updatedAt);
131
- }
132
- else {
133
- line("Last stats update", "(none yet)");
134
- }
135
- if (stats.lastError) {
136
- line("Last error", stats.lastError);
137
- }
138
- console.log();
139
- });
140
- program
141
- .command("update")
142
- .description("Check for a newer Beacon CLI and optionally install it")
143
- .option("--json", "Print machine-readable JSON on stdout")
144
- .option("-y, --yes", "Run npm install -g @agentsoc/beacon@latest (non-interactive upgrade)")
145
- .action(async (opts) => {
146
- const current = BEACON_VERSION;
147
- const fetched = await fetchBeaconUpdateFromNpm();
148
- if (opts.json) {
149
- const latest = fetched.ok ? fetched.info.latestVersion : null;
150
- const outdated = latest != null &&
151
- latest.length > 0 &&
152
- semverLessThan(current, latest);
153
- console.log(JSON.stringify({
154
- currentVersion: current,
155
- registry: "https://registry.npmjs.org/@agentsoc%2fbeacon",
156
- remote: fetched.ok ? fetched.info : null,
157
- error: fetched.ok ? undefined : fetched.message,
158
- updateAvailable: fetched.ok ? outdated : null,
159
- }, null, 2));
160
- if (!fetched.ok)
161
- process.exit(1);
162
- return;
163
- }
164
- if (!fetched.ok) {
165
- console.error(`[beacon] Could not reach npm registry: ${fetched.message}`);
166
- console.error("[beacon] You can still run: npm install -g @agentsoc/beacon@latest");
167
- process.exit(1);
168
- }
169
- const { info } = fetched;
170
- const latest = info.latestVersion;
171
- console.log("\n AgentSOC Beacon — Update check\n");
172
- console.log(` This install ${current}`);
173
- if (latest) {
174
- console.log(` Latest on registry ${latest}`);
175
- }
176
- else {
177
- console.log(" Latest on registry (unavailable — unexpected npm response)");
178
- }
179
- const canCompare = Boolean(latest && latest.length > 0);
180
- const outdated = canCompare && semverLessThan(current, latest);
181
- if (canCompare && !outdated) {
182
- console.log("\n You are on the latest published version.\n");
183
- return;
184
- }
185
- if (canCompare && outdated) {
186
- console.log("\n A newer version is available.\n");
187
- }
188
- else {
189
- console.log("\n Compare versions manually, or reinstall with:\n");
190
- }
191
- console.log(` ${info.install.npm}`);
192
- console.log(` ${info.install.bun}`);
193
- console.log(` ${info.install.pnpm}`);
194
- if (info.docsUrl) {
195
- console.log(`\n Docs: ${info.docsUrl}`);
196
- }
197
- if (opts.yes) {
198
- if (!outdated && canCompare) {
199
- console.log("\n[beacon] Already up to date — skipping install.\n");
200
- return;
201
- }
202
- console.log("\n[beacon] Running npm install -g @agentsoc/beacon@latest …\n");
203
- const npm = process.platform === "win32" ? "npm.cmd" : "npm";
204
- try {
205
- execFileSync(npm, ["install", "-g", "@agentsoc/beacon@latest"], { stdio: "inherit", env: process.env });
206
- console.log("\n[beacon] Update finished. Run `beacon --version` to verify.\n");
207
- }
208
- catch {
209
- process.exit(1);
210
- }
211
- return;
212
- }
213
- console.log("\n To upgrade now, run the same command with --yes\n");
214
- });
215
- program
216
- .command("run")
217
- .description("Run the forwarder daemon (foreground)")
218
- .option("--batch-size <n>", "Batch size", "25")
219
- .option("--flush-ms <n>", "Flush interval in ms", "2000")
220
- .action(async (options) => {
221
- const config = await loadConfig();
222
- const apiKey = resolveBeaconApiKey(config);
223
- const ingestUrl = resolveIngestUrl(config);
224
- if (!apiKey) {
225
- console.error(`[beacon] ${BEACON_CONFIG_REQUIRED_MESSAGE}`);
226
- process.exit(1);
227
- }
228
- console.log("[beacon] Starting in foreground...");
229
- const beacon = await runBeacon({
230
- apiKey,
231
- ingestUrl,
232
- batchSize: parseInt(options.batchSize, 10),
233
- flushMs: parseInt(options.flushMs, 10),
234
- });
235
- const stop = async () => {
236
- console.log("\n[beacon] Stopping...");
237
- await beacon.stop();
238
- process.exit(0);
239
- };
240
- process.on("SIGINT", stop);
241
- process.on("SIGTERM", stop);
242
- });
243
- program.parse(process.argv);
2
+ import{createRequire as a0}from"node:module";var i0=Object.create;var{getPrototypeOf:n0,defineProperty:Q0,getOwnPropertyNames:t0}=Object;var r0=Object.prototype.hasOwnProperty;var o0=($,z,J)=>{J=$!=null?i0(n0($)):{};let B=z||!$||!$.__esModule?Q0(J,"default",{value:$,enumerable:!0}):J;for(let Q of t0($))if(!r0.call(B,Q))Q0(B,Q,{get:()=>$[Q],enumerable:!0});return B};var j=($,z)=>()=>(z||$((z={exports:{}}).exports,z),z.exports);var N=a0(import.meta.url);var P=j((e0)=>{class v extends Error{constructor($,z,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=z,this.exitCode=$,this.nestedError=void 0}}class Y0 extends v{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}e0.CommanderError=v;e0.InvalidArgumentError=Y0});var k=j((Q1)=>{var{InvalidArgumentError:J1}=P();class Z0{constructor($,z){switch(this.description=z||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,z){if(z===this.defaultValue||!Array.isArray(z))return[$];return z.concat($)}default($,z){return this.defaultValue=$,this.defaultValueDescription=z,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(z,J)=>{if(!this.argChoices.includes(z))throw new J1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(z,J);return z},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function B1($){let z=$.name()+($.variadic===!0?"...":"");return $.required?"<"+z+">":"["+z+"]"}Q1.Argument=Z0;Q1.humanReadableArgName=B1});var h=j((X1)=>{var{humanReadableArgName:q1}=k();class q0{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands($){let z=$.commands.filter((J)=>!J._hidden);if($._hasImplicitHelpCommand()){let[,J,B]=$._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),Q=$.createCommand(J).helpOption(!1);if(Q.description($._helpCommandDescription),B)Q.arguments(B);z.push(Q)}if(this.sortSubcommands)z.sort((J,B)=>{return J.name().localeCompare(B.name())});return z}compareOptions($,z){let J=(B)=>{return B.short?B.short.replace(/^-/,""):B.long.replace(/^--/,"")};return J($).localeCompare(J(z))}visibleOptions($){let z=$.options.filter((Q)=>!Q.hidden),J=$._hasHelpOption&&$._helpShortFlag&&!$._findOption($._helpShortFlag),B=$._hasHelpOption&&!$._findOption($._helpLongFlag);if(J||B){let Q;if(!J)Q=$.createOption($._helpLongFlag,$._helpDescription);else if(!B)Q=$.createOption($._helpShortFlag,$._helpDescription);else Q=$.createOption($._helpFlags,$._helpDescription);z.push(Q)}if(this.sortOptions)z.sort(this.compareOptions);return z}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let z=[];for(let J=$.parent;J;J=J.parent){let B=J.options.filter((Q)=>!Q.hidden);z.push(...B)}if(this.sortOptions)z.sort(this.compareOptions);return z}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((z)=>{z.description=z.description||$._argsDescription[z.name()]||""});if($.registeredArguments.find((z)=>z.description))return $.registeredArguments;return[]}subcommandTerm($){let z=$.registeredArguments.map((J)=>q1(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(z?" "+z:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,z){return z.visibleCommands($).reduce((J,B)=>{return Math.max(J,z.subcommandTerm(B).length)},0)}longestOptionTermLength($,z){return z.visibleOptions($).reduce((J,B)=>{return Math.max(J,z.optionTerm(B).length)},0)}longestGlobalOptionTermLength($,z){return z.visibleGlobalOptions($).reduce((J,B)=>{return Math.max(J,z.optionTerm(B).length)},0)}longestArgumentTermLength($,z){return z.visibleArguments($).reduce((J,B)=>{return Math.max(J,z.argumentTerm(B).length)},0)}commandUsage($){let z=$._name;if($._aliases[0])z=z+"|"+$._aliases[0];let J="";for(let B=$.parent;B;B=B.parent)J=B.name()+" "+J;return J+z+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let z=[];if($.argChoices)z.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")z.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)z.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)z.push(`env: ${$.envVar}`);if(z.length>0)return`${$.description} (${z.join(", ")})`;return $.description}argumentDescription($){let z=[];if($.argChoices)z.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)z.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(z.length>0){let J=`(${z.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatHelp($,z){let J=z.padWidth($,z),B=z.helpWidth||80,Q=2,Y=2;function q(K,H){if(H){let x=`${K.padEnd(J+2)}${H}`;return z.wrap(x,B-2,J+2)}return K}function Z(K){return K.join(`
3
+ `).replace(/^/gm," ".repeat(2))}let X=[`Usage: ${z.commandUsage($)}`,""],G=z.commandDescription($);if(G.length>0)X=X.concat([z.wrap(G,B,0),""]);let W=z.visibleArguments($).map((K)=>{return q(z.argumentTerm(K),z.argumentDescription(K))});if(W.length>0)X=X.concat(["Arguments:",Z(W),""]);let U=z.visibleOptions($).map((K)=>{return q(z.optionTerm(K),z.optionDescription(K))});if(U.length>0)X=X.concat(["Options:",Z(U),""]);if(this.showGlobalOptions){let K=z.visibleGlobalOptions($).map((H)=>{return q(z.optionTerm(H),z.optionDescription(H))});if(K.length>0)X=X.concat(["Global Options:",Z(K),""])}let T=z.visibleCommands($).map((K)=>{return q(z.subcommandTerm(K),z.subcommandDescription(K))});if(T.length>0)X=X.concat(["Commands:",Z(T),""]);return X.join(`
4
+ `)}padWidth($,z){return Math.max(z.longestOptionTermLength($,z),z.longestGlobalOptionTermLength($,z),z.longestSubcommandTermLength($,z),z.longestArgumentTermLength($,z))}wrap($,z,J,B=40){let Y=new RegExp(`[\\n][${" \\f\\t\\v   -    \uFEFF"}]+`);if($.match(Y))return $;let q=z-J;if(q<B)return $;let Z=$.slice(0,J),X=$.slice(J).replace(`\r
5
+ `,`
6
+ `),G=" ".repeat(J),U=`\\s${"​"}`,T=new RegExp(`
7
+ |.{1,${q-1}}([${U}]|$)|[^${U}]+?([${U}]|$)`,"g"),K=X.match(T)||[];return Z+K.map((H,x)=>{if(H===`
8
+ `)return"";return(x>0?G:"")+H.trimEnd()}).join(`
9
+ `)}}X1.Help=q0});var u=j((K1)=>{var{InvalidArgumentError:W1}=P();class X0{constructor($,z){this.flags=$,this.description=z||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=W0($);if(this.short=J.shortFlag,this.long=J.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,z){return this.defaultValue=$,this.defaultValueDescription=z,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let z=$;if(typeof $==="string")z={[$]:!0};return this.implied=Object.assign(this.implied||{},z),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,z){if(z===this.defaultValue||!Array.isArray(z))return[$];return z.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(z,J)=>{if(!this.argChoices.includes(z))throw new W1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(z,J);return z},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return M1(this.name().replace(/^no-/,""))}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class G0{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((z)=>{if(z.negate)this.negativeOptions.set(z.attributeName(),z);else this.positiveOptions.set(z.attributeName(),z)}),this.negativeOptions.forEach((z,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,z){let J=z.attributeName();if(!this.dualOptions.has(J))return!0;let B=this.negativeOptions.get(J).presetArg,Q=B!==void 0?B:!1;return z.negate===(Q===$)}}function M1($){return $.split("-").reduce((z,J)=>{return z+J[0].toUpperCase()+J.slice(1)})}function W0($){let z,J,B=$.split(/[ |,]+/);if(B.length>1&&!/^[[<]/.test(B[1]))z=B.shift();if(J=B.shift(),!z&&/^-[^-]$/.test(J))z=J,J=void 0;return{shortFlag:z,longFlag:J}}K1.Option=X0;K1.splitOptionFlags=W0;K1.DualOptions=G0});var M0=j((T1)=>{function H1($,z){if(Math.abs($.length-z.length)>3)return Math.max($.length,z.length);let J=[];for(let B=0;B<=$.length;B++)J[B]=[B];for(let B=0;B<=z.length;B++)J[0][B]=B;for(let B=1;B<=z.length;B++)for(let Q=1;Q<=$.length;Q++){let Y=1;if($[Q-1]===z[B-1])Y=0;else Y=1;if(J[Q][B]=Math.min(J[Q-1][B]+1,J[Q][B-1]+1,J[Q-1][B-1]+Y),Q>1&&B>1&&$[Q-1]===z[B-2]&&$[Q-2]===z[B-1])J[Q][B]=Math.min(J[Q][B],J[Q-2][B-2]+1)}return J[$.length][z.length]}function _1($,z){if(!z||z.length===0)return"";z=Array.from(new Set(z));let J=$.startsWith("--");if(J)$=$.slice(2),z=z.map((q)=>q.slice(2));let B=[],Q=3,Y=0.4;if(z.forEach((q)=>{if(q.length<=1)return;let Z=H1($,q),X=Math.max($.length,q.length);if((X-Z)/X>Y){if(Z<Q)Q=Z,B=[q];else if(Z===Q)B.push(q)}}),B.sort((q,Z)=>q.localeCompare(Z)),J)B=B.map((q)=>`--${q}`);if(B.length>1)return`
10
+ (Did you mean one of ${B.join(", ")}?)`;if(B.length===1)return`
11
+ (Did you mean ${B[0]}?)`;return""}T1.suggestSimilar=_1});var H0=j((w1)=>{var I1=N("events").EventEmitter,g=N("child_process"),R=N("path"),c=N("fs"),M=N("process"),{Argument:V1,humanReadableArgName:S1}=k(),{CommanderError:l}=P(),{Help:N1}=h(),{Option:K0,splitOptionFlags:P1,DualOptions:E1}=u(),{suggestSimilar:U0}=M0();class m extends I1{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:(z)=>M.stdout.write(z),writeErr:(z)=>M.stderr.write(z),getOutHelpWidth:()=>M.stdout.isTTY?M.stdout.columns:void 0,getErrHelpWidth:()=>M.stderr.isTTY?M.stderr.columns:void 0,outputError:(z,J)=>J(z)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._hasHelpOption=$._hasHelpOption,this._helpFlags=$._helpFlags,this._helpDescription=$._helpDescription,this._helpShortFlag=$._helpShortFlag,this._helpLongFlag=$._helpLongFlag,this._helpCommandName=$._helpCommandName,this._helpCommandnameAndArgs=$._helpCommandnameAndArgs,this._helpCommandDescription=$._helpCommandDescription,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let z=this;z;z=z.parent)$.push(z);return $}command($,z,J){let B=z,Q=J;if(typeof B==="object"&&B!==null)Q=B,B=null;Q=Q||{};let[,Y,q]=$.match(/([^ ]+) *(.*)/),Z=this.createCommand(Y);if(B)Z.description(B),Z._executableHandler=!0;if(Q.isDefault)this._defaultCommandName=Z._name;if(Z._hidden=!!(Q.noHelp||Q.hidden),Z._executableFile=Q.executableFile||null,q)Z.arguments(q);if(this.commands.push(Z),Z.parent=this,Z.copyInheritedSettings(this),B)return this;return Z}createCommand($){return new m($)}createHelp(){return Object.assign(new N1,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,z){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);if(z=z||{},z.isDefault)this._defaultCommandName=$._name;if(z.noHelp||z.hidden)$._hidden=!0;return this.commands.push($),$.parent=this,this}createArgument($,z){return new V1($,z)}argument($,z,J,B){let Q=this.createArgument($,z);if(typeof J==="function")Q.default(B).argParser(J);else Q.default(J);return this.addArgument(Q),this}arguments($){return $.trim().split(/ +/).forEach((z)=>{this.argument(z)}),this}addArgument($){let z=this.registeredArguments.slice(-1)[0];if(z&&z.variadic)throw Error(`only the last argument can be variadic '${z.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}addHelpCommand($,z){if($===!1)this._addImplicitHelpCommand=!1;else{if(this._addImplicitHelpCommand=!0,typeof $==="string")this._helpCommandName=$.split(" ")[0],this._helpCommandnameAndArgs=$;this._helpCommandDescription=z||this._helpCommandDescription}return this}_hasImplicitHelpCommand(){if(this._addImplicitHelpCommand===void 0)return this.commands.length&&!this._actionHandler&&!this._findCommand("help");return this._addImplicitHelpCommand}hook($,z){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
13
+ Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(z);else this._lifeCycleHooks[$]=[z];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(z)=>{if(z.code!=="commander.executeSubCommandAsync")throw z};return this}_exit($,z,J){if(this._exitCallback)this._exitCallback(new l($,z,J));M.exit($)}action($){let z=(J)=>{let B=this.registeredArguments.length,Q=J.slice(0,B);if(this._storeOptionsAsProperties)Q[B]=this;else Q[B]=this.opts();return Q.push(this),$.apply(this,Q)};return this._actionHandler=z,this}createOption($,z){return new K0($,z)}_callParseArg($,z,J,B){try{return $.parseArg(z,J)}catch(Q){if(Q.code==="commander.invalidArgument"){let Y=`${B} ${Q.message}`;this.error(Y,{exitCode:Q.exitCode,code:Q.code})}throw Q}}addOption($){let z=$.name(),J=$.attributeName();if($.negate){let Q=$.long.replace(/^--no-/,"--");if(!this._findOption(Q))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");this.options.push($);let B=(Q,Y,q)=>{if(Q==null&&$.presetArg!==void 0)Q=$.presetArg;let Z=this.getOptionValue(J);if(Q!==null&&$.parseArg)Q=this._callParseArg($,Q,Z,Y);else if(Q!==null&&$.variadic)Q=$._concatValue(Q,Z);if(Q==null)if($.negate)Q=!1;else if($.isBoolean()||$.optional)Q=!0;else Q="";this.setOptionValueWithSource(J,Q,q)};if(this.on("option:"+z,(Q)=>{let Y=`error: option '${$.flags}' argument '${Q}' is invalid.`;B(Q,Y,"cli")}),$.envVar)this.on("optionEnv:"+z,(Q)=>{let Y=`error: option '${$.flags}' value '${Q}' from env '${$.envVar}' is invalid.`;B(Q,Y,"env")});return this}_optionEx($,z,J,B,Q){if(typeof z==="object"&&z instanceof K0)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(z,J);if(Y.makeOptionMandatory(!!$.mandatory),typeof B==="function")Y.default(Q).argParser(B);else if(B instanceof RegExp){let q=B;B=(Z,X)=>{let G=q.exec(Z);return G?G[0]:X},Y.default(Q).argParser(B)}else Y.default(B);return this.addOption(Y)}option($,z,J,B){return this._optionEx({},$,z,J,B)}requiredOption($,z,J,B){return this._optionEx({mandatory:!0},$,z,J,B)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){if(this._passThroughOptions=!!$,!!this.parent&&$&&!this.parent._enablePositionalOptions)throw Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,z){return this.setOptionValueWithSource($,z,void 0)}setOptionValueWithSource($,z,J){if(this._storeOptionsAsProperties)this[$]=z;else this._optionValues[$]=z;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let z;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)z=J.getOptionValueSource($)}),z}_prepareUserArgs($,z){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(z=z||{},$===void 0){if($=M.argv,M.versions&&M.versions.electron)z.from="electron"}this.rawArgs=$.slice();let J;switch(z.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(M.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;default:throw Error(`unexpected parse option { from: '${z.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,z){let J=this._prepareUserArgs($,z);return this._parseCommand([],J),this}async parseAsync($,z){let J=this._prepareUserArgs($,z);return await this._parseCommand([],J),this}_executeSubCommand($,z){z=z.slice();let J=!1,B=[".js",".ts",".tsx",".mjs",".cjs"];function Q(G,W){let U=R.resolve(G,W);if(c.existsSync(U))return U;if(B.includes(R.extname(W)))return;let T=B.find((K)=>c.existsSync(`${U}${K}`));if(T)return`${U}${T}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,q=this._executableDir||"";if(this._scriptPath){let G;try{G=c.realpathSync(this._scriptPath)}catch(W){G=this._scriptPath}q=R.resolve(R.dirname(G),q)}if(q){let G=Q(q,Y);if(!G&&!$._executableFile&&this._scriptPath){let W=R.basename(this._scriptPath,R.extname(this._scriptPath));if(W!==this._name)G=Q(q,`${W}-${$._name}`)}Y=G||Y}J=B.includes(R.extname(Y));let Z;if(M.platform!=="win32")if(J)z.unshift(Y),z=R0(M.execArgv).concat(z),Z=g.spawn(M.argv[0],z,{stdio:"inherit"});else Z=g.spawn(Y,z,{stdio:"inherit"});else z.unshift(Y),z=R0(M.execArgv).concat(z),Z=g.spawn(M.execPath,z,{stdio:"inherit"});if(!Z.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((W)=>{M.on(W,()=>{if(Z.killed===!1&&Z.exitCode===null)Z.kill(W)})});let X=this._exitCallback;if(!X)Z.on("close",M.exit.bind(M));else Z.on("close",()=>{X(new l(M.exitCode||0,"commander.executeSubCommandAsync","(close)"))});Z.on("error",(G)=>{if(G.code==="ENOENT"){let W=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",U=`'${Y}' does not exist
14
+ - if '${$._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
15
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
16
+ - ${W}`;throw Error(U)}else if(G.code==="EACCES")throw Error(`'${Y}' not executable`);if(!X)M.exit(1);else{let W=new l(1,"commander.executeSubCommandAsync","(error)");W.nestedError=G,X(W)}}),this.runningCommand=Z}_dispatchSubcommand($,z,J){let B=this._findCommand($);if(!B)this.help({error:!0});let Q;return Q=this._chainOrCallSubCommandHook(Q,B,"preSubcommand"),Q=this._chainOrCall(Q,()=>{if(B._executableHandler)this._executeSubCommand(B,z.concat(J));else return B._parseCommand(z,J)}),Q}_dispatchHelpCommand($){if(!$)this.help();let z=this._findCommand($);if(z&&!z._executableHandler)z.help();return this._dispatchSubcommand($,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,z)=>{if($.required&&this.args[z]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(J,B,Q)=>{let Y=B;if(B!==null&&J.parseArg){let q=`error: command-argument value '${B}' is invalid for argument '${J.name()}'.`;Y=this._callParseArg(J,B,Q,q)}return Y};this._checkNumberOfArguments();let z=[];this.registeredArguments.forEach((J,B)=>{let Q=J.defaultValue;if(J.variadic){if(B<this.args.length){if(Q=this.args.slice(B),J.parseArg)Q=Q.reduce((Y,q)=>{return $(J,q,Y)},J.defaultValue)}else if(Q===void 0)Q=[]}else if(B<this.args.length){if(Q=this.args[B],J.parseArg)Q=$(J,Q,J.defaultValue)}z[B]=Q}),this.processedArgs=z}_chainOrCall($,z){if($&&$.then&&typeof $.then==="function")return $.then(()=>z());return z()}_chainOrCallHooks($,z){let J=$,B=[];if(this._getCommandAndAncestors().reverse().filter((Q)=>Q._lifeCycleHooks[z]!==void 0).forEach((Q)=>{Q._lifeCycleHooks[z].forEach((Y)=>{B.push({hookedCommand:Q,callback:Y})})}),z==="postAction")B.reverse();return B.forEach((Q)=>{J=this._chainOrCall(J,()=>{return Q.callback(Q.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,z,J){let B=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((Q)=>{B=this._chainOrCall(B,()=>{return Q(this,z)})});return B}_parseCommand($,z){let J=this.parseOptions(z);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),z=J.unknown,this.args=$.concat(z),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),z);if(this._hasImplicitHelpCommand()&&$[0]===this._helpCommandName)return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return L0(this,z),this._dispatchSubcommand(this._defaultCommandName,$,z);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});L0(this,J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let B=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},Q=`command:${this.name()}`;if(this._actionHandler){B(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(Q,$,z)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent&&this.parent.listenerCount(Q))B(),this._processArguments(),this.parent.emit(Q,$,z);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,z);if(this.listenerCount("command:*"))this.emit("command:*",$,z);else if(this.commands.length)this.unknownCommand();else B(),this._processArguments()}else if(this.commands.length)B(),this.help({error:!0});else B(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((z)=>z._name===$||z._aliases.includes($))}_findOption($){return this.options.find((z)=>z.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((z)=>{if(z.mandatory&&$.getOptionValue(z.attributeName())===void 0)$.missingMandatoryOptionValue(z)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let B=J.attributeName();if(this.getOptionValue(B)===void 0)return!1;return this.getOptionValueSource(B)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let B=$.find((Q)=>J.conflictsWith.includes(Q.attributeName()));if(B)this._conflictingOption(J,B)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let z=[],J=[],B=z,Q=$.slice();function Y(Z){return Z.length>1&&Z[0]==="-"}let q=null;while(Q.length){let Z=Q.shift();if(Z==="--"){if(B===J)B.push(Z);B.push(...Q);break}if(q&&!Y(Z)){this.emit(`option:${q.name()}`,Z);continue}if(q=null,Y(Z)){let X=this._findOption(Z);if(X){if(X.required){let G=Q.shift();if(G===void 0)this.optionMissingArgument(X);this.emit(`option:${X.name()}`,G)}else if(X.optional){let G=null;if(Q.length>0&&!Y(Q[0]))G=Q.shift();this.emit(`option:${X.name()}`,G)}else this.emit(`option:${X.name()}`);q=X.variadic?X:null;continue}}if(Z.length>2&&Z[0]==="-"&&Z[1]!=="-"){let X=this._findOption(`-${Z[1]}`);if(X){if(X.required||X.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${X.name()}`,Z.slice(2));else this.emit(`option:${X.name()}`),Q.unshift(`-${Z.slice(2)}`);continue}}if(/^--[^=]+=/.test(Z)){let X=Z.indexOf("="),G=this._findOption(Z.slice(0,X));if(G&&(G.required||G.optional)){this.emit(`option:${G.name()}`,Z.slice(X+1));continue}}if(Y(Z))B=J;if((this._enablePositionalOptions||this._passThroughOptions)&&z.length===0&&J.length===0){if(this._findCommand(Z)){if(z.push(Z),Q.length>0)J.push(...Q);break}else if(Z===this._helpCommandName&&this._hasImplicitHelpCommand()){if(z.push(Z),Q.length>0)z.push(...Q);break}else if(this._defaultCommandName){if(J.push(Z),Q.length>0)J.push(...Q);break}}if(this._passThroughOptions){if(B.push(Z),Q.length>0)B.push(...Q);break}B.push(Z)}return{operands:z,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},z=this.options.length;for(let J=0;J<z;J++){let B=this.options[J].attributeName();$[B]=B===this._versionOptionName?this._version:this[B]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,z)=>Object.assign($,z.opts()),{})}error($,z){if(this._outputConfiguration.outputError(`${$}
17
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
18
+ `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
19
+ `),this.outputHelp({error:!0});let J=z||{},B=J.exitCode||1,Q=J.code||"commander.error";this._exit(B,Q,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in M.env){let z=$.attributeName();if(this.getOptionValue(z)===void 0||["default","config","env"].includes(this.getOptionValueSource(z)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,M.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new E1(this.options),z=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&z(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((B)=>!z(B)).forEach((B)=>{this.setOptionValueWithSource(B,J.implied[B],"implied")})})}missingArgument($){let z=`error: missing required argument '${$}'`;this.error(z,{code:"commander.missingArgument"})}optionMissingArgument($){let z=`error: option '${$.flags}' argument missing`;this.error(z,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let z=`error: required option '${$.flags}' not specified`;this.error(z,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,z){let J=(Y)=>{let q=Y.attributeName(),Z=this.getOptionValue(q),X=this.options.find((W)=>W.negate&&q===W.attributeName()),G=this.options.find((W)=>!W.negate&&q===W.attributeName());if(X&&(X.presetArg===void 0&&Z===!1||X.presetArg!==void 0&&Z===X.presetArg))return X;return G||Y},B=(Y)=>{let q=J(Y),Z=q.attributeName();if(this.getOptionValueSource(Z)==="env")return`environment variable '${q.envVar}'`;return`option '${q.flags}'`},Q=`error: ${B($)} cannot be used with ${B(z)}`;this.error(Q,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let z="";if($.startsWith("--")&&this._showSuggestionAfterError){let B=[],Q=this;do{let Y=Q.createHelp().visibleOptions(Q).filter((q)=>q.long).map((q)=>q.long);B=B.concat(Y),Q=Q.parent}while(Q&&!Q._enablePositionalOptions);z=U0($,B)}let J=`error: unknown option '${$}'${z}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let z=this.registeredArguments.length,J=z===1?"":"s",Q=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${z} argument${J} but got ${$.length}.`;this.error(Q,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],z="";if(this._showSuggestionAfterError){let B=[];this.createHelp().visibleCommands(this).forEach((Q)=>{if(B.push(Q.name()),Q.alias())B.push(Q.alias())}),z=U0($,B)}let J=`error: unknown command '${$}'${z}`;this.error(J,{code:"commander.unknownCommand"})}version($,z,J){if($===void 0)return this._version;this._version=$,z=z||"-V, --version",J=J||"output the version number";let B=this.createOption(z,J);return this._versionOptionName=B.attributeName(),this.options.push(B),this.on("option:"+B.name(),()=>{this._outputConfiguration.writeOut(`${$}
20
+ `),this._exit(0,"commander.version",$)}),this}description($,z){if($===void 0&&z===void 0)return this._description;if(this._description=$,z)this._argsDescription=z;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let z=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)z=this.commands[this.commands.length-1];if($===z._name)throw Error("Command alias can't be the same as its name");return z._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((z)=>this.alias(z)),this}usage($){if($===void 0){if(this._usage)return this._usage;let z=this.registeredArguments.map((J)=>{return S1(J)});return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?z:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=R.basename($,R.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let z=this.createHelp();if(z.helpWidth===void 0)z.helpWidth=$&&$.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return z.formatHelp(this,z)}_getHelpContext($){$=$||{};let z={error:!!$.error},J;if(z.error)J=(B)=>this._outputConfiguration.writeErr(B);else J=(B)=>this._outputConfiguration.writeOut(B);return z.write=$.write||J,z.command=this,z}outputHelp($){let z;if(typeof $==="function")z=$,$=void 0;let J=this._getHelpContext($);this._getCommandAndAncestors().reverse().forEach((Q)=>Q.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let B=this.helpInformation(J);if(z){if(B=z(B),typeof B!=="string"&&!Buffer.isBuffer(B))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write(B),this._helpLongFlag)this.emit(this._helpLongFlag);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((Q)=>Q.emit("afterAllHelp",J))}helpOption($,z){if(typeof $==="boolean")return this._hasHelpOption=$,this;this._helpFlags=$||this._helpFlags,this._helpDescription=z||this._helpDescription;let J=P1(this._helpFlags);return this._helpShortFlag=J.shortFlag,this._helpLongFlag=J.longFlag,this}help($){this.outputHelp($);let z=M.exitCode||0;if(z===0&&$&&typeof $!=="function"&&$.error)z=1;this._exit(z,"commander.help","(outputHelp)")}addHelpText($,z){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw Error(`Unexpected value for position to addHelpText.
21
+ Expecting one of '${J.join("', '")}'`);let B=`${$}Help`;return this.on(B,(Q)=>{let Y;if(typeof z==="function")Y=z({error:Q.error,command:Q.command});else Y=z;if(Y)Q.write(`${Y}
22
+ `)}),this}}function L0($,z){if($._hasHelpOption&&z.find((B)=>B===$._helpLongFlag||B===$._helpShortFlag))$.outputHelp(),$._exit(0,"commander.helpDisplayed","(outputHelp)")}function R0($){return $.map((z)=>{if(!z.startsWith("--inspect"))return z;let J,B="127.0.0.1",Q="9229",Y;if((Y=z.match(/^(--inspect(-brk)?)$/))!==null)J=Y[1];else if((Y=z.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=Y[1],/^\d+$/.test(Y[3]))Q=Y[3];else B=Y[3];else if((Y=z.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=Y[1],B=Y[3],Q=Y[4];if(J&&Q!=="0")return`${J}=${B}:${parseInt(Q)+1}`;return z})}w1.Command=m});var I0=j((L,j0)=>{var{Argument:F1}=k(),{Command:_0}=H0(),{CommanderError:k1,InvalidArgumentError:T0}=P(),{Help:y1}=h(),{Option:A1}=u();L=j0.exports=new _0;L.program=L;L.Command=_0;L.Option=A1;L.Argument=F1;L.Help=y1;L.CommanderError=k1;L.InvalidArgumentError=T0;L.InvalidOptionArgumentError=T0});import{execFileSync as K$}from"node:child_process";var V0=o0(I0(),1),{program:V$,createCommand:S$,createArgument:N$,createOption:P$,CommanderError:E$,InvalidArgumentError:w$,InvalidOptionArgumentError:D$,Command:S0,Argument:F$,Option:k$,Help:y$}=V0.default;import b1 from"node:os";import I from"node:path";import d from"node:fs/promises";var C1="https://ingest.agentsoc.com/api/v1/webhooks/syslog",O1="http://localhost:8110/api/v1/webhooks/syslog",f1="https://api.agentsoc.com",x1="http://localhost:8100",v1="/api/v1/siem/beacon/validate/key";function p($){let z=process.env.AGENTSOC_API_KEY?.trim();if(z)return z;return $.apiKey?.trim()||void 0}var E="Beacon is not configured. Run: beacon config --key <your-api-key> [--env production|development]. Or set AGENTSOC_API_KEY in your environment.";function y($){let z=$.toLowerCase().trim();if(z==="production"||z==="prod")return"production";if(z==="development"||z==="dev")return"development";throw Error(`Invalid environment "${$}". Use production or development (prod / dev).`)}function s($){if($==="production"||$==="development")return $;if(typeof $==="string")try{return y($)}catch{return}return}function h1($){return $==="development"?O1:C1}function u1($){return $==="development"?x1:f1}function g1(){let $=process.env.AGENTSOC_ENV?.trim();if(!$)return;try{return y($)}catch{console.warn(`[beacon] Ignoring invalid AGENTSOC_ENV="${$}" (use production or development).`);return}}function P0($){return g1()??s($.environment)??"production"}function E0($){let z=process.env.AGENTSOC_INGEST_URL?.trim();if(z)return z;return h1(P0($))}function c1($){let z=process.env.AGENTSOC_PLATFORM_URL?.trim()||process.env.AGENTSOC_PLATFORM_API_BASE_URL?.trim();if(z)return z.replace(/\/$/,"");return u1(P0($))}function w0($){return`${c1($)}${v1}`}function i($){if(process.platform==="win32")return I.join(process.env.APPDATA||I.join($,"AppData","Roaming"),"agentsoc-beacon");if(process.platform==="darwin")return I.join($,"Library","Application Support","agentsoc-beacon");let z=process.env.XDG_CONFIG_HOME||I.join($,".config");return I.join(z,"agentsoc-beacon")}function w(){return i(b1.homedir())}function N0(){return I.join(w(),"config.json")}async function _(){return n(w())}async function n($){try{let z=I.join($,"config.json"),J=await d.readFile(z,"utf8");return JSON.parse(J)}catch{return{}}}async function A($){let z=w();try{await d.mkdir(z,{recursive:!0}),await d.writeFile(N0(),JSON.stringify($,null,2),"utf8")}catch(J){console.error(`[syslog-beacon] Failed to save config to ${N0()}:`,J)}}async function D0($,z){let J=new AbortController,B=setTimeout(()=>J.abort(),12000);try{let Q=await fetch($,{method:"GET",headers:{"X-API-Key":z},signal:J.signal}),Y=await Q.text(),q;try{q=Y?JSON.parse(Y):null}catch{return{ok:!1,message:"Invalid response from platform API"}}if(!Q.ok){let X=q;return{ok:!1,message:X&&typeof X.error==="string"?X.error:`HTTP ${Q.status}`}}let Z=q;if(!Z?.success||!Z.apiKey?.name)return{ok:!1,message:"Unexpected response from platform API"};return{ok:!0,organizationName:Z.organization?.name??null,organizationSlug:Z.organization?.slug??null,apiKeyName:Z.apiKey.name}}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")return{ok:!1,message:"Request timed out"};return{ok:!1,message:Q instanceof Error?Q.message:String(Q)}}finally{clearTimeout(B)}}var l1=`https://registry.npmjs.org/${encodeURIComponent("@agentsoc/beacon")}`;function m1($,z){return{success:!0,package:"@agentsoc/beacon",latestVersion:$,registryResolved:z,install:{npm:"npm install -g @agentsoc/beacon@latest",bun:"bun add -g @agentsoc/beacon@latest",pnpm:"pnpm add -g @agentsoc/beacon@latest"},docsUrl:"https://agentsoc.com/products/agentsoc-beacon",installScriptUrl:"https://agentsoc.com/connectors/beacon.sh"}}async function F0(){let $=new AbortController,z=setTimeout(()=>$.abort(),12000);try{let J=await fetch(l1,{headers:{Accept:"application/json"},signal:$.signal}),B=await J.text(),Q;try{Q=B?JSON.parse(B):null}catch{return{ok:!1,message:"Invalid JSON from registry.npmjs.org"}}if(!J.ok)return{ok:!1,message:`registry.npmjs.org returned HTTP ${J.status}`};let q=Q["dist-tags"]?.latest?.trim()??null;return{ok:!0,info:m1(q,!0)}}catch(J){if(J instanceof Error&&J.name==="AbortError")return{ok:!1,message:"Request timed out"};return{ok:!1,message:J instanceof Error?J.message:String(J)}}finally{clearTimeout(z)}}import{existsSync as d1,readFileSync as p1}from"node:fs";import{dirname as k0,join as s1}from"node:path";import{fileURLToPath as i1}from"node:url";function A0(){let $=k0(i1(import.meta.url));for(let z=0;z<8;z++){let J=s1($,"package.json");if(d1(J))try{let Q=JSON.parse(p1(J,"utf8"));if(Q.name==="@agentsoc/beacon"&&typeof Q.version==="string")return Q.version}catch{}let B=k0($);if(B===$)break;$=B}return"0.0.0"}function y0($){let z=$.indexOf("-");return z===-1?$:$.slice(0,z)}function t($,z){let J=y0($).split(".").map((Y)=>parseInt(Y,10)||0),B=y0(z).split(".").map((Y)=>parseInt(Y,10)||0),Q=Math.max(J.length,B.length);for(let Y=0;Y<Q;Y++){let q=J[Y]??0,Z=B[Y]??0;if(q<Z)return!0;if(q>Z)return!1}return!1}import r from"node:os";import n1 from"node:crypto";async function b0(){let $=await _(),z=$.agentId;if(!z)z=n1.randomUUID(),$.agentId=z,await A($);let J=r.hostname(),B=r.platform(),Q="127.0.0.1",Y="00:00:00:00:00:00",q=r.networkInterfaces();for(let Z of Object.keys(q)){let X=q[Z];if(!X)continue;for(let G of X)if(!G.internal&&G.family==="IPv4"){Q=G.address,Y=G.mac;break}if(Q!=="127.0.0.1")break}return{agentId:z,hostname:J,ip:Q,osPlatform:B,mac:Y}}import b from"node:fs/promises";import C0 from"node:path";var D=1,o=()=>({version:D,updatedAt:new Date(0).toISOString(),logsForwarded:0,batchesSucceeded:0,batchesFailed:0});function C(){return C0.join(w(),"stats.json")}async function O(){try{let $=await b.readFile(C(),"utf8"),z=JSON.parse($);if(z.version!==D)return o();return{...o(),...z,version:D}}catch{return o()}}async function O0($){let z=C(),J=C0.dirname(z);await b.mkdir(J,{recursive:!0});let B=`${z}.${process.pid}.tmp`;await b.writeFile(B,JSON.stringify($,null,2),"utf8"),await b.rename(B,z)}async function f0($){try{let z=await O();await O0({version:D,updatedAt:new Date().toISOString(),logsForwarded:z.logsForwarded+$,batchesSucceeded:z.batchesSucceeded+1,batchesFailed:z.batchesFailed,lastError:void 0})}catch{}}async function a($){try{let z=await O(),J=$.replace(/\s+/g," ").slice(0,500);await O0({version:D,updatedAt:new Date().toISOString(),logsForwarded:z.logsForwarded,batchesSucceeded:z.batchesSucceeded,batchesFailed:z.batchesFailed+1,lastError:J||"Unknown error"})}catch{}}function t1($){let z=5,J=1,B=$.match(/^<(\d+)>/);if(B){let Y=parseInt(B[1],10);J=Math.floor(Y/8),z=Y&7}else{let Y=$.toLowerCase();if(Y.includes("critical")||Y.includes("fatal")||Y.includes("panic"))z=2;else if(Y.includes("high")||Y.includes("error")||Y.includes("failed"))z=3;else if(Y.includes("medium")||Y.includes("warn"))z=4;else if(Y.includes("info"))z=6;else if(Y.includes("low")||Y.includes("notice"))z=5}let Q="info";if(z<=2)Q="critical";else if(z===3)Q="high";else if(z===4)Q="medium";else if(z===5)Q="low";return{severityStr:Q,facility:J}}function r1($){let z=$.match(/^\S+\s+(?:\S+\s+)?(\w+)(?:\[\d+\])?:\s*(.*)$/);if(z)return{app:z[1],message:z[2]};return{message:$}}class e{opts;buffer=[];timer=null;batchSize;flushMs;constructor($){this.opts=$;this.batchSize=$.batchSize||25,this.flushMs=$.flushMs||2000}pushLog($){let{severityStr:z,facility:J}=t1($),{app:B,message:Q}=r1($),Y={full_log:Q,timestamp:new Date().toISOString(),hostname:this.opts.host.hostname,facility:J,severity:z,id:`${this.opts.host.agentId}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,agent:{id:this.opts.host.agentId,name:this.opts.host.hostname,ip:this.opts.host.ip,mac:this.opts.host.mac}};if(B)Y.app=B,Y.process={name:B};if(this.buffer.push(Y),this.buffer.length>=this.batchSize)this.flush();else if(!this.timer)this.timer=setTimeout(()=>this.flush(),this.flushMs)}async flush(){if(this.timer)clearTimeout(this.timer),this.timer=null;if(this.buffer.length===0)return;let $=this.buffer;this.buffer=[],console.log(`[syslog-beacon] Pushing ${$.length} logs to API...`);try{let z=await fetch(this.opts.ingestUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.apiKey}`},body:JSON.stringify($)});if(!z.ok){let J=await z.text(),B=`HTTP ${z.status} ${J}`;console.error(`[syslog-beacon] Failed to push logs: HTTP ${z.status} ${J}`),await a(B)}else console.log(`[syslog-beacon] Successfully pushed ${$.length} logs`),await f0($.length)}catch(z){console.error("[syslog-beacon] Ingest error:",z),await a(z instanceof Error?z.message:String(z))}}async stop(){if(this.buffer.length>0)await this.flush()}}import{spawn as $0,spawnSync as o1}from"node:child_process";import a1 from"node:dgram";import x0 from"node:fs";var e1=["/var/log/syslog","/var/log/auth.log","/var/log/messages"];function $$(){return e1.filter(($)=>{try{return x0.existsSync($)&&x0.statSync($).isFile()}catch{return!1}})}function z$(){let $=o1("journalctl",["--version"],{stdio:"ignore"});return!$.error&&$.status===0}var J$=/not seeing messages from other users/i;class z0{onLog;tailProc;udpServer;journalRestrictedHintShown=!1;constructor($){this.onLog=$}startUdpListener(){this.udpServer=a1.createSocket("udp4"),this.udpServer.on("message",($)=>{this.onLog($.toString("utf8").trim())}),this.udpServer.on("error",($)=>{console.error(`[syslog-udp] error:
23
+ ${$.stack}`),this.udpServer?.close()}),this.udpServer.bind(5140,()=>{console.log("[syslog-udp] listening on UDP 5140")})}start(){if(process.platform==="linux"){let $=!1;if(z$())$=!0,console.log("[syslog-tail] Streaming systemd journal (journalctl -f)"),this.tailProc=$0("journalctl",["-f","--no-pager","-o","short-iso"]);else{let z=$$();if(z.length>0)console.log(`[syslog-tail] Following: ${z.join(", ")}`),this.tailProc=$0("tail",["-F",...z]);else{console.log("[syslog-tail] No journalctl or log files under /var/log; listening on UDP 5140"),this.startUdpListener();return}}this.tailProc.stdout?.on("data",(z)=>{let J=z.toString().split(`
24
+ `);for(let B of J)if(B.trim())this.onLog(B)}),this.tailProc.stderr?.on("data",(z)=>{let J=z.toString();if(console.error(`[syslog-tail] ${J}`),$&&!this.journalRestrictedHintShown&&J$.test(J))this.journalRestrictedHintShown=!0,console.error("[syslog-tail] Only your user journal is visible. For system-wide logs, add this user to group systemd-journal or adm, or run beacon as root (no extra packages).")})}else if(process.platform==="darwin")this.tailProc=$0("log",["stream","--predicate",'process == "sshd" or process == "sudo" or process == "login" or process == "logger"',"--style","syslog"]),console.log("[syslog-tail] macOS log stream started"),this.tailProc.stdout?.on("data",($)=>{let z=$.toString().split(`
25
+ `);for(let J of z)if(J.trim())this.onLog(J)}),this.tailProc.stderr?.on("data",($)=>{console.error(`[syslog-tail] ${$.toString()}`)});else this.startUdpListener()}stop(){if(this.tailProc)this.tailProc.kill();if(this.udpServer)this.udpServer.close()}}async function v0($){let z=await b0(),J=new e({...$,host:z}),B=new z0((Q)=>{J.pushLog(Q)});return B.start(),{stop:async()=>{B.stop(),await J.stop()}}}import{constants as B$}from"node:fs";import B0 from"node:fs/promises";import Q$ from"node:os";import F from"node:path";import{execFileSync as S,execSync as J0}from"node:child_process";var Y$=`That location is only writable as root. From the same shell where \`beacon\` works, run:
26
+
27
+ sudo "$(command -v beacon)" install
28
+
29
+ You will be prompted for your administrator password.
30
+
31
+ Why not \`sudo beacon install\`? sudo uses a minimal PATH. When beacon was installed with npm/nvm/fnm as your user, root often cannot find the \`beacon\` command (you will see "command not found"). The line above resolves the full path before sudo runs.
32
+
33
+ Other options:
34
+ sudo env "PATH=$PATH" beacon install
35
+ sudo /path/from/which/beacon install`;function c0($){return Error(`Cannot install the system service: permission denied for ${F.dirname($)}.
36
+
37
+ ${Y$}`)}async function h0($){let z=F.dirname($);try{await B0.access(z,B$.W_OK)}catch(J){let B=J&&typeof J==="object"&&"code"in J?J.code:void 0;if(B==="EACCES"||B==="EPERM")throw c0($);throw J}}async function u0($,z){try{await B0.writeFile($,z,"utf8")}catch(J){let B=J&&typeof J==="object"&&"code"in J?J.code:void 0;if(B==="EACCES"||B==="EPERM")throw c0($);throw J}}function Z$(){if(process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe"))return process.execPath;let z=F.basename(process.execPath);if(/^node(\.exe)?$/i.test(z))return process.execPath;try{let J=S("/usr/bin/which",["node"],{encoding:"utf8"}).trim();if(J)return J}catch{}return"node"}function q$($,z){try{S("launchctl",["bootout","system",$],{stdio:"ignore"});return}catch{}try{S("launchctl",["bootout",`system/${z}`],{stdio:"ignore"})}catch{}}function X$($){if(process.platform==="win32")return;try{let J=S("getent",["passwd",$],{encoding:"utf8"}).trim().split(":");if(J.length>=6&&J[5])return J[5]}catch{}if(process.platform==="darwin")return`/Users/${$}`;return F.join("/home",$)}async function G$(){if((typeof process.getuid==="function"?process.getuid():-1)===0){let z=process.env.SUDO_USER?.trim();if(z){let J=X$(z);if(J)return n(i(J))}}return _()}function g0(){let $=process.env.SUDO_USER?.trim();if($)return $;if((typeof process.getuid==="function"?process.getuid():-1)!==0)try{return Q$.userInfo().username}catch{}throw Error("Cannot determine which user account should run the beacon daemon. Config is stored under that user's home directory. Run install from your normal account with sudo, e.g. `sudo beacon install`, not from a root-only shell.")}function W$($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function M$($){try{S("launchctl",["bootstrap","system",$],{encoding:"utf8",stdio:["ignore","inherit","pipe"]})}catch(z){let B=z.stderr?.toString("utf8").trim()??"",Q=B?`
38
+ ${B}`:"";throw Error(`launchctl bootstrap failed for ${$}.${Q}
39
+
40
+ Try:
41
+ sudo launchctl bootout system ${$}
42
+ sudo "$(command -v beacon)" install`)}}async function l0(){if(!(await G$()).apiKey?.trim())throw Error(E);let J=process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe")?process.execPath:"node",B=F.resolve(process.argv[1]),Q=`${J} ${B} run`;if(process.platform==="linux"){let q=`[Unit]
43
+ Description=AgentSOC Syslog Beacon
44
+ After=network.target
45
+
46
+ [Service]
47
+ Type=simple
48
+ User=${g0()}
49
+ ExecStart=${Q}
50
+ Restart=always
51
+ RestartSec=10
52
+ Environment=NODE_ENV=production
53
+
54
+ [Install]
55
+ WantedBy=multi-user.target
56
+ `,Z="/etc/systemd/system/syslog-beacon.service";await h0("/etc/systemd/system/syslog-beacon.service"),await u0("/etc/systemd/system/syslog-beacon.service",q),J0("systemctl daemon-reload"),J0("systemctl enable syslog-beacon"),J0("systemctl start syslog-beacon"),console.log("[syslog-beacon] Installed systemd service")}else if(process.platform==="darwin"){let q=W$(g0()),Z=Z$(),X=`<?xml version="1.0" encoding="UTF-8"?>
57
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
58
+ <plist version="1.0">
59
+ <dict>
60
+ <key>Label</key>
61
+ <string>com.agentsoc.syslog-beacon</string>
62
+ <key>UserName</key>
63
+ <string>${q}</string>
64
+ <key>ProgramArguments</key>
65
+ <array>
66
+ <string>${Z}</string>
67
+ <string>${B}</string>
68
+ <string>run</string>
69
+ </array>
70
+ <key>RunAtLoad</key>
71
+ <true/>
72
+ <key>KeepAlive</key>
73
+ <true/>
74
+ </dict>
75
+ </plist>
76
+ `,G="/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist";await h0("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist"),q$("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist","com.agentsoc.syslog-beacon"),await u0("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist",X),S("chown",["root:wheel","/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist"],{stdio:"inherit"}),await B0.chmod("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist",420),M$("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist"),console.log("[syslog-beacon] Installed launchd service")}else if(process.platform==="win32")console.log("[syslog-beacon] Windows service installation must be done via NSSM or WinSW. Skipping automatic install.");else throw Error(`Platform ${process.platform} is not supported for automatic service installation.`)}import f from"node:fs";import{execFileSync as m0}from"node:child_process";function d0($,z=200){let J=$.replace(/\s+/g," ").trim();return J.length<=z?J:`${J.slice(0,z)}…`}function p0(){if(process.platform==="linux"){if(!f.existsSync("/etc/systemd/system/syslog-beacon.service"))return{manager:"systemd",installed:!1,active:null,stateLabel:"not installed",detail:"No unit at /etc/systemd/system/syslog-beacon.service"};try{let J=m0("systemctl",["is-active","syslog-beacon"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim();return{manager:"systemd",installed:!0,active:J==="active",stateLabel:J||"unknown"}}catch(J){let B=J.status,Q=J.stderr?.toString?.()??"";if(B===3)return{manager:"systemd",installed:!0,active:!1,stateLabel:"inactive"};return{manager:"systemd",installed:!0,active:!1,stateLabel:"unknown",detail:d0(Q||String(J))}}}if(process.platform==="darwin"){if(!f.existsSync("/Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist"))return{manager:"launchd",installed:!1,active:null,stateLabel:"not installed",detail:"No plist at /Library/LaunchDaemons/com.agentsoc.syslog-beacon.plist"};try{let Q=m0("launchctl",["print","system/com.agentsoc.syslog-beacon"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).match(/^\s*state\s*=\s*(\S+)/m)?.[1]??"unknown";return{manager:"launchd",installed:!0,active:Q==="running",stateLabel:Q}}catch(J){let B=J.stderr?.toString?.()??"";return{manager:"launchd",installed:!0,active:null,stateLabel:"unknown",detail:d0(B||String(J))}}}return{manager:"none",installed:!1,active:null,stateLabel:"unsupported",detail:"Automatic service detection is only available on Linux (systemd) and macOS (launchd)."}}var s0=A0(),V=new S0;V.name("beacon").description("AgentSOC Syslog Beacon - Lightweight background log forwarder").version(s0,"-v, --version");V.command("config").description("Configure the AgentSOC connection").option("-e, --env <env>","Environment: production (default) or development").option("-k, --key <key>","AgentSOC API Key").action(async($)=>{if(!$.key)console.log(`
77
+ [beacon] Missing required option.
78
+ `),console.log(`Usage: beacon config --key <key> [--env production|development]
79
+ `),console.log("Examples:"),console.log(" beacon config --key sk_1234567890abcdef"),console.log(` beacon config --key sk_1234567890abcdef --env development
80
+ `),console.log("Options:"),console.log(" -k, --key <key> AgentSOC API Key (required)"),console.log(` -e, --env <env> production (default) or development; sets ingest + platform API defaults
81
+ `),process.exit(1);let z=await _(),J;try{J=$.env!==void 0?y($.env):s(z.environment)??"production"}catch(B){console.error("[beacon]",B instanceof Error?B.message:String(B)),process.exit(1)}await A({apiKey:$.key,environment:J,agentId:z.agentId}),console.log("[beacon] Config saved."),console.log(`[beacon] Environment: ${J}`)});V.command("install").description("Install the background service daemon").action(async()=>{try{await l0()}catch($){let z=$ instanceof Error?$.message:String($);console.error(`[beacon] Install failed:
82
+
83
+ ${z}
84
+ `),process.exit(1)}});V.command("status").description("Show service state and forwarding statistics").option("--json","Print machine-readable JSON on stdout").action(async($)=>{let z=p0(),J=await O(),B=C(),Q=await _(),Y=p(Q),q=w0(Q),Z=Y?await D0(q,Y):{ok:!1,message:E};if($.json){console.log(JSON.stringify({service:z,stats:J,statsPath:B,validateKeyUrl:q,context:Z.ok?{organizationName:Z.organizationName,organizationSlug:Z.organizationSlug,apiKeyName:Z.apiKeyName}:{error:Z.message}},null,2));return}let X=26,G=(W,U)=>{console.log(` ${W.padEnd(X)}${U}`)};if(console.log(`
85
+ AgentSOC Beacon — Status
86
+ `),console.log(" Account"),Z.ok)G("Organization",Z.organizationName??"(name unavailable — check platform API / database)"),G("API key",Z.apiKeyName);else G("Connection",Z.message);if(console.log(`
87
+ Service`),G(`Daemon (${z.manager})`,z.installed?z.stateLabel:"not installed"),z.active===!0)G("Running","yes");else if(z.active===!1)G("Running","no");else G("Running","n/a");if(z.detail)G("Note",z.detail);if(console.log(`
88
+ Forwarding (this machine)`),G("Log entries forwarded",String(J.logsForwarded)),G("Successful batches",String(J.batchesSucceeded)),G("Failed batches",String(J.batchesFailed)),J.updatedAt&&J.updatedAt!==new Date(0).toISOString())G("Last stats update",J.updatedAt);else G("Last stats update","(none yet)");if(J.lastError)G("Last error",J.lastError);console.log()});V.command("update").description("Check for a newer Beacon CLI and optionally install it").option("--json","Print machine-readable JSON on stdout").option("-y, --yes","Run npm install -g @agentsoc/beacon@latest (non-interactive upgrade)").action(async($)=>{let z=s0,J=await F0();if($.json){let Z=J.ok?J.info.latestVersion:null,X=Z!=null&&Z.length>0&&t(z,Z);if(console.log(JSON.stringify({currentVersion:z,registry:"https://registry.npmjs.org/@agentsoc%2fbeacon",remote:J.ok?J.info:null,error:J.ok?void 0:J.message,updateAvailable:J.ok?X:null},null,2)),!J.ok)process.exit(1);return}if(!J.ok)console.error(`[beacon] Could not reach npm registry: ${J.message}`),console.error("[beacon] You can still run: npm install -g @agentsoc/beacon@latest"),process.exit(1);let{info:B}=J,Q=B.latestVersion;if(console.log(`
89
+ AgentSOC Beacon — Update check
90
+ `),console.log(` This install ${z}`),Q)console.log(` Latest on registry ${Q}`);else console.log(" Latest on registry (unavailable — unexpected npm response)");let Y=Boolean(Q&&Q.length>0),q=Y&&t(z,Q);if(Y&&!q){console.log(`
91
+ You are on the latest published version.
92
+ `);return}if(Y&&q)console.log(`
93
+ A newer version is available.
94
+ `);else console.log(`
95
+ Compare versions manually, or reinstall with:
96
+ `);if(console.log(` ${B.install.npm}`),console.log(` ${B.install.bun}`),console.log(` ${B.install.pnpm}`),B.docsUrl)console.log(`
97
+ Docs: ${B.docsUrl}`);if($.yes){if(!q&&Y){console.log(`
98
+ [beacon] Already up to date — skipping install.
99
+ `);return}console.log(`
100
+ [beacon] Running npm install -g @agentsoc/beacon@latest …
101
+ `);let Z=process.platform==="win32"?"npm.cmd":"npm";try{K$(Z,["install","-g","@agentsoc/beacon@latest"],{stdio:"inherit",env:process.env}),console.log("\n[beacon] Update finished. Run `beacon --version` to verify.\n")}catch{process.exit(1)}return}console.log(`
102
+ To upgrade now, run the same command with --yes
103
+ `)});V.command("run").description("Run the forwarder daemon (foreground)").option("--batch-size <n>","Batch size","25").option("--flush-ms <n>","Flush interval in ms","2000").action(async($)=>{let z=await _(),J=p(z),B=E0(z);if(!J)console.error(`[beacon] ${E}`),process.exit(1);console.log("[beacon] Starting in foreground...");let Q=await v0({apiKey:J,ingestUrl:B,batchSize:parseInt($.batchSize,10),flushMs:parseInt($.flushMs,10)}),Y=async()=>{console.log(`
104
+ [beacon] Stopping...`),await Q.stop(),process.exit(0)};process.on("SIGINT",Y),process.on("SIGTERM",Y)});V.parse(process.argv);
package/dist/config.d.ts CHANGED
@@ -38,8 +38,14 @@ export declare function resolvePlatformApiBase(config: BeaconConfig): string;
38
38
  export declare function resolveSiemBeaconValidateKeyUrl(config: BeaconConfig): string;
39
39
  /** @deprecated Use {@link resolveSiemBeaconValidateKeyUrl} */
40
40
  export declare function resolveBeaconContextUrl(config: BeaconConfig): string;
41
+ /**
42
+ * Config directory for a given home directory (same layout as {@link getConfigDir} for that user).
43
+ * Used when `sudo beacon install` must read the invoking user's `config.json` (root's home is /root).
44
+ */
45
+ export declare function getConfigDirForHome(home: string): string;
41
46
  export declare function getConfigDir(): string;
42
47
  export declare function getConfigFile(): string;
43
48
  export declare function loadConfig(): Promise<BeaconConfig>;
49
+ export declare function loadConfigFromConfigDir(configDir: string): Promise<BeaconConfig>;
44
50
  export declare function saveConfig(config: BeaconConfig): Promise<void>;
45
51
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,qBAAqB,uDACoB,CAAC;AAEvD,eAAO,MAAM,sBAAsB,iDACa,CAAC;AAEjD,0EAA0E;AAC1E,eAAO,MAAM,uBAAuB,6BAA6B,CAAC;AAElE,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAEhE,iFAAiF;AACjF,eAAO,MAAM,6BAA6B,qCACN,CAAC;AAErC,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,aAAa,CAAC;AAE7D,kEAAkE;AAClE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAK5E;AAED,iEAAiE;AACjE,eAAO,MAAM,8BAA8B,mJACuG,CAAC;AAEnJ,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAOvE;AAED,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,OAAO,GACb,iBAAiB,GAAG,SAAS,CAU/B;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAItE;AAmBD,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,iBAAiB,CAM5E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAI7D;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAMnE;AAED;;GAEG;AACH,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,YAAY,GACnB,MAAM,CAER;AAED,8DAA8D;AAC9D,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAEpE;AAED,wBAAgB,YAAY,IAAI,MAAM,CAarC;AAED,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED,wBAAsB,UAAU,IAAI,OAAO,CAAC,YAAY,CAAC,CAQxD;AAED,wBAAsB,UAAU,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAepE"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,qBAAqB,uDACoB,CAAC;AAEvD,eAAO,MAAM,sBAAsB,iDACa,CAAC;AAEjD,0EAA0E;AAC1E,eAAO,MAAM,uBAAuB,6BAA6B,CAAC;AAElE,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAEhE,iFAAiF;AACjF,eAAO,MAAM,6BAA6B,qCACN,CAAC;AAErC,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,aAAa,CAAC;AAE7D,kEAAkE;AAClE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAK5E;AAED,iEAAiE;AACjE,eAAO,MAAM,8BAA8B,mJACuG,CAAC;AAEnJ,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAOvE;AAED,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,OAAO,GACb,iBAAiB,GAAG,SAAS,CAU/B;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAItE;AAmBD,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,iBAAiB,CAM5E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAI7D;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAMnE;AAED;;GAEG;AACH,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,YAAY,GACnB,MAAM,CAER;AAED,8DAA8D;AAC9D,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAEpE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYxD;AAED,wBAAgB,YAAY,IAAI,MAAM,CAErC;AAED,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED,wBAAsB,UAAU,IAAI,OAAO,CAAC,YAAY,CAAC,CAExD;AAED,wBAAsB,uBAAuB,CAC3C,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,YAAY,CAAC,CAQvB;AAED,wBAAsB,UAAU,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAepE"}
package/dist/config.js CHANGED
@@ -95,8 +95,11 @@ export function resolveSiemBeaconValidateKeyUrl(config) {
95
95
  export function resolveBeaconContextUrl(config) {
96
96
  return resolveSiemBeaconValidateKeyUrl(config);
97
97
  }
98
- export function getConfigDir() {
99
- const home = os.homedir();
98
+ /**
99
+ * Config directory for a given home directory (same layout as {@link getConfigDir} for that user).
100
+ * Used when `sudo beacon install` must read the invoking user's `config.json` (root's home is /root).
101
+ */
102
+ export function getConfigDirForHome(home) {
100
103
  if (process.platform === "win32") {
101
104
  return path.join(process.env.APPDATA || path.join(home, "AppData", "Roaming"), "agentsoc-beacon");
102
105
  }
@@ -106,16 +109,22 @@ export function getConfigDir() {
106
109
  const xdg = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
107
110
  return path.join(xdg, "agentsoc-beacon");
108
111
  }
112
+ export function getConfigDir() {
113
+ return getConfigDirForHome(os.homedir());
114
+ }
109
115
  export function getConfigFile() {
110
116
  return path.join(getConfigDir(), "config.json");
111
117
  }
112
118
  export async function loadConfig() {
119
+ return loadConfigFromConfigDir(getConfigDir());
120
+ }
121
+ export async function loadConfigFromConfigDir(configDir) {
113
122
  try {
114
- const file = getConfigFile();
123
+ const file = path.join(configDir, "config.json");
115
124
  const data = await fs.readFile(file, "utf8");
116
125
  return JSON.parse(data);
117
126
  }
118
- catch (err) {
127
+ catch {
119
128
  return {};
120
129
  }
121
130
  }
@@ -1 +1 @@
1
- {"version":3,"file":"service-install.d.ts","sourceRoot":"","sources":["../src/service-install.ts"],"names":[],"mappings":"AAkJA,wBAAsB,cAAc,kBA4EnC"}
1
+ {"version":3,"file":"service-install.d.ts","sourceRoot":"","sources":["../src/service-install.ts"],"names":[],"mappings":"AAyLA,wBAAsB,cAAc,kBA4EnC"}
@@ -3,7 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { execFileSync, execSync } from 'node:child_process';
6
- import { BEACON_CONFIG_REQUIRED_MESSAGE, loadConfig } from './config.js';
6
+ import { BEACON_CONFIG_REQUIRED_MESSAGE, getConfigDirForHome, loadConfig, loadConfigFromConfigDir, } from './config.js';
7
7
  const PERMISSION_DENIED_HINT = `That location is only writable as root. From the same shell where \`beacon\` works, run:
8
8
 
9
9
  sudo "$(command -v beacon)" install
@@ -89,6 +89,41 @@ function launchctlBootoutSystem(plistPath, label) {
89
89
  // not loaded yet
90
90
  }
91
91
  }
92
+ /**
93
+ * Home directory for passwd entry (for `sudo beacon install`: read invoking user's config, not /root).
94
+ */
95
+ function lookupUnixHomeDir(username) {
96
+ if (process.platform === 'win32')
97
+ return undefined;
98
+ try {
99
+ const line = execFileSync('getent', ['passwd', username], {
100
+ encoding: 'utf8',
101
+ }).trim();
102
+ const parts = line.split(':');
103
+ if (parts.length >= 6 && parts[5])
104
+ return parts[5];
105
+ }
106
+ catch {
107
+ /* getent missing (e.g. some macOS) or unknown user */
108
+ }
109
+ if (process.platform === 'darwin') {
110
+ return `/Users/${username}`;
111
+ }
112
+ return path.join('/home', username);
113
+ }
114
+ async function loadConfigForServiceInstall() {
115
+ const uid = typeof process.getuid === 'function' ? process.getuid() : -1;
116
+ if (uid === 0) {
117
+ const sudoUser = process.env.SUDO_USER?.trim();
118
+ if (sudoUser) {
119
+ const home = lookupUnixHomeDir(sudoUser);
120
+ if (home) {
121
+ return loadConfigFromConfigDir(getConfigDirForHome(home));
122
+ }
123
+ }
124
+ }
125
+ return loadConfig();
126
+ }
92
127
  /**
93
128
  * Config and stats paths use os.homedir(). A LaunchDaemon/systemd unit runs as root by
94
129
  * default, which points at /var/root (macOS) or /root — not the user who ran `beacon config`.
@@ -133,7 +168,7 @@ function launchctlBootstrapSystem(plistPath) {
133
168
  }
134
169
  }
135
170
  export async function installService() {
136
- const config = await loadConfig();
171
+ const config = await loadConfigForServiceInstall();
137
172
  // Service units do not inherit the install shell's env — key must be saved in config.
138
173
  if (!config.apiKey?.trim()) {
139
174
  throw new Error(BEACON_CONFIG_REQUIRED_MESSAGE);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsoc/beacon",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "Lightweight, background-running log forwarder (beacon) for AgentSOC",
5
5
  "type": "module",
6
6
  "bin": {