bridge-agent 0.3.6 → 0.4.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.
@@ -1299,21 +1299,21 @@ var require_errors = __commonJS({
1299
1299
  function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
1300
1300
  if (errsCount === void 0)
1301
1301
  throw new Error("ajv implementation error");
1302
- const err2 = gen.name("err");
1302
+ const err3 = gen.name("err");
1303
1303
  gen.forRange("i", errsCount, names_1.default.errors, (i) => {
1304
- gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
1305
- gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
1306
- gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
1304
+ gen.const(err3, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
1305
+ gen.if((0, codegen_1._)`${err3}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err3}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
1306
+ gen.assign((0, codegen_1._)`${err3}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
1307
1307
  if (it.opts.verbose) {
1308
- gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue);
1309
- gen.assign((0, codegen_1._)`${err2}.data`, data);
1308
+ gen.assign((0, codegen_1._)`${err3}.schema`, schemaValue);
1309
+ gen.assign((0, codegen_1._)`${err3}.data`, data);
1310
1310
  }
1311
1311
  });
1312
1312
  }
1313
1313
  exports2.extendErrors = extendErrors;
1314
1314
  function addError(gen, errObj) {
1315
- const err2 = gen.const("err", errObj);
1316
- gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`);
1315
+ const err3 = gen.const("err", errObj);
1316
+ gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err3}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err3})`);
1317
1317
  gen.code((0, codegen_1._)`${names_1.default.errors}++`);
1318
1318
  }
1319
1319
  function returnErrors(it, errs) {
@@ -7541,8 +7541,8 @@ var ZodType = class {
7541
7541
  } : {
7542
7542
  issues: ctx.common.issues
7543
7543
  };
7544
- } catch (err2) {
7545
- if (err2?.message?.toLowerCase()?.includes("encountered")) {
7544
+ } catch (err3) {
7545
+ if (err3?.message?.toLowerCase()?.includes("encountered")) {
7546
7546
  this["~standard"].async = true;
7547
7547
  }
7548
7548
  ctx.common = {
@@ -21243,16 +21243,16 @@ var handleFetchError = (e) => new Response(null, {
21243
21243
  status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
21244
21244
  });
21245
21245
  var handleResponseError = (e, outgoing) => {
21246
- const err2 = e instanceof Error ? e : new Error("unknown error", { cause: e });
21247
- if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
21246
+ const err3 = e instanceof Error ? e : new Error("unknown error", { cause: e });
21247
+ if (err3.code === "ERR_STREAM_PREMATURE_CLOSE") {
21248
21248
  console.info("The user aborted a request.");
21249
21249
  } else {
21250
21250
  console.error(e);
21251
21251
  if (!outgoing.headersSent) {
21252
21252
  outgoing.writeHead(500, { "Content-Type": "text/plain" });
21253
21253
  }
21254
- outgoing.end(`Error: ${err2.message}`);
21255
- outgoing.destroy(err2);
21254
+ outgoing.end(`Error: ${err3.message}`);
21255
+ outgoing.destroy(err3);
21256
21256
  }
21257
21257
  };
21258
21258
  var flushHeaders = (outgoing) => {
@@ -21309,8 +21309,8 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
21309
21309
  if (options.errorHandler) {
21310
21310
  try {
21311
21311
  res = await res;
21312
- } catch (err2) {
21313
- const errRes = await options.errorHandler(err2);
21312
+ } catch (err3) {
21313
+ const errRes = await options.errorHandler(err3);
21314
21314
  if (!errRes) {
21315
21315
  return;
21316
21316
  }
@@ -22264,6 +22264,10 @@ function projectPath(ctx, suffix = "") {
22264
22264
  const base = ctx.serverUrl.replace(/\/$/, "");
22265
22265
  return `${base}/api/workspaces/${ctx.workspaceId}/projects/${ctx.projectId}${suffix}`;
22266
22266
  }
22267
+ function workspacePath(ctx, suffix = "") {
22268
+ const base = ctx.serverUrl.replace(/\/$/, "");
22269
+ return `${base}/api/workspaces/${ctx.workspaceId}${suffix}`;
22270
+ }
22267
22271
  async function request(ctx, method, url, body) {
22268
22272
  const res = await fetch(url, {
22269
22273
  method,
@@ -22359,7 +22363,7 @@ async function spawnAgent(ctx, agentKey, daemonId, role, cmd) {
22359
22363
  }
22360
22364
  async function killAgent(ctx, agentId) {
22361
22365
  const base = ctx.serverUrl.replace(/\/$/, "");
22362
- const url = `${base}/api/workspaces/${ctx.workspaceId}/projects/${ctx.projectId}/agents/${agentId}`;
22366
+ const url = ctx.projectId && ctx.projectId !== "workspace" ? `${base}/api/workspaces/${ctx.workspaceId}/projects/${ctx.projectId}/agents/${agentId}` : `${base}/api/workspaces/${ctx.workspaceId}/agents/${agentId}`;
22363
22367
  const res = await fetch(url, {
22364
22368
  method: "DELETE",
22365
22369
  headers: { "Authorization": `Bearer ${ctx.token}`, "Content-Type": "application/json" }
@@ -22653,6 +22657,81 @@ function registerMessagingTools(server, ctx) {
22653
22657
  );
22654
22658
  }
22655
22659
 
22660
+ // ../mcp-server/src/tools/workspace.ts
22661
+ function ok2(data) {
22662
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
22663
+ }
22664
+ function err2(message) {
22665
+ return { content: [{ type: "text", text: JSON.stringify({ ok: false, error: message }) }] };
22666
+ }
22667
+ async function safe2(fn) {
22668
+ try {
22669
+ return ok2(await fn());
22670
+ } catch (e) {
22671
+ const message = e instanceof Error ? e.message : String(e);
22672
+ if (e instanceof Error && (e.name === "TypeError" || e.name === "ReferenceError")) {
22673
+ console.error("[mcp-bridge] unexpected error in workspace tool handler", { name: e.name, message, stack: e.stack });
22674
+ }
22675
+ return err2(message);
22676
+ }
22677
+ }
22678
+ function registerWorkspaceTools(server, ctx) {
22679
+ server.tool(
22680
+ "bridge_list_groups",
22681
+ "List all agent groups (teams) in the workspace. Returns groupId, teamName (human-readable name if set), member agentIds, and agent count.",
22682
+ {},
22683
+ () => safe2(() => request(ctx, "GET", workspacePath(ctx, "/groups")))
22684
+ );
22685
+ server.tool(
22686
+ "bridge_get_group_status",
22687
+ "Get all agents in a group with their current status and last output line.",
22688
+ { groupId: external_exports.string().describe("The group ID to inspect") },
22689
+ ({ groupId }) => safe2(() => request(ctx, "GET", workspacePath(ctx, `/groups/${groupId}`)))
22690
+ );
22691
+ server.tool(
22692
+ "bridge_dispatch_to_group",
22693
+ "Send a text message or command to every agent in a group via PTY stdin.",
22694
+ {
22695
+ groupId: external_exports.string().describe("The target group ID"),
22696
+ text: external_exports.string().min(1).max(4096).describe("Text to send to all group members")
22697
+ },
22698
+ ({ groupId, text }) => safe2(() => request(ctx, "POST", workspacePath(ctx, `/groups/${groupId}/broadcast`), { text }))
22699
+ );
22700
+ server.tool(
22701
+ "bridge_list_workspace_projects",
22702
+ "List all projects in the workspace with name, cwd, and machineId.",
22703
+ {},
22704
+ () => safe2(() => request(ctx, "GET", workspacePath(ctx, "/projects")))
22705
+ );
22706
+ server.tool(
22707
+ "bridge_query_workspace",
22708
+ "Natural-language query about orchestration state (runs, todos, failures). No LLM involved \u2014 deterministic answer.",
22709
+ { q: external_exports.string().min(1).max(500).describe('Natural language query, e.g. "what failed last time?"') },
22710
+ ({ q }) => safe2(() => request(ctx, "GET", workspacePath(ctx, `/orchestration/query?q=${encodeURIComponent(q)}`)))
22711
+ );
22712
+ server.tool(
22713
+ "bridge_list_active_runs",
22714
+ "All active orchestration runs across workspace projects with todo progress.",
22715
+ {},
22716
+ () => safe2(() => request(ctx, "GET", workspacePath(ctx, "/runs/active")))
22717
+ );
22718
+ server.tool(
22719
+ "bridge_peek_panel",
22720
+ "Read the last N lines of any panel's terminal output, workspace-wide (no project boundary). Use this to check what a specific agent is doing.",
22721
+ {
22722
+ agentId: external_exports.string().describe("The panel/agent ID to peek at"),
22723
+ lines: external_exports.number().int().min(1).max(300).optional().describe("Trailing lines to return (default 50, max 300)")
22724
+ },
22725
+ ({ agentId, lines }) => safe2(() => request(ctx, "GET", workspacePath(ctx, `/agents/${agentId}/output${lines !== void 0 ? `?lines=${lines}` : ""}`)))
22726
+ );
22727
+ server.tool(
22728
+ "bridge_status_panel",
22729
+ "Get current status of any panel in the workspace, regardless of project. Returns agentKey, status, daemonId, role, projectId.",
22730
+ { agentId: external_exports.string().describe("The panel/agent ID to inspect") },
22731
+ ({ agentId }) => safe2(() => request(ctx, "GET", workspacePath(ctx, `/agents/${agentId}`)))
22732
+ );
22733
+ }
22734
+
22656
22735
  // ../mcp-server/src/index.ts
22657
22736
  var sessions = /* @__PURE__ */ new Map();
22658
22737
  function buildMcpServer(ctx) {
@@ -22661,6 +22740,7 @@ function buildMcpServer(ctx) {
22661
22740
  registerTodoTools(srv, ctx);
22662
22741
  registerOrchestrationTools(srv, ctx);
22663
22742
  registerMessagingTools(srv, ctx);
22743
+ registerWorkspaceTools(srv, ctx);
22664
22744
  return srv;
22665
22745
  }
22666
22746
  async function parseBody(req) {
@@ -22733,9 +22813,21 @@ function startHttpServer() {
22733
22813
  return;
22734
22814
  }
22735
22815
  if (!preflight.ok) {
22736
- res.writeHead(preflight.status, { "Content-Type": "application/json" });
22737
- res.end(JSON.stringify({ error: "Project not found or server error" }));
22738
- return;
22816
+ if (projectId === "workspace" && preflight.status === 404) {
22817
+ const wsPreflight = await fetch(
22818
+ `${bridgeServerUrl.replace(/\/$/, "")}/api/workspaces/${workspaceId}`,
22819
+ { headers: { Authorization: `Bearer ${token}` } }
22820
+ ).catch(() => null);
22821
+ if (!wsPreflight?.ok) {
22822
+ res.writeHead(wsPreflight?.status ?? 500, { "Content-Type": "application/json" });
22823
+ res.end(JSON.stringify({ error: "Workspace not found or server error" }));
22824
+ return;
22825
+ }
22826
+ } else {
22827
+ res.writeHead(preflight.status, { "Content-Type": "application/json" });
22828
+ res.end(JSON.stringify({ error: "Project not found or server error" }));
22829
+ return;
22830
+ }
22739
22831
  }
22740
22832
  const agentId = (req.headers["x-panel-id"] ?? "") || void 0;
22741
22833
  const ctx = { serverUrl: bridgeServerUrl, token, workspaceId, projectId, agentId };
@@ -22752,8 +22844,8 @@ function startHttpServer() {
22752
22844
  const mcpServer = buildMcpServer(ctx);
22753
22845
  await mcpServer.connect(transport);
22754
22846
  await transport.handleRequest(req, res, body);
22755
- } catch (err2) {
22756
- console.error("[bridge-mcp] request error:", err2);
22847
+ } catch (err3) {
22848
+ console.error("[bridge-mcp] request error:", err3);
22757
22849
  if (!res.headersSent) {
22758
22850
  res.writeHead(500, { "Content-Type": "application/json" });
22759
22851
  res.end(JSON.stringify({ error: "Internal server error" }));
@@ -22787,8 +22879,8 @@ async function startStdioServer() {
22787
22879
  if (process.env["HTTP_MODE"] !== "false") {
22788
22880
  startHttpServer();
22789
22881
  } else {
22790
- startStdioServer().catch((err2) => {
22791
- console.error("[bridge-mcp] fatal:", err2);
22882
+ startStdioServer().catch((err3) => {
22883
+ console.error("[bridge-mcp] fatal:", err3);
22792
22884
  process.exit(1);
22793
22885
  });
22794
22886
  }
package/dist/index.js CHANGED
@@ -1,46 +1,46 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var js=Object.create;var gt=Object.defineProperty;var Ls=Object.getOwnPropertyDescriptor;var Ms=Object.getOwnPropertyNames;var $s=Object.getPrototypeOf,Bs=Object.prototype.hasOwnProperty;var Us=(r,e)=>()=>(r&&(e=r(r=0)),e);var k=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ws=(r,e)=>{for(var t in e)gt(r,t,{get:e[t],enumerable:!0})},Fs=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ms(e))!Bs.call(r,s)&&s!==t&&gt(r,s,{get:()=>e[s],enumerable:!(n=Ls(e,s))||n.enumerable});return r};var _=(r,e,t)=>(t=r!=null?js($s(r)):{},Fs(e||!r||!r.__esModule?gt(t,"default",{value:r,enumerable:!0}):t,r));var ke=k(_t=>{var Ue=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},mt=class extends Ue{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};_t.CommanderError=Ue;_t.InvalidArgumentError=mt});var We=k(bt=>{var{InvalidArgumentError:Hs}=ke(),yt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Hs(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function qs(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}bt.Argument=yt;bt.humanReadableArgName=qs});var St=k(yr=>{var{humanReadableArgName:Vs}=We(),wt=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Vs(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function l(p,f){if(f){let m=`${p.padEnd(n+o)}${f}`;return t.wrap(m,s-i,n+o)}return p}function a(p){return p.join(`
3
- `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,s,0),""]));let u=t.visibleArguments(e).map(p=>l(t.argumentTerm(p),t.argumentDescription(p)));u.length>0&&(c=c.concat(["Arguments:",a(u),""]));let h=t.visibleOptions(e).map(p=>l(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(c=c.concat(["Options:",a(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(f=>l(t.optionTerm(f),t.optionDescription(f)));p.length>0&&(c=c.concat(["Global Options:",a(p),""]))}let g=t.visibleCommands(e).map(p=>l(t.subcommandTerm(p),t.subcommandDescription(p)));return g.length>0&&(c=c.concat(["Commands:",a(g),""])),c.join(`
4
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let l=t-n;if(l<s)return e;let a=e.slice(0,n),c=e.slice(n).replace(`\r
2
+ "use strict";var qs=Object.create;var Et=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Vs=Object.getOwnPropertyNames;var Ks=Object.getPrototypeOf,Js=Object.prototype.hasOwnProperty;var Or=(r,e)=>()=>(r&&(e=r(r=0)),e);var O=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ys=(r,e)=>{for(var t in e)Et(r,t,{get:e[t],enumerable:!0})},zs=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vs(e))!Js.call(r,s)&&s!==t&&Et(r,s,{get:()=>e[s],enumerable:!(n=Hs(e,s))||n.enumerable});return r};var _=(r,e,t)=>(t=r!=null?qs(Ks(r)):{},zs(e||!r||!r.__esModule?Et(t,"default",{value:r,enumerable:!0}):t,r));var Oe=O(xt=>{var Ge=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},kt=class extends Ge{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};xt.CommanderError=Ge;xt.InvalidArgumentError=kt});var qe=O(It=>{var{InvalidArgumentError:Xs}=Oe(),Ot=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Xs(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Qs(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}It.Argument=Ot;It.humanReadableArgName=Qs});var At=O(Ir=>{var{humanReadableArgName:Zs}=qe(),Ct=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>Zs(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function c(h,f){if(f){let m=`${h.padEnd(n+o)}${f}`;return t.wrap(m,s-i,n+o)}return h}function a(h){return h.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let u=t.visibleArguments(e).map(h=>c(t.argumentTerm(h),t.argumentDescription(h)));u.length>0&&(l=l.concat(["Arguments:",a(u),""]));let p=t.visibleOptions(e).map(h=>c(t.optionTerm(h),t.optionDescription(h)));if(p.length>0&&(l=l.concat(["Options:",a(p),""])),this.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(f=>c(t.optionTerm(f),t.optionDescription(f)));h.length>0&&(l=l.concat(["Global Options:",a(h),""]))}let g=t.visibleCommands(e).map(h=>c(t.subcommandTerm(h),t.subcommandDescription(h)));return g.length>0&&(l=l.concat(["Commands:",a(g),""])),l.join(`
4
+ `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let c=t-n;if(c<s)return e;let a=e.slice(0,n),l=e.slice(n).replace(`\r
5
5
  `,`
6
- `),d=" ".repeat(n),h="\\s\u200B",g=new RegExp(`
7
- |.{1,${l-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=c.match(g)||[];return a+p.map((f,m)=>f===`
6
+ `),d=" ".repeat(n),p="\\s\u200B",g=new RegExp(`
7
+ |.{1,${c-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),h=l.match(g)||[];return a+h.map((f,m)=>f===`
8
8
  `?"":(m>0?d:"")+f.trimEnd()).join(`
9
- `)}};yr.Help=wt});var kt=k(xt=>{var{InvalidArgumentError:Gs}=ke(),Et=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ys(e);this.short=n.shortFlag,this.long=n.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(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Gs(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Ks(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},vt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Ks(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ys(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}xt.Option=Et;xt.DualOptions=vt});var wr=k(br=>{function Js(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function zs(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let l=Js(r,o),a=Math.max(r.length,o.length);(a-l)/a>i&&(l<s?(s=l,n=[o]):l===s&&n.push(o))}),n.sort((o,l)=>o.localeCompare(l)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
9
+ `)}};Ir.Help=Ct});var Dt=O(Nt=>{var{InvalidArgumentError:ei}=Oe(),Pt=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=ri(e);this.short=n.shortFlag,this.long=n.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(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new ei(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ti(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function ti(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ri(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Nt.Option=Pt;Nt.DualOptions=Tt});var Ar=O(Cr=>{function ni(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function si(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let c=ni(r,o),a=Math.max(r.length,o.length);(a-c)/a>i&&(c<s?(s=c,n=[o]):c===s&&n.push(o))}),n.sort((o,c)=>o.localeCompare(c)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
10
10
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
11
- (Did you mean ${n[0]}?)`:""}br.suggestSimilar=zs});var kr=k(xr=>{var Xs=require("node:events").EventEmitter,Ot=require("node:child_process"),H=require("node:path"),Ct=require("node:fs"),O=require("node:process"),{Argument:Qs,humanReadableArgName:Zs}=We(),{CommanderError:It}=ke(),{Help:ei}=St(),{Option:Sr,DualOptions:ti}=kt(),{suggestSimilar:Er}=wr(),At=class r extends Xs{constructor(e){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=e||"",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:t=>O.stdout.write(t),writeErr:t=>O.stderr.write(t),getOutHelpWidth:()=>O.stdout.isTTY?O.stdout.columns:void 0,getErrHelpWidth:()=>O.stderr.isTTY?O.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new ei,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Qs(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new It(e,t,n)),O.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Sr(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,l)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof Sr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(a,c)=>{let d=l.exec(a);return d?d[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){O.versions?.electron&&(t.from="electron");let s=O.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=O.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":O.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let h=H.resolve(d,u);if(Ct.existsSync(h))return h;if(s.includes(H.extname(u)))return;let g=s.find(p=>Ct.existsSync(`${h}${p}`));if(g)return`${h}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let d;try{d=Ct.realpathSync(this._scriptPath)}catch{d=this._scriptPath}l=H.resolve(H.dirname(d),l)}if(l){let d=i(l,o);if(!d&&!e._executableFile&&this._scriptPath){let u=H.basename(this._scriptPath,H.extname(this._scriptPath));u!==this._name&&(d=i(l,`${u}-${e._name}`))}o=d||o}n=s.includes(H.extname(o));let a;O.platform!=="win32"?n?(t.unshift(o),t=vr(O.execArgv).concat(t),a=Ot.spawn(O.argv[0],t,{stdio:"inherit"})):a=Ot.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=vr(O.execArgv).concat(t),a=Ot.spawn(O.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{O.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let c=this._exitCallback;a.on("close",d=>{d=d??1,c?c(new It(d,"commander.executeSubCommandAsync","(close)")):O.exit(d)}),a.on("error",d=>{if(d.code==="ENOENT"){let u=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
11
+ (Did you mean ${n[0]}?)`:""}Cr.suggestSimilar=si});var Rr=O(Dr=>{var ii=require("node:events").EventEmitter,Rt=require("node:child_process"),q=require("node:path"),Lt=require("node:fs"),I=require("node:process"),{Argument:oi,humanReadableArgName:ai}=qe(),{CommanderError:jt}=Oe(),{Help:ci}=At(),{Option:Pr,DualOptions:li}=Dt(),{suggestSimilar:Tr}=Ar(),Mt=class r extends ii{constructor(e){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=e||"",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:t=>I.stdout.write(t),writeErr:t=>I.stderr.write(t),getOutHelpWidth:()=>I.stdout.isTTY?I.stdout.columns:void 0,getErrHelpWidth:()=>I.stderr.isTTY?I.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,c]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,c&&a.arguments(c),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new ci,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new oi(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new jt(e,t,n)),I.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Pr(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,c)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof Pr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let c=s;s=(a,l)=>{let d=c.exec(a);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){I.versions?.electron&&(t.from="electron");let s=I.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=I.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":I.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let p=q.resolve(d,u);if(Lt.existsSync(p))return p;if(s.includes(q.extname(u)))return;let g=s.find(h=>Lt.existsSync(`${p}${h}`));if(g)return`${p}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let d;try{d=Lt.realpathSync(this._scriptPath)}catch{d=this._scriptPath}c=q.resolve(q.dirname(d),c)}if(c){let d=i(c,o);if(!d&&!e._executableFile&&this._scriptPath){let u=q.basename(this._scriptPath,q.extname(this._scriptPath));u!==this._name&&(d=i(c,`${u}-${e._name}`))}o=d||o}n=s.includes(q.extname(o));let a;I.platform!=="win32"?n?(t.unshift(o),t=Nr(I.execArgv).concat(t),a=Rt.spawn(I.argv[0],t,{stdio:"inherit"})):a=Rt.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Nr(I.execArgv).concat(t),a=Rt.spawn(I.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{I.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let l=this._exitCallback;a.on("close",d=>{d=d??1,l?l(new jt(d,"commander.executeSubCommandAsync","(close)")):I.exit(d)}),a.on("error",d=>{if(d.code==="ENOENT"){let u=c?`searched for local subcommand relative to directory '${c}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)O.exit(1);else{let u=new It(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,c(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,l)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,l)=>e(n,l,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let l=null;for(;i.length;){let a=i.shift();if(a==="--"){s===n&&s.push(a),s.push(...i);break}if(l&&!o(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,o(a)){let c=this._findOption(a);if(c){if(c.required){let d=i.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),d=this._findOption(a.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,a.slice(c+1));continue}}if(o(a)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(a),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(a),i.length>0&&s.push(...i);break}s.push(a)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${u}`;throw new Error(p)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)I.exit(1);else{let u=new jt(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,c)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,c)=>e(n,c,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let c=null;for(;i.length;){let a=i.shift();if(a==="--"){s===n&&s.push(a),s.push(...i);break}if(c&&!o(a)){this.emit(`option:${c.name()}`,a);continue}if(c=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),d=this._findOption(a.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,a.slice(l+1));continue}}if(o(a)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(a),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(a),i.length>0&&s.push(...i);break}s.push(a)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in O.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,O.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ti(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let l=o.attributeName(),a=this.getOptionValue(l),c=this.options.find(u=>u.negate&&l===u.attributeName()),d=this.options.find(u=>!u.negate&&l===u.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:d||o},s=o=>{let l=n(o),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Er(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Er(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Zs(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=H.basename(e,H.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=O.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
20
+ `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in I.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,I.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new li(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let c=o.attributeName(),a=this.getOptionValue(c),l=this.options.find(u=>u.negate&&c===u.attributeName()),d=this.options.find(u=>!u.negate&&c===u.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:d||o},s=o=>{let c=n(o),a=c.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Tr(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Tr(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>ai(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=q.basename(e,q.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=I.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function vr(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}xr.Command=At});var Ar=k(j=>{var{Argument:Or}=We(),{Command:Pt}=kr(),{CommanderError:ri,InvalidArgumentError:Cr}=ke(),{Help:ni}=St(),{Option:Ir}=kt();j.program=new Pt;j.createCommand=r=>new Pt(r);j.createOption=(r,e)=>new Ir(r,e);j.createArgument=(r,e)=>new Or(r,e);j.Command=Pt;j.Option=Ir;j.Argument=Or;j.Help=ni;j.CommanderError=ri;j.InvalidArgumentError=Cr;j.InvalidOptionArgumentError=Cr});var Mr=k(I=>{"use strict";var Tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),si=Tt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=async(l,a={})=>{let{ignoreErrors:c=!1}=a;try{return i(await(0,t.stat)(l),a)}catch(d){let u=d;if(c||u.code==="EACCES")return!1;throw u}};r.isexe=n;var s=(l,a={})=>{let{ignoreErrors:c=!1}=a;try{return i((0,e.statSync)(l),a)}catch(d){let u=d;if(c||u.code==="EACCES")return!1;throw u}};r.sync=s;var i=(l,a)=>l.isFile()&&o(l,a),o=(l,a)=>{let c=a.uid??process.getuid?.(),d=a.groups??process.getgroups?.()??[],u=a.gid??process.getgid?.()??d[0];if(c===void 0||u===void 0)throw new Error("cannot get uid or gid");let h=new Set([u,...d]),g=l.mode,p=l.uid,f=l.gid,m=parseInt("100",8),x=parseInt("010",8),b=parseInt("001",8),T=m|x;return!!(g&b||g&x&&h.has(f)||g&m&&p===c||g&T&&c===0)}}),ii=Tt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=require("node:path"),s=async(a,c={})=>{let{ignoreErrors:d=!1}=c;try{return l(await(0,t.stat)(a),a,c)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.isexe=s;var i=(a,c={})=>{let{ignoreErrors:d=!1}=c;try{return l((0,e.statSync)(a),a,c)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.sync=i;var o=(a,c)=>{let{pathExt:d=process.env.PATHEXT||""}=c,u=d.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let h of u){let g=h.toLowerCase(),p=a.substring(a.length-g.length).toLowerCase();if(g&&p===g)return!0}return!1},l=(a,c,d)=>a.isFile()&&o(c,d)}),oi=Tt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),Nr=I&&I.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),ai=I&&I.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Rr=I&&I.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Nr(t,e,n[s]);return ai(t,e),t}})(),ci=I&&I.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Nr(e,r,t)};Object.defineProperty(I,"__esModule",{value:!0});I.sync=I.isexe=I.posix=I.win32=void 0;var Dr=Rr(si());I.posix=Dr;var jr=Rr(ii());I.win32=jr;ci(oi(),I);var li=process.env._ISEXE_TEST_PLATFORM_||process.platform,Lr=li==="win32"?jr:Dr;I.isexe=Lr.isexe;I.sync=Lr.sync});var Kr=k((ic,Gr)=>{var{isexe:di,sync:ui}=Mr(),{join:hi,delimiter:fi,sep:$r,posix:Br}=require("path"),Ur=process.platform==="win32",Wr=new RegExp(`[${Br.sep}${$r===Br.sep?"":$r}]`.replace(/(\\)/g,"\\$1")),pi=new RegExp(`^\\.${Wr.source}`),Fr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Hr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=fi})=>{let s=r.match(Wr)?[""]:[...Ur?[process.cwd()]:[],...(e||"").split(n)];if(Ur){let i=t||[".EXE",".CMD",".BAT",".COM"].join(n),o=i.split(n).flatMap(l=>[l,l.toLowerCase()]);return r.includes(".")&&o[0]!==""&&o.unshift(""),{pathEnv:s,pathExt:o,pathExtExe:i}}return{pathEnv:s,pathExt:[""]}},qr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&pi.test(e)?e.slice(0,2):"")+hi(t,e)},Vr=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Hr(r,e),i=[];for(let o of t){let l=qr(o,r);for(let a of n){let c=l+a;if(await di(c,{pathExt:s,ignoreErrors:!0})){if(!e.all)return c;i.push(c)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Fr(r)},gi=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Hr(r,e),i=[];for(let o of t){let l=qr(o,r);for(let a of n){let c=l+a;if(ui(c,{pathExt:s,ignoreErrors:!0})){if(!e.all)return c;i.push(c)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Fr(r)};Gr.exports=Vr;Vr.sync=gi});var q=k((lc,en)=>{"use strict";var Qr=["nodebuffer","arraybuffer","fragments"],Zr=typeof Blob<"u";Zr&&Qr.push("blob");en.exports={BINARY_TYPES:Qr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ce=k((dc,Ge)=>{"use strict";var{EMPTY_BUFFER:bi}=q(),jt=Buffer[Symbol.species];function wi(r,e){if(r.length===0)return bi;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new jt(t.buffer,t.byteOffset,n):t}function tn(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function rn(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Si(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Lt(r){if(Lt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new jt(r):ArrayBuffer.isView(r)?e=new jt(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Lt.readOnly=!1),e}Ge.exports={concat:wi,mask:tn,toArrayBuffer:Si,toBuffer:Lt,unmask:rn};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Ge.exports.mask=function(e,t,n,s,i){i<48?tn(e,t,n,s,i):r.mask(e,t,n,s,i)},Ge.exports.unmask=function(e,t){e.length<32?rn(e,t):r.unmask(e,t)}}catch{}});var on=k((uc,sn)=>{"use strict";var nn=Symbol("kDone"),Mt=Symbol("kRun"),$t=class{constructor(e){this[nn]=()=>{this.pending--,this[Mt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Mt]()}[Mt](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nn])}}};sn.exports=$t});var me=k((hc,dn)=>{"use strict";var Ie=require("zlib"),an=Ce(),Ei=on(),{kStatusCode:cn}=q(),vi=Buffer[Symbol.species],xi=Buffer.from([0,0,255,255]),Ye=Symbol("permessage-deflate"),V=Symbol("total-length"),pe=Symbol("callback"),z=Symbol("buffers"),ge=Symbol("error"),Ke,Bt=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ke){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ke=new Ei(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[pe];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Ke.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Ke.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ie.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ie.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ye]=this,this._inflate[V]=0,this._inflate[z]=[],this._inflate.on("error",Oi),this._inflate.on("data",ln)}this._inflate[pe]=n,this._inflate.write(e),t&&this._inflate.write(xi),this._inflate.flush(()=>{let i=this._inflate[ge];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=an.concat(this._inflate[z],this._inflate[V]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[V]=0,this._inflate[z]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ie.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ie.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[V]=0,this._deflate[z]=[],this._deflate.on("data",ki)}this._deflate[pe]=n,this._deflate.write(e),this._deflate.flush(Ie.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=an.concat(this._deflate[z],this._deflate[V]);t&&(i=new vi(i.buffer,i.byteOffset,i.length-4)),this._deflate[pe]=null,this._deflate[V]=0,this._deflate[z]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};dn.exports=Bt;function ki(r){this[z].push(r),this[V]+=r.length}function ln(r){if(this[V]+=r.length,this[Ye]._maxPayload<1||this[V]<=this[Ye]._maxPayload){this[z].push(r);return}this[ge]=new RangeError("Max payload size exceeded"),this[ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ge][cn]=1009,this.removeListener("data",ln),this.reset()}function Oi(r){if(this[Ye]._inflate=null,this[ge]){this[pe](this[ge]);return}r[cn]=1007,this[pe](r)}});var _e=k((fc,Je)=>{"use strict";var{isUtf8:un}=require("buffer"),{hasBlob:Ci}=q(),Ii=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Ai(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ut(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Pi(r){return Ci&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Je.exports={isBlob:Pi,isValidStatusCode:Ai,isValidUTF8:Ut,tokenChars:Ii};if(un)Je.exports.isValidUTF8=function(r){return r.length<24?Ut(r):un(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Je.exports.isValidUTF8=function(e){return e.length<32?Ut(e):r(e)}}catch{}});var Vt=k((pc,yn)=>{"use strict";var{Writable:Ti}=require("stream"),hn=me(),{BINARY_TYPES:Ni,EMPTY_BUFFER:fn,kStatusCode:Ri,kWebSocket:Di}=q(),{concat:Wt,toArrayBuffer:ji,unmask:Li}=Ce(),{isValidStatusCode:Mi,isValidUTF8:pn}=_e(),ze=Buffer[Symbol.species],L=0,gn=1,mn=2,_n=3,Ft=4,Ht=5,Xe=6,qt=class extends Ti{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ni[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Di]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=L}_write(e,t,n){if(this._opcode===8&&this._state==L)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new ze(n.buffer,n.byteOffset+e,n.length-e),new ze(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new ze(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case L:this.getInfo(e);break;case gn:this.getPayloadLength16(e);break;case mn:this.getPayloadLength64(e);break;case _n:this.getMask();break;case Ft:this.getData(e);break;case Ht:case Xe:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[hn.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=gn:this._payloadLength===127?this._state=mn:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_n:this._state=Ft}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ft}getData(e){let t=fn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Li(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Ht,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[hn.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===L&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=L;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Wt(n,t):this._binaryType==="arraybuffer"?s=ji(Wt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=L):(this._state=Xe,setImmediate(()=>{this.emit("message",s,!0),this._state=L,this.startLoop(e)}))}else{let s=Wt(n,t);if(!this._skipUTF8Validation&&!pn(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ht||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=L):(this._state=Xe,setImmediate(()=>{this.emit("message",s,!1),this._state=L,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fn),this.end();else{let n=e.readUInt16BE(0);if(!Mi(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new ze(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!pn(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=L;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=L):(this._state=Xe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=L,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Ri]=s,o}};yn.exports=qt});var Yt=k((mc,Sn)=>{"use strict";var{Duplex:gc}=require("stream"),{randomFillSync:$i}=require("crypto"),bn=me(),{EMPTY_BUFFER:Bi,kWebSocket:Ui,NOOP:Wi}=q(),{isBlob:ye,isValidStatusCode:Fi}=_e(),{mask:wn,toBuffer:ee}=Ce(),M=Symbol("kByteLength"),Hi=Buffer.alloc(4),Qe=8*1024,te,be=Qe,B=0,qi=1,Vi=2,Gt=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=B,this.onerror=Wi,this[Ui]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Hi,t.generateMask?t.generateMask(n):(be===Qe&&(te===void 0&&(te=Buffer.alloc(Qe)),$i(te,0,Qe),be=0),n[0]=te[be++],n[1]=te[be++],n[2]=te[be++],n[3]=te[be++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let l;typeof e=="string"?(!t.mask||o)&&t[M]!==void 0?l=t[M]:(e=Buffer.from(e),l=e.length):(l=e.length,s=t.mask&&t.readOnly&&!o);let a=l;l>=65536?(i+=8,a=127):l>125&&(i+=2,a=126);let c=Buffer.allocUnsafe(s?l+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,a===126?c.writeUInt16BE(l,2):a===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),t.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(wn(e,n,c,i,l),[c]):(wn(e,n,e,0,l),[c,e])):[c,e]}close(e,t,n,s){let i;if(e===void 0)i=Bi;else{if(typeof e!="number"||!Fi(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(t);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[M]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==B?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ye(e)?(s=e.size,i=!1):(e=ee(e),s=e.length,i=ee.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[M]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ye(e)?this._state!==B?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==B?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ye(e)?(s=e.size,i=!1):(e=ee(e),s=e.length,i=ee.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[M]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ye(e)?this._state!==B?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==B?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[bn.extensionName],i=t.binary?2:1,o=t.compress,l,a;typeof e=="string"?(l=Buffer.byteLength(e),a=!1):ye(e)?(l=e.size,a=!1):(e=ee(e),l=e.length,a=ee.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[M]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};ye(e)?this._state!==B?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==B?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[M],this._state=Vi,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Kt,this,l,s);return}this._bufferedBytes-=n[M];let o=ee(i);t?this.dispatch(o,t,n,s):(this._state=B,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Gi,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[bn.extensionName];this._bufferedBytes+=n[M],this._state=qi,i.compress(e,n.fin,(o,l)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");Kt(this,a,s);return}this._bufferedBytes-=n[M],this._state=B,n.readOnly=!1,this.sendFrame(r.frame(l,n),s),this.dequeue()})}dequeue(){for(;this._state===B&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][M],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][M],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Sn.exports=Gt;function Kt(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Gi(r,e,t){Kt(r,e,t),r.onerror(e)}});var Pn=k((_c,An)=>{"use strict";var{kForOnEventAttribute:Ae,kListener:Jt}=q(),En=Symbol("kCode"),vn=Symbol("kData"),xn=Symbol("kError"),kn=Symbol("kMessage"),On=Symbol("kReason"),we=Symbol("kTarget"),Cn=Symbol("kType"),In=Symbol("kWasClean"),G=class{constructor(e){this[we]=null,this[Cn]=e}get target(){return this[we]}get type(){return this[Cn]}};Object.defineProperty(G.prototype,"target",{enumerable:!0});Object.defineProperty(G.prototype,"type",{enumerable:!0});var re=class extends G{constructor(e,t={}){super(e),this[En]=t.code===void 0?0:t.code,this[On]=t.reason===void 0?"":t.reason,this[In]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[En]}get reason(){return this[On]}get wasClean(){return this[In]}};Object.defineProperty(re.prototype,"code",{enumerable:!0});Object.defineProperty(re.prototype,"reason",{enumerable:!0});Object.defineProperty(re.prototype,"wasClean",{enumerable:!0});var Se=class extends G{constructor(e,t={}){super(e),this[xn]=t.error===void 0?null:t.error,this[kn]=t.message===void 0?"":t.message}get error(){return this[xn]}get message(){return this[kn]}};Object.defineProperty(Se.prototype,"error",{enumerable:!0});Object.defineProperty(Se.prototype,"message",{enumerable:!0});var Pe=class extends G{constructor(e,t={}){super(e),this[vn]=t.data===void 0?null:t.data}get data(){return this[vn]}};Object.defineProperty(Pe.prototype,"data",{enumerable:!0});var Ki={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Ae]&&s[Jt]===e&&!s[Ae])return;let n;if(r==="message")n=function(i,o){let l=new Pe("message",{data:o?i:i.toString()});l[we]=this,Ze(e,this,l)};else if(r==="close")n=function(i,o){let l=new re("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[we]=this,Ze(e,this,l)};else if(r==="error")n=function(i){let o=new Se("error",{error:i,message:i.message});o[we]=this,Ze(e,this,o)};else if(r==="open")n=function(){let i=new G("open");i[we]=this,Ze(e,this,i)};else return;n[Ae]=!!t[Ae],n[Jt]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Jt]===e&&!t[Ae]){this.removeListener(r,t);break}}};An.exports={CloseEvent:re,ErrorEvent:Se,Event:G,EventTarget:Ki,MessageEvent:Pe};function Ze(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var et=k((yc,Tn)=>{"use strict";var{tokenChars:Te}=_e();function W(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Yi(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,l,a=-1,c=-1,d=-1,u=0;for(;u<r.length;u++)if(c=r.charCodeAt(u),o===void 0)if(d===-1&&Te[c]===1)a===-1&&(a=u);else if(u!==0&&(c===32||c===9))d===-1&&a!==-1&&(d=u);else if(c===59||c===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);c===44?(W(e,g,t),t=Object.create(null)):o=g,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===void 0)if(d===-1&&Te[c]===1)a===-1&&(a=u);else if(c===32||c===9)d===-1&&a!==-1&&(d=u);else if(c===59||c===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),W(t,r.slice(a,d),!0),c===44&&(W(e,o,t),t=Object.create(null),o=void 0),a=d=-1}else if(c===61&&a!==-1&&d===-1)l=r.slice(a,u),a=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Te[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Te[c]===1)a===-1&&(a=u);else if(c===34&&a!==-1)i=!1,d=u;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Te[c]===1)a===-1&&(a=u);else if(a!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);n&&(g=g.replace(/\\/g,""),n=!1),W(t,l,g),c===44&&(W(e,o,t),t=Object.create(null),o=void 0),l=void 0,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(a===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=r.slice(a,d);return o===void 0?W(e,h,t):(l===void 0?W(t,h,!0):n?W(t,l,h.replace(/\\/g,"")):W(t,l,h),W(e,o,t)),e}function Ji(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Tn.exports={format:Ji,parse:Yi}});var st=k((Sc,Hn)=>{"use strict";var zi=require("events"),Xi=require("https"),Qi=require("http"),Dn=require("net"),Zi=require("tls"),{randomBytes:eo,createHash:to}=require("crypto"),{Duplex:bc,Readable:wc}=require("stream"),{URL:zt}=require("url"),X=me(),ro=Vt(),no=Yt(),{isBlob:so}=_e(),{BINARY_TYPES:Nn,CLOSE_TIMEOUT:io,EMPTY_BUFFER:tt,GUID:oo,kForOnEventAttribute:Xt,kListener:ao,kStatusCode:co,kWebSocket:A,NOOP:jn}=q(),{EventTarget:{addEventListener:lo,removeEventListener:uo}}=Pn(),{format:ho,parse:fo}=et(),{toBuffer:po}=Ce(),Ln=Symbol("kAborted"),Qt=[8,13],K=["CONNECTING","OPEN","CLOSING","CLOSED"],go=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,v=class r extends zi{constructor(e,t,n){super(),this._binaryType=Nn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=tt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Mn(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Nn.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new ro({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new no(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",yo),s.on("drain",bo),s.on("error",wo),s.on("message",So),s.on("ping",Eo),s.on("pong",vo),i.onerror=xo,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Un),e.on("data",nt),e.on("end",Wn),e.on("error",Fn),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[X.extensionName]&&this._extensions[X.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){R(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Bn(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Zt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||tt,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Zt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||tt,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Zt(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[X.extensionName]||(s.compress=!1),this._sender.send(e||tt,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){R(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(v,"CONNECTING",{enumerable:!0,value:K.indexOf("CONNECTING")});Object.defineProperty(v.prototype,"CONNECTING",{enumerable:!0,value:K.indexOf("CONNECTING")});Object.defineProperty(v,"OPEN",{enumerable:!0,value:K.indexOf("OPEN")});Object.defineProperty(v.prototype,"OPEN",{enumerable:!0,value:K.indexOf("OPEN")});Object.defineProperty(v,"CLOSING",{enumerable:!0,value:K.indexOf("CLOSING")});Object.defineProperty(v.prototype,"CLOSING",{enumerable:!0,value:K.indexOf("CLOSING")});Object.defineProperty(v,"CLOSED",{enumerable:!0,value:K.indexOf("CLOSED")});Object.defineProperty(v.prototype,"CLOSED",{enumerable:!0,value:K.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(v.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(v.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Xt])return e[ao];return null},set(e){for(let t of this.listeners(r))if(t[Xt]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Xt]:!0})}})});v.prototype.addEventListener=lo;v.prototype.removeEventListener=uo;Hn.exports=v;function Mn(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:io,protocolVersion:Qt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Qt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Qt.join(", ")})`);let i;if(e instanceof zt)i=e;else try{i=new zt(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",a;if(i.protocol!=="ws:"&&!o&&!l?a=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?a="The URL's pathname is empty":i.hash&&(a="The URL contains a fragment identifier"),a){let f=new SyntaxError(a);if(r._redirects===0)throw f;rt(r,f);return}let c=o?443:80,d=eo(16).toString("base64"),u=o?Xi.request:Qi.request,h=new Set,g;if(s.createConnection=s.createConnection||(o?_o:mo),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new X({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=ho({[X.extensionName]:g.offer()})),t.length){for(let f of t){if(typeof f!="string"||!go.test(f)||h.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(f)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let f=s.path.split(":");s.socketPath=f[0],s.path=f[1]}let p;if(s.followRedirects){if(r._redirects===0){r._originalIpc=l,r._originalSecure=o,r._originalHostOrSocketPath=l?s.socketPath:i.host;let f=n&&n.headers;if(n={...n,headers:{}},f)for(let[m,x]of Object.entries(f))n.headers[m.toLowerCase()]=x}else if(r.listenerCount("redirect")===0){let f=l?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!f||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,f||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=r._req=u(s),r._redirects&&r.emit("redirect",r.url,p)}else p=r._req=u(s);s.timeout&&p.on("timeout",()=>{R(r,p,"Opening handshake has timed out")}),p.on("error",f=>{p===null||p[Ln]||(p=r._req=null,rt(r,f))}),p.on("response",f=>{let m=f.headers.location,x=f.statusCode;if(m&&s.followRedirects&&x>=300&&x<400){if(++r._redirects>s.maxRedirects){R(r,p,"Maximum redirects exceeded");return}p.abort();let b;try{b=new zt(m,e)}catch{let y=new SyntaxError(`Invalid URL: ${m}`);rt(r,y);return}Mn(r,b,t,n)}else r.emit("unexpected-response",p,f)||R(r,p,`Unexpected server response: ${f.statusCode}`)}),p.on("upgrade",(f,m,x)=>{if(r.emit("upgrade",f),r.readyState!==v.CONNECTING)return;p=r._req=null;let b=f.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){R(r,m,"Invalid Upgrade header");return}let T=to("sha1").update(d+oo).digest("base64");if(f.headers["sec-websocket-accept"]!==T){R(r,m,"Invalid Sec-WebSocket-Accept header");return}let y=f.headers["sec-websocket-protocol"],w;if(y!==void 0?h.size?h.has(y)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":h.size&&(w="Server sent no subprotocol"),w){R(r,m,w);return}y&&(r._protocol=y);let S=f.headers["sec-websocket-extensions"];if(S!==void 0){if(!g){R(r,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=fo(S)}catch{R(r,m,"Invalid Sec-WebSocket-Extensions header");return}let E=Object.keys(N);if(E.length!==1||E[0]!==X.extensionName){R(r,m,"Server indicated an extension that was not requested");return}try{g.accept(N[X.extensionName])}catch{R(r,m,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[X.extensionName]=g}r.setSocket(m,x,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,r):p.end()}function rt(r,e){r._readyState=v.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function mo(r){return r.path=r.socketPath,Dn.connect(r)}function _o(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Dn.isIP(r.host)?"":r.host),Zi.connect(r)}function R(r,e,t){r._readyState=v.CLOSING;let n=new Error(t);Error.captureStackTrace(n,R),e.setHeader?(e[Ln]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(rt,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Zt(r,e,t){if(e){let n=so(e)?e.size:po(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${K[r.readyState]})`);process.nextTick(t,n)}}function yo(r,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[A]!==void 0&&(t._socket.removeListener("data",nt),process.nextTick($n,t._socket),r===1005?t.close():t.close(r,e))}function bo(){let r=this[A];r.isPaused||r._socket.resume()}function wo(r){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",nt),process.nextTick($n,e._socket),e.close(r[co])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Rn(){this[A].emitClose()}function So(r,e){this[A].emit("message",r,e)}function Eo(r){let e=this[A];e._autoPong&&e.pong(r,!this._isServer,jn),e.emit("ping",r)}function vo(r){this[A].emit("pong",r)}function $n(r){r.resume()}function xo(r){let e=this[A];e.readyState!==v.CLOSED&&(e.readyState===v.OPEN&&(e._readyState=v.CLOSING,Bn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Bn(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Un(){let r=this[A];if(this.removeListener("close",Un),this.removeListener("data",nt),this.removeListener("end",Wn),r._readyState=v.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[A]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Rn),r._receiver.on("finish",Rn))}function nt(r){this[A]._receiver.write(r)||this.pause()}function Wn(){let r=this[A];r._readyState=v.CLOSING,r._receiver.end(),this.end()}function Fn(){let r=this[A];this.removeListener("error",Fn),this.on("error",jn),r&&(r._readyState=v.CLOSING,this.destroy())}});var Kn=k((vc,Gn)=>{"use strict";var Ec=st(),{Duplex:ko}=require("stream");function qn(r){r.emit("close")}function Oo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vn(r){this.removeListener("error",Vn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Co(r,e){let t=!0,n=new ko({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let l=!o&&n._readableState.objectMode?i.toString():i;n.push(l)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(qn,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(qn,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Oo),n.on("error",Vn),n}Gn.exports=Co});var er=k((xc,Yn)=>{"use strict";var{tokenChars:Io}=_e();function Ao(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Io[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let l=r.slice(t,n);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Yn.exports={parse:Ao}});var ts=k((Oc,es)=>{"use strict";var Po=require("events"),it=require("http"),{Duplex:kc}=require("stream"),{createHash:To}=require("crypto"),Jn=et(),ne=me(),No=er(),Ro=st(),{CLOSE_TIMEOUT:Do,GUID:jo,kWebSocket:Lo}=q(),Mo=/^[+/0-9A-Za-z]{22}==$/,zn=0,Xn=1,Zn=2,tr=class extends Po{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Do,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ro,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=it.createServer((n,s)=>{let i=it.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=$o(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=zn}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Zn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ne,this);return}if(e&&this.once("close",e),this._state!==Xn)if(this._state=Xn,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ne,this):process.nextTick(Ne,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ne(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Qn);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){se(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){se(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Mo.test(i)){se(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){se(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Re(t,400);return}let a=e.headers["sec-websocket-protocol"],c=new Set;if(a!==void 0)try{c=No.parse(a)}catch{se(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new ne({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Jn.parse(d);g[ne.extensionName]&&(h.accept(g[ne.extensionName]),u[ne.extensionName]=h)}catch{se(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(g,p,f,m)=>{if(!g)return Re(t,p||401,f,m);this.completeUpgrade(u,i,c,e,t,n,s)});return}if(!this.options.verifyClient(h))return Re(t,401)}this.completeUpgrade(u,i,c,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[Lo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>zn)return Re(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${To("sha1").update(t+jo).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[ne.extensionName]){let u=e[ne.extensionName].params,h=Jn.format({[ne.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Nr(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}Dr.Command=Mt});var $r=O(M=>{var{Argument:Lr}=qe(),{Command:$t}=Rr(),{CommanderError:di,InvalidArgumentError:jr}=Oe(),{Help:ui}=At(),{Option:Mr}=Dt();M.program=new $t;M.createCommand=r=>new $t(r);M.createOption=(r,e)=>new Mr(r,e);M.createArgument=(r,e)=>new Lr(r,e);M.Command=$t;M.Option=Mr;M.Argument=Lr;M.Help=ui;M.CommanderError=di;M.InvalidArgumentError=jr;M.InvalidOptionArgumentError=jr});var Vr=O(P=>{"use strict";var Bt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),hi=Bt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=async(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i(await(0,t.stat)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.isexe=n;var s=(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i((0,e.statSync)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.sync=s;var i=(c,a)=>c.isFile()&&o(c,a),o=(c,a)=>{let l=a.uid??process.getuid?.(),d=a.groups??process.getgroups?.()??[],u=a.gid??process.getgid?.()??d[0];if(l===void 0||u===void 0)throw new Error("cannot get uid or gid");let p=new Set([u,...d]),g=c.mode,h=c.uid,f=c.gid,m=parseInt("100",8),k=parseInt("010",8),S=parseInt("001",8),N=m|k;return!!(g&S||g&k&&p.has(f)||g&m&&h===l||g&N&&l===0)}}),fi=Bt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=require("node:path"),s=async(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c(await(0,t.stat)(a),a,l)}catch(u){let p=u;if(d||p.code==="EACCES")return!1;throw p}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let p=u;if(d||p.code==="EACCES")return!1;throw p}};r.sync=i;var o=(a,l)=>{let{pathExt:d=process.env.PATHEXT||""}=l,u=d.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let p of u){let g=p.toLowerCase(),h=a.substring(a.length-g.length).toLowerCase();if(g&&h===g)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),pi=Bt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),Wr=P&&P.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),gi=P&&P.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Fr=P&&P.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&Wr(t,e,n[s]);return gi(t,e),t}})(),mi=P&&P.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Wr(e,r,t)};Object.defineProperty(P,"__esModule",{value:!0});P.sync=P.isexe=P.posix=P.win32=void 0;var Gr=Fr(hi());P.posix=Gr;var qr=Fr(fi());P.win32=qr;mi(pi(),P);var _i=process.env._ISEXE_TEST_PLATFORM_||process.platform,Hr=_i==="win32"?qr:Gr;P.isexe=Hr.isexe;P.sync=Hr.sync});var rn=O((pc,tn)=>{var{isexe:yi,sync:bi}=Vr(),{join:wi,delimiter:Si,sep:Kr,posix:Jr}=require("path"),Yr=process.platform==="win32",zr=new RegExp(`[${Jr.sep}${Kr===Jr.sep?"":Kr}]`.replace(/(\\)/g,"\\$1")),vi=new RegExp(`^\\.${zr.source}`),Xr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Qr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=Si})=>{let s=r.match(zr)?[""]:[...Yr?[process.cwd()]:[],...(e||"").split(n)];if(Yr){let i=t||[".EXE",".CMD",".BAT",".COM"].join(n),o=i.split(n).flatMap(c=>[c,c.toLowerCase()]);return r.includes(".")&&o[0]!==""&&o.unshift(""),{pathEnv:s,pathExt:o,pathExtExe:i}}return{pathEnv:s,pathExt:[""]}},Zr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&vi.test(e)?e.slice(0,2):"")+wi(t,e)},en=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Qr(r,e),i=[];for(let o of t){let c=Zr(o,r);for(let a of n){let l=c+a;if(await yi(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Xr(r)},Ei=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Qr(r,e),i=[];for(let o of t){let c=Zr(o,r);for(let a of n){let l=c+a;if(bi(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Xr(r)};tn.exports=en;en.sync=Ei});var H=O((yc,dn)=>{"use strict";var cn=["nodebuffer","arraybuffer","fragments"],ln=typeof Blob<"u";ln&&cn.push("blob");dn.exports={BINARY_TYPES:cn,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ln,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ce=O((bc,Ye)=>{"use strict";var{EMPTY_BUFFER:Ii}=H(),Gt=Buffer[Symbol.species];function Ci(r,e){if(r.length===0)return Ii;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Gt(t.buffer,t.byteOffset,n):t}function un(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function hn(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Ai(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function qt(r){if(qt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Gt(r):ArrayBuffer.isView(r)?e=new Gt(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),qt.readOnly=!1),e}Ye.exports={concat:Ci,mask:un,toArrayBuffer:Ai,toBuffer:qt,unmask:hn};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Ye.exports.mask=function(e,t,n,s,i){i<48?un(e,t,n,s,i):r.mask(e,t,n,s,i)},Ye.exports.unmask=function(e,t){e.length<32?hn(e,t):r.unmask(e,t)}}catch{}});var gn=O((wc,pn)=>{"use strict";var fn=Symbol("kDone"),Ht=Symbol("kRun"),Vt=class{constructor(e){this[fn]=()=>{this.pending--,this[Ht]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ht]()}[Ht](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[fn])}}};pn.exports=Vt});var ge=O((Sc,bn)=>{"use strict";var Ae=require("zlib"),mn=Ce(),Pi=gn(),{kStatusCode:_n}=H(),Ti=Buffer[Symbol.species],Ni=Buffer.from([0,0,255,255]),Xe=Symbol("permessage-deflate"),V=Symbol("total-length"),fe=Symbol("callback"),z=Symbol("buffers"),pe=Symbol("error"),ze,Kt=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ze){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ze=new Pi(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[fe];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){ze.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){ze.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ae.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ae.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Xe]=this,this._inflate[V]=0,this._inflate[z]=[],this._inflate.on("error",Ri),this._inflate.on("data",yn)}this._inflate[fe]=n,this._inflate.write(e),t&&this._inflate.write(Ni),this._inflate.flush(()=>{let i=this._inflate[pe];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=mn.concat(this._inflate[z],this._inflate[V]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[V]=0,this._inflate[z]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ae.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ae.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[V]=0,this._deflate[z]=[],this._deflate.on("data",Di)}this._deflate[fe]=n,this._deflate.write(e),this._deflate.flush(Ae.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=mn.concat(this._deflate[z],this._deflate[V]);t&&(i=new Ti(i.buffer,i.byteOffset,i.length-4)),this._deflate[fe]=null,this._deflate[V]=0,this._deflate[z]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};bn.exports=Kt;function Di(r){this[z].push(r),this[V]+=r.length}function yn(r){if(this[V]+=r.length,this[Xe]._maxPayload<1||this[V]<=this[Xe]._maxPayload){this[z].push(r);return}this[pe]=new RangeError("Max payload size exceeded"),this[pe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pe][_n]=1009,this.removeListener("data",yn),this.reset()}function Ri(r){if(this[Xe]._inflate=null,this[pe]){this[fe](this[pe]);return}r[_n]=1007,this[fe](r)}});var me=O((vc,Qe)=>{"use strict";var{isUtf8:wn}=require("buffer"),{hasBlob:Li}=H(),ji=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Mi(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Jt(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function $i(r){return Li&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Qe.exports={isBlob:$i,isValidStatusCode:Mi,isValidUTF8:Jt,tokenChars:ji};if(wn)Qe.exports.isValidUTF8=function(r){return r.length<24?Jt(r):wn(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Qe.exports.isValidUTF8=function(e){return e.length<32?Jt(e):r(e)}}catch{}});var Zt=O((Ec,In)=>{"use strict";var{Writable:Bi}=require("stream"),Sn=ge(),{BINARY_TYPES:Ui,EMPTY_BUFFER:vn,kStatusCode:Wi,kWebSocket:Fi}=H(),{concat:Yt,toArrayBuffer:Gi,unmask:qi}=Ce(),{isValidStatusCode:Hi,isValidUTF8:En}=me(),Ze=Buffer[Symbol.species],$=0,kn=1,xn=2,On=3,zt=4,Xt=5,et=6,Qt=class extends Bi{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ui[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fi]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=$}_write(e,t,n){if(this._opcode===8&&this._state==$)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ze(n.buffer,n.byteOffset+e,n.length-e),new Ze(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Ze(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case $:this.getInfo(e);break;case kn:this.getPayloadLength16(e);break;case xn:this.getPayloadLength64(e);break;case On:this.getMask();break;case zt:this.getData(e);break;case Xt:case et:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Sn.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=kn:this._payloadLength===127?this._state=xn:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=On:this._state=zt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zt}getData(e){let t=vn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&qi(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Xt,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Sn.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===$&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=$;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Yt(n,t):this._binaryType==="arraybuffer"?s=Gi(Yt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=$):(this._state=et,setImmediate(()=>{this.emit("message",s,!0),this._state=$,this.startLoop(e)}))}else{let s=Yt(n,t);if(!this._skipUTF8Validation&&!En(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Xt||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=$):(this._state=et,setImmediate(()=>{this.emit("message",s,!1),this._state=$,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,vn),this.end();else{let n=e.readUInt16BE(0);if(!Hi(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ze(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!En(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=$;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$):(this._state=et,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Wi]=s,o}};In.exports=Qt});var rr=O((xc,Pn)=>{"use strict";var{Duplex:kc}=require("stream"),{randomFillSync:Vi}=require("crypto"),Cn=ge(),{EMPTY_BUFFER:Ki,kWebSocket:Ji,NOOP:Yi}=H(),{isBlob:_e,isValidStatusCode:zi}=me(),{mask:An,toBuffer:Z}=Ce(),B=Symbol("kByteLength"),Xi=Buffer.alloc(4),tt=8*1024,ee,ye=tt,U=0,Qi=1,Zi=2,er=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=U,this.onerror=Yi,this[Ji]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Xi,t.generateMask?t.generateMask(n):(ye===tt&&(ee===void 0&&(ee=Buffer.alloc(tt)),Vi(ee,0,tt),ye=0),n[0]=ee[ye++],n[1]=ee[ye++],n[2]=ee[ye++],n[3]=ee[ye++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[B]!==void 0?c=t[B]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!o);let a=c;c>=65536?(i+=8,a=127):c>125&&(i+=2,a=126);let l=Buffer.allocUnsafe(s?c+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=a,a===126?l.writeUInt16BE(c,2):a===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(An(e,n,l,i,c),[l]):(An(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Ki;else{if(typeof e!="number"||!zi(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[B]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==U?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):_e(e)?(s=e.size,i=!1):(e=Z(e),s=e.length,i=Z.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[B]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==U?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):_e(e)?(s=e.size,i=!1):(e=Z(e),s=e.length,i=Z.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[B]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==U?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Cn.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):_e(e)?(c=e.size,a=!1):(e=Z(e),c=e.length,a=Z.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=c>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[B]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==U?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[B],this._state=Zi,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(tr,this,c,s);return}this._bufferedBytes-=n[B];let o=Z(i);t?this.dispatch(o,t,n,s):(this._state=U,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(eo,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Cn.extensionName];this._bufferedBytes+=n[B],this._state=Qi,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");tr(this,a,s);return}this._bufferedBytes-=n[B],this._state=U,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===U&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][B],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][B],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Pn.exports=er;function tr(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function eo(r,e,t){tr(r,e,t),r.onerror(e)}});var Bn=O((Oc,$n)=>{"use strict";var{kForOnEventAttribute:Pe,kListener:nr}=H(),Tn=Symbol("kCode"),Nn=Symbol("kData"),Dn=Symbol("kError"),Rn=Symbol("kMessage"),Ln=Symbol("kReason"),be=Symbol("kTarget"),jn=Symbol("kType"),Mn=Symbol("kWasClean"),K=class{constructor(e){this[be]=null,this[jn]=e}get target(){return this[be]}get type(){return this[jn]}};Object.defineProperty(K.prototype,"target",{enumerable:!0});Object.defineProperty(K.prototype,"type",{enumerable:!0});var te=class extends K{constructor(e,t={}){super(e),this[Tn]=t.code===void 0?0:t.code,this[Ln]=t.reason===void 0?"":t.reason,this[Mn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Tn]}get reason(){return this[Ln]}get wasClean(){return this[Mn]}};Object.defineProperty(te.prototype,"code",{enumerable:!0});Object.defineProperty(te.prototype,"reason",{enumerable:!0});Object.defineProperty(te.prototype,"wasClean",{enumerable:!0});var we=class extends K{constructor(e,t={}){super(e),this[Dn]=t.error===void 0?null:t.error,this[Rn]=t.message===void 0?"":t.message}get error(){return this[Dn]}get message(){return this[Rn]}};Object.defineProperty(we.prototype,"error",{enumerable:!0});Object.defineProperty(we.prototype,"message",{enumerable:!0});var Te=class extends K{constructor(e,t={}){super(e),this[Nn]=t.data===void 0?null:t.data}get data(){return this[Nn]}};Object.defineProperty(Te.prototype,"data",{enumerable:!0});var to={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Pe]&&s[nr]===e&&!s[Pe])return;let n;if(r==="message")n=function(i,o){let c=new Te("message",{data:o?i:i.toString()});c[be]=this,rt(e,this,c)};else if(r==="close")n=function(i,o){let c=new te("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[be]=this,rt(e,this,c)};else if(r==="error")n=function(i){let o=new we("error",{error:i,message:i.message});o[be]=this,rt(e,this,o)};else if(r==="open")n=function(){let i=new K("open");i[be]=this,rt(e,this,i)};else return;n[Pe]=!!t[Pe],n[nr]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[nr]===e&&!t[Pe]){this.removeListener(r,t);break}}};$n.exports={CloseEvent:te,ErrorEvent:we,Event:K,EventTarget:to,MessageEvent:Te};function rt(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var nt=O((Ic,Un)=>{"use strict";var{tokenChars:Ne}=me();function G(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function ro(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,c,a=-1,l=-1,d=-1,u=0;for(;u<r.length;u++)if(l=r.charCodeAt(u),o===void 0)if(d===-1&&Ne[l]===1)a===-1&&(a=u);else if(u!==0&&(l===32||l===9))d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);l===44?(G(e,g,t),t=Object.create(null)):o=g,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===void 0)if(d===-1&&Ne[l]===1)a===-1&&(a=u);else if(l===32||l===9)d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),G(t,r.slice(a,d),!0),l===44&&(G(e,o,t),t=Object.create(null),o=void 0),a=d=-1}else if(l===61&&a!==-1&&d===-1)c=r.slice(a,u),a=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Ne[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Ne[l]===1)a===-1&&(a=u);else if(l===34&&a!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Ne[l]===1)a===-1&&(a=u);else if(a!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);n&&(g=g.replace(/\\/g,""),n=!1),G(t,c,g),l===44&&(G(e,o,t),t=Object.create(null),o=void 0),c=void 0,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(a===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let p=r.slice(a,d);return o===void 0?G(e,p,t):(c===void 0?G(t,p,!0):n?G(t,c,p.replace(/\\/g,"")):G(t,c,p),G(e,o,t)),e}function no(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Un.exports={format:no,parse:ro}});var at=O((Pc,Qn)=>{"use strict";var so=require("events"),io=require("https"),oo=require("http"),Gn=require("net"),ao=require("tls"),{randomBytes:co,createHash:lo}=require("crypto"),{Duplex:Cc,Readable:Ac}=require("stream"),{URL:sr}=require("url"),X=ge(),uo=Zt(),ho=rr(),{isBlob:fo}=me(),{BINARY_TYPES:Wn,CLOSE_TIMEOUT:po,EMPTY_BUFFER:st,GUID:go,kForOnEventAttribute:ir,kListener:mo,kStatusCode:_o,kWebSocket:T,NOOP:qn}=H(),{EventTarget:{addEventListener:yo,removeEventListener:bo}}=Bn(),{format:wo,parse:So}=nt(),{toBuffer:vo}=Ce(),Hn=Symbol("kAborted"),or=[8,13],J=["CONNECTING","OPEN","CLOSING","CLOSED"],Eo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class r extends so{constructor(e,t,n){super(),this._binaryType=Wn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=st,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Vn(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Wn.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new uo({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new ho(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[T]=this,i[T]=this,e[T]=this,s.on("conclude",Oo),s.on("drain",Io),s.on("error",Co),s.on("message",Ao),s.on("ping",Po),s.on("pong",To),i.onerror=No,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yn),e.on("data",ot),e.on("end",zn),e.on("error",Xn),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[X.extensionName]&&this._extensions[X.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){L(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Jn(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ar(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||st,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ar(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||st,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ar(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[X.extensionName]||(s.compress=!1),this._sender.send(e||st,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){L(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:J.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:J.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:J.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:J.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:J.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:J.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:J.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:J.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(x.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(x.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ir])return e[mo];return null},set(e){for(let t of this.listeners(r))if(t[ir]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ir]:!0})}})});x.prototype.addEventListener=yo;x.prototype.removeEventListener=bo;Qn.exports=x;function Vn(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:po,protocolVersion:or[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!or.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${or.join(", ")})`);let i;if(e instanceof sr)i=e;else try{i=new sr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",c=i.protocol==="ws+unix:",a;if(i.protocol!=="ws:"&&!o&&!c?a=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?a="The URL's pathname is empty":i.hash&&(a="The URL contains a fragment identifier"),a){let f=new SyntaxError(a);if(r._redirects===0)throw f;it(r,f);return}let l=o?443:80,d=co(16).toString("base64"),u=o?io.request:oo.request,p=new Set,g;if(s.createConnection=s.createConnection||(o?xo:ko),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new X({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=wo({[X.extensionName]:g.offer()})),t.length){for(let f of t){if(typeof f!="string"||!Eo.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let f=s.path.split(":");s.socketPath=f[0],s.path=f[1]}let h;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let f=n&&n.headers;if(n={...n,headers:{}},f)for(let[m,k]of Object.entries(f))n.headers[m.toLowerCase()]=k}else if(r.listenerCount("redirect")===0){let f=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!f||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,f||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=r._req=u(s),r._redirects&&r.emit("redirect",r.url,h)}else h=r._req=u(s);s.timeout&&h.on("timeout",()=>{L(r,h,"Opening handshake has timed out")}),h.on("error",f=>{h===null||h[Hn]||(h=r._req=null,it(r,f))}),h.on("response",f=>{let m=f.headers.location,k=f.statusCode;if(m&&s.followRedirects&&k>=300&&k<400){if(++r._redirects>s.maxRedirects){L(r,h,"Maximum redirects exceeded");return}h.abort();let S;try{S=new sr(m,e)}catch{let y=new SyntaxError(`Invalid URL: ${m}`);it(r,y);return}Vn(r,S,t,n)}else r.emit("unexpected-response",h,f)||L(r,h,`Unexpected server response: ${f.statusCode}`)}),h.on("upgrade",(f,m,k)=>{if(r.emit("upgrade",f),r.readyState!==x.CONNECTING)return;h=r._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){L(r,m,"Invalid Upgrade header");return}let N=lo("sha1").update(d+go).digest("base64");if(f.headers["sec-websocket-accept"]!==N){L(r,m,"Invalid Sec-WebSocket-Accept header");return}let y=f.headers["sec-websocket-protocol"],v;if(y!==void 0?p.size?p.has(y)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":p.size&&(v="Server sent no subprotocol"),v){L(r,m,v);return}y&&(r._protocol=y);let w=f.headers["sec-websocket-extensions"];if(w!==void 0){if(!g){L(r,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=So(w)}catch{L(r,m,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(E);if(b.length!==1||b[0]!==X.extensionName){L(r,m,"Server indicated an extension that was not requested");return}try{g.accept(E[X.extensionName])}catch{L(r,m,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[X.extensionName]=g}r.setSocket(m,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,r):h.end()}function it(r,e){r._readyState=x.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function ko(r){return r.path=r.socketPath,Gn.connect(r)}function xo(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Gn.isIP(r.host)?"":r.host),ao.connect(r)}function L(r,e,t){r._readyState=x.CLOSING;let n=new Error(t);Error.captureStackTrace(n,L),e.setHeader?(e[Hn]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(it,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ar(r,e,t){if(e){let n=fo(e)?e.size:vo(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${J[r.readyState]})`);process.nextTick(t,n)}}function Oo(r,e){let t=this[T];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[T]!==void 0&&(t._socket.removeListener("data",ot),process.nextTick(Kn,t._socket),r===1005?t.close():t.close(r,e))}function Io(){let r=this[T];r.isPaused||r._socket.resume()}function Co(r){let e=this[T];e._socket[T]!==void 0&&(e._socket.removeListener("data",ot),process.nextTick(Kn,e._socket),e.close(r[_o])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Fn(){this[T].emitClose()}function Ao(r,e){this[T].emit("message",r,e)}function Po(r){let e=this[T];e._autoPong&&e.pong(r,!this._isServer,qn),e.emit("ping",r)}function To(r){this[T].emit("pong",r)}function Kn(r){r.resume()}function No(r){let e=this[T];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,Jn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Jn(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Yn(){let r=this[T];if(this.removeListener("close",Yn),this.removeListener("data",ot),this.removeListener("end",zn),r._readyState=x.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[T]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Fn),r._receiver.on("finish",Fn))}function ot(r){this[T]._receiver.write(r)||this.pause()}function zn(){let r=this[T];r._readyState=x.CLOSING,r._receiver.end(),this.end()}function Xn(){let r=this[T];this.removeListener("error",Xn),this.on("error",qn),r&&(r._readyState=x.CLOSING,this.destroy())}});var rs=O((Nc,ts)=>{"use strict";var Tc=at(),{Duplex:Do}=require("stream");function Zn(r){r.emit("close")}function Ro(){!this.destroyed&&this._writableState.finished&&this.destroy()}function es(r){this.removeListener("error",es),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Lo(r,e){let t=!0,n=new Do({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let c=!o&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Zn,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(Zn,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Ro),n.on("error",es),n}ts.exports=Lo});var cr=O((Dc,ns)=>{"use strict";var{tokenChars:jo}=me();function Mo(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&jo[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ns.exports={parse:Mo}});var ds=O((Lc,ls)=>{"use strict";var $o=require("events"),ct=require("http"),{Duplex:Rc}=require("stream"),{createHash:Bo}=require("crypto"),ss=nt(),re=ge(),Uo=cr(),Wo=at(),{CLOSE_TIMEOUT:Fo,GUID:Go,kWebSocket:qo}=H(),Ho=/^[+/0-9A-Za-z]{22}==$/,is=0,os=1,cs=2,lr=class extends $o{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Fo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wo,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ct.createServer((n,s)=>{let i=ct.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Vo(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=is}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===cs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(De,this);return}if(e&&this.once("close",e),this._state!==os)if(this._state=os,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(De,this):process.nextTick(De,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{De(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",as);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ne(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ne(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ho.test(i)){ne(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){ne(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Re(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=Uo.parse(a)}catch{ne(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let p=new re({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=ss.parse(d);g[re.extensionName]&&(p.accept(g[re.extensionName]),u[re.extensionName]=p)}catch{ne(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(g,h,f,m)=>{if(!g)return Re(t,h||401,f,m);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(p))return Re(t,401)}this.completeUpgrade(u,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,c){if(!i.readable||!i.writable)return i.destroy();if(i[qo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>is)return Re(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bo("sha1").update(t+Go).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[re.extensionName]){let u=e[re.extensionName].params,p=ss.format({[re.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${p}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
24
24
  `).join(`\r
25
- `)),i.removeListener("error",Qn),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ne,this)})),l(d,s)}};es.exports=tr;function $o(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Ne(r){r._state=Zn,r.emit("close")}function Qn(){this.destroy()}function Re(r,e,t,n){t=t||it.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${it.STATUS_CODES[e]}\r
25
+ `)),i.removeListener("error",as),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(De,this)})),c(d,s)}};ls.exports=lr;function Vo(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function De(r){r._state=cs,r.emit("close")}function as(){this.destroy()}function Re(r,e,t,n){t=t||ct.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${ct.STATUS_CODES[e]}\r
26
26
  `+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
27
27
  `)+`\r
28
28
  \r
29
- `+t)}function se(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,se),r.emit("wsClientError",o,t,e)}else Re(t,n,s,i)}});var as={};Ws(as,{loadConfig:()=>ie,loadProjectSettings:()=>sr,saveConfig:()=>oe});function De(r,e){let t=r[e];if(!(!t||typeof t!="object"||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function ie(){let r=Y.default.existsSync(ot)?ot:os;Y.default.existsSync(r)||(console.error("[bridge] Config not found. Run: bridge-agent auth"),process.exit(1));let e=Y.default.readFileSync(r,"utf-8"),t;try{t=JSON.parse(e)}catch{console.error("[bridge] Invalid config file at",os),process.exit(1)}(!t||typeof t!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let n=t,s=typeof n.server=="string"?n.server:"",i=typeof n.token=="string"?n.token:"",o=typeof n.name=="string"?n.name:"bridge-agent";(!s||!i)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1));let l={server:s,token:i,name:o},a=De(n,"agentPaths"),c=De(n,"projectPaths");return a&&(l.agentPaths=a),c&&(l.projectPaths=c),l}function oe(r){let e=je.default.dirname(ot);Y.default.existsSync(e)||Y.default.mkdirSync(e,{recursive:!0}),Y.default.writeFileSync(ot,JSON.stringify(r,null,2),{mode:384})}function sr(r){let e=je.default.join(r??process.cwd(),".jerico","settings.json");if(!Y.default.existsSync(e))return{};try{let t=Y.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent);let o=De(s,"hooks"),l=De(s,"env"),a=De(s,"agentPaths");return o&&(i.hooks=o),l&&(i.env=l),a&&(i.agentPaths=a),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var Y,je,nr,ot,os,Ee=Us(()=>{"use strict";Y=_(require("fs")),je=_(require("path")),nr=_(require("os"));ot=je.default.join(nr.default.homedir(),".jerico","settings.json"),os=je.default.join(nr.default.homedir(),".bridge","config.json")});var Pr=_(Ar(),1),{program:Ka,createCommand:Ya,createArgument:Ja,createOption:za,CommanderError:Xa,InvalidArgumentError:Qa,InvalidOptionArgumentError:Za,Command:Tr,Argument:ec,Option:tc,Help:rc}=Pr.default;var Ss=require("node:http"),le=require("node:child_process"),P=require("node:fs"),Z=require("node:os"),D=_(require("path"));var Xr=_(require("node-pty"));var Rt=_(Kr()),he=_(require("fs")),Oe=_(require("path")),Jr=_(require("net")),zr=require("child_process"),Fe=r=>r+`
30
- `,He=r=>r.replace(/[\r\n]+$/,"")+"\r",fe=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:Fe},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>Nt(".claude")||ue("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:He,versionDirGlobs:[".local/share/claude/versions/*"]},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>ue("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:He},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>Nt(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:He,versionDirGlobs:[".local/share/qwen/versions/*"]},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>ue("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:Fe},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>yi(11434),formatInput:Fe},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>ue("OPENAI_API_KEY")||ue("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:Fe},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>Nt(".kimi")||ue("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:He,versionDirGlobs:[".local/share/uv/tools/kimi-cli/bin",".local/share/kimi/versions/*"]}];var Yr=process.env.HOME??"/Users/unknown";function qe(r){try{let e=(0,zr.spawnSync)(r,["--version"],{timeout:5e3});return e.status!==0?void 0:(e.stdout??e.stderr??Buffer.from("")).toString("utf8").split(`
31
- `)[0].trim()||void 0}catch{return}}function mi(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=Oe.default.join(Yr,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=he.default.readdirSync(s)}catch{}i.sort((o,l)=>l.localeCompare(o));for(let o of i){let l=Oe.default.join(s,o,r.binary);if(he.default.existsSync(l)){let a=qe(l);e.push({path:l,version:a})}}}else{let i=Oe.default.join(Yr,n);if(he.default.existsSync(i)){let o=qe(i);e.push({path:i,version:o})}}}return e}async function _i(r,e={}){if(e[r.key]){let n=e[r.key],s=qe(n);if(s)return{path:n,version:s}}try{let n=await(0,Rt.default)(r.binary);if(n&&he.default.existsSync(n)){let s=qe(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=mi(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,Rt.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function Dt(r={}){let e=[];for(let t of fe)try{let{path:n,version:s}=await _i(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:fe.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function Nt(r){return he.default.existsSync(Oe.default.join(process.env.HOME??"",r))}function ue(r){return!!process.env[r]}async function yi(r){return new Promise(e=>{let t=Jr.default.createConnection(r,"127.0.0.1");t.setTimeout(200),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}var Ve=class{handles=new Map;nextInstanceId=1;lastErrors=new Map;spawn(e,t,n,s,i,o,l,a,c){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),h=Math.max(1,Math.min(500,o)),g={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};c&&(g.BRIDGE_SERVER_URL=c.serverUrl,g.BRIDGE_TOKEN=c.token,g.BRIDGE_WORKSPACE_ID=c.workspaceId,g.BRIDGE_PROJECT_ID=c.projectId,c.projectEnv&&Object.assign(g,c.projectEnv));let p=process.env.BRIDGE_MCP_URL;p&&(g.BRIDGE_MCP_URL=p);let f;try{f=Xr.spawn(n,s,{name:"xterm-256color",cols:u,rows:h,cwd:c?.cwd,env:g})}catch(b){let T=b instanceof Error?b.message:String(b);return this.lastErrors.set(e,T),console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:T}),!1}let m=this.nextInstanceId++,x={agentId:e,agentKey:t,process:f,pid:f.pid,killed:!1,instanceId:m};return f.onData(b=>{let T=this.handles.get(e);!T||T.instanceId!==m||x.killed||l(Buffer.from(b).toString("base64"))}),f.onExit(({exitCode:b,signal:T})=>{let y=this.handles.get(e);!y||y.instanceId!==m||x.killed||x.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:b,signal:T}),a(b??null,T?String(T):null))}),this.lastErrors.delete(e),this.handles.set(e,x),console.log("[daemon] pty.spawn.success",{agentId:e,agentKey:t,args:s,cwd:c?.cwd}),!0}write(e,t,n){let s=this.handles.get(e);if(!s){console.warn("[daemon] pty.write.no_handle",{agentId:e.slice(-8),source:n,dataLength:t.length});return}let i=Buffer.from(t,"base64").toString(),o=fe.find(a=>a.key===s.agentKey),l=n==="orchestrator"&&o?.formatInput?o.formatInput(i):i;s.process.write(l)}kill(e,t=!1){let n=this.handles.get(e);if(!n)return;n.killed=!0,this.handles.delete(e);let s=n.pid;if(t){try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}setTimeout(()=>{try{process.kill(-s,"SIGKILL")}catch{}},2e3)}else try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}console.log("[daemon] pty.kill",{agentId:e,force:t})}resize(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Math.max(1,Math.min(500,t)),o=Math.max(1,Math.min(500,n));s.process.resize(i,o)}getLastError(e){return this.lastErrors.get(e)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}getLiveAgentIds(){return[...this.handles.keys()]}};var Bo=_(Kn(),1),Uo=_(et(),1),Wo=_(me(),1),Fo=_(Vt(),1),Ho=_(Yt(),1),qo=_(er(),1),rs=_(st(),1),Vo=_(ts(),1);var C=rs.default;var F=_(require("fs")),$=_(require("path")),J=_(require("os")),dt=require("node:child_process"),fr=require("node:crypto");var ns=r=>r;var ss=r=>r,is=r=>r;function rr(r){return(process.env.JERICO_FEATURES??"").split(",").map(t=>t.trim()).filter(Boolean).includes(r)}Ee();var Le=_(require("fs")),ir=_(require("path")),cs=_(require("os")),Go=2e5;function Ko(r){let e=ir.default.join(cs.default.homedir(),".claude","projects");if(Le.default.existsSync(e))try{let t=Le.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=ir.default.join(e,n.name,`${r}.jsonl`);if(Le.default.existsSync(s))return s}}catch{}}function Yo(r){try{let t=Le.default.readFileSync(r,"utf-8").trim().split(`
32
- `);for(let n=t.length-1;n>=0;n--){let s=t[n]?.trim();if(s)try{let i=JSON.parse(s),o=i.message?.usage??i.usage;if(!o||typeof o!="object")continue;let l=o,a=(l.input_tokens??0)+(l.cache_creation_input_tokens??0)+(l.cache_read_input_tokens??0);if(a===0)continue;return{usedPct:Math.min(100,Math.round(a/Go*100)),usedTokens:a}}catch{continue}}}catch{}return null}function or(r,e,t){let n,s=-1,i=()=>{if(n||(n=Ko(e)),!n)return;let a=Yo(n);a&&a.usedTokens!==s&&(s=a.usedTokens,t(r,a.usedPct,a.usedTokens))},o=setTimeout(i,2e3),l=setInterval(i,3e3);return()=>{clearTimeout(o),clearInterval(l)}}var Q=_(require("fs")),Me=_(require("path")),ar=_(require("os")),ls=300*60*1e3,ds={free:10,pro:40,max_5x:200,max_20x:200};function Jo(){let r=Me.default.join(ar.default.homedir(),".jerico","settings.json");try{if(!Q.default.existsSync(r))return"pro";let t=JSON.parse(Q.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in ds)return t}catch{}return"pro"}function zo(){let r=Me.default.join(ar.default.homedir(),".claude","projects");if(!Q.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-ls,n=1/0,s=0;try{let o=Q.default.readdirSync(r,{withFileTypes:!0}).filter(l=>l.isDirectory());for(let l of o){let a=Me.default.join(r,l.name),c;try{c=Q.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of c){let u=Me.default.join(a,d),h;try{if(Q.default.statSync(u).size>20*1024*1024)continue;h=Q.default.readFileSync(u,"utf-8")}catch{continue}for(let g of h.split(`
33
- `)){let p=g.trim();if(p)try{let f=JSON.parse(p);if(f.type!=="user"||f.message?.role!=="user"||f.userType!==void 0&&f.userType!=="external")continue;let x=f.timestamp;if(typeof x!="string")continue;let b=Date.parse(x);if(isNaN(b)||b<t)continue;s++,b<n&&(n=b)}catch{continue}}}}}catch{}let i=isFinite(n)?n+ls:0;return{prompts5h:s,resetAt:i}}function us(r){let e=()=>{let n=Jo(),s=ds[n]??40,{prompts5h:i,resetAt:o}=zo();r({prompts5h:i,limit5h:s,resetAt:o,tier:n})};try{e()}catch(n){console.warn("[quota] initial poll failed",n)}let t=setInterval(()=>{try{e()}catch{}},6e4);return()=>clearInterval(t)}var ve=_(require("os")),at=_(require("fs")),lr=require("node:child_process");function fs(){let r=0,e=0;for(let t of ve.default.cpus())r+=t.times.idle,e+=t.times.user+t.times.nice+t.times.sys+t.times.idle+(t.times.irq??0);return{idle:r,total:e}}var cr=fs();function Xo(){let r=fs(),e=r.idle-cr.idle,t=r.total-cr.total;return cr=r,t===0?0:Math.round((1-e/t)*100)}function Qo(){let r=ve.default.totalmem(),e=ve.default.freemem(),t=0;try{let n=(0,lr.spawnSync)("vm_stat",["-c","10"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(n.status===0&&n.stdout){let s=n.stdout.match(/page size of (\d+) bytes/),i=n.stdout.match(/Pages speculative:\s*(\d+)/),o=n.stdout.match(/Pages inactive:\s*(\d+)/);if(i&&o){let l=s?parseInt(s[1],10):4096;t=(parseInt(i[1],10)+parseInt(o[1],10))*l}}}catch{}return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:Math.round(t/1024/1024)}}function Zo(){if(process.platform==="darwin")return Qo();let r=ve.default.totalmem(),e=ve.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:0}}function ea(){try{let r=(0,lr.spawnSync)("pmset",["-g","batt"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(r.status!==0||!r.stdout)return;let e=r.stdout.match(/(\d+)%;\s*(charging|discharging|charged|finishing charge)/i);if(!e)return;let t=parseInt(e[1],10),n=/charging|charged|finishing/i.test(e[2]);return{percent:t,charging:n}}catch{return}}function ta(){try{let r="/sys/class/power_supply",e=at.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(at.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=at.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function hs(){let r=process.platform;if(r==="darwin")return ea();if(r==="linux")return ta()}var ra=1e4,na=3;function ps(r){let e=0,t=hs(),n=setInterval(()=>{e++,e%na===0&&(t=hs());let s=Zo();r({cpu:Xo(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,ramCachedMb:s.cachedMb,battery:t})},ra);return()=>clearInterval(n)}var ct=_(require("fs")),lt=_(require("path")),gs=_(require("node-pty"));function sa(){try{let r=require.resolve("node-pty"),e=lt.default.resolve(lt.default.dirname(r),"..");return lt.default.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper")}catch{return}}function ms(){let r=sa();if(!r||!ct.default.existsSync(r))return!0;try{ct.default.accessSync(r,ct.default.constants.X_OK)}catch{return!1}try{gs.spawn("/bin/sh",[],{name:"xterm-256color",cols:80,rows:24}).kill()}catch{return!1}return!0}var ae=new Map;function ia(){try{return(0,fr.createHash)("sha256").update(J.default.hostname()+":"+J.default.userInfo().username).digest("hex")}catch{return"unknown"}}var $e=[];function oa(r){let e=Date.now(),t=e-3e4;for(;$e.length&&$e[0].ts<t;)$e.shift();return $e.push({agentKey:r,ts:e}),new Set($e.map(s=>s.agentKey)).size>=2}var aa=r=>r.replace(/[\r\n]+$/,"")+"\r",ur=null,ca=us(r=>{ur=r}),la=3e4,da=5e3,ua=400;function ha(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function fa(r,e=ua){return r.length<=e?r:`${r.slice(0,e)}...`}function pa(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function ht(){let r=F.default.realpathSync(process.argv[1]??""),e=$.default.dirname(r);return[$.default.resolve(e,"../../mcp-server/dist/index.cjs"),$.default.resolve(e,"bridge-mcp.cjs"),$.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>F.default.existsSync(n))??"bridge-mcp"}function ga(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:ht(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=$.default.join(J.default.tmpdir(),`bridge-mcp-${r.agentId??r.projectId}.json`);return F.default.writeFileSync(n,JSON.stringify(t,null,2)+`
34
- `,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config",n]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var ma={bridge_get_project:"Project metadata: name, cwd, machineId",bridge_get_plan:"Read project spec/description",bridge_update_plan:"Update project spec/description",bridge_get_project_history:"Past run history and failure patterns",bridge_get_execution_status:"Run history with todo completion counts",bridge_get_todos:"List todos + session state for this project",bridge_add_todo:"Create a new todo (title, todoType, dependsOn)",bridge_update_todo:"Update a todo title or status",bridge_cancel_run:"Cancel active run (use before restarting a stale plan)",bridge_list_agents:"All agents: role, status, inRun flag",bridge_get_agent_status:"Single agent status check",bridge_spawn_worker:"Spawn a new worker agent (agentKey, role)",bridge_kill_agent:"Terminate a stuck or dead agent",bridge_get_agent_output:"Read terminal output of any agent",bridge_send_input:"Send text input to an agent PTY",bridge_get_my_task:"Get the task assigned to this agent",bridge_complete_task:"Signal task completion",bridge_fail_task:"Signal task failure with a specific reason",bridge_get_todo_context:"Read todo output/error for a specific todo",bridge_assign_task:"Assign a pending todo to a specific agent"};function xe(...r){return`
29
+ `+t)}function ne(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ne),r.emit("wsClientError",o,t,e)}else Re(t,n,s,i)}});function je(){return process.env.BRIDGE_PROFILE||void 0}function lt(){let r=je();return r?se.default.join(gs,"profiles",r,"settings.json"):se.default.join(gs,"settings.json")}function ur(){let r=je(),e=r?`${r}.daemon.lock`:"daemon.lock";return se.default.join((0,Le.homedir)(),".bridge",e)}function dt(){let r=je();return r?`com.jerico.bridge-agent.${r}.plist`:"com.jerico.bridge-agent.plist"}function ut(){let r=je(),e=r?`-${r}`:"";return{out:se.default.join((0,Le.homedir)(),`bridge-daemon${e}.log`),err:se.default.join((0,Le.homedir)(),`bridge-daemon${e}.err.log`)}}function ms(){let r=je();return r?`:profile:${r}`:""}var Le,se,gs,ht=Or(()=>{"use strict";Le=require("node:os"),se=_(require("path")),gs=se.default.join((0,Le.homedir)(),".jerico")});var ys={};Ys(ys,{getConfigPath:()=>lt,loadConfig:()=>ie,loadProjectSettings:()=>hr,saveConfig:()=>oe});function Me(r,e){let t=r[e];if(!(!t||typeof t!="object"||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function ie(){let r=lt(),e=Y.default.existsSync(r)?r:ea;if(!Y.default.existsSync(e)){let u=process.env.BRIDGE_PROFILE?`bridge-agent --profile ${process.env.BRIDGE_PROFILE} auth`:"bridge-agent auth";console.error(`[bridge] Config not found. Run: ${u}`),process.exit(1)}let t=Y.default.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{console.error("[bridge] Invalid config file at",e),process.exit(1)}(!n||typeof n!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let s=n,i=typeof s.server=="string"?s.server:"",o=typeof s.token=="string"?s.token:"",c=typeof s.name=="string"?s.name:"bridge-agent";(!i||!o)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1));let a={server:i,token:o,name:c},l=Me(s,"agentPaths"),d=Me(s,"projectPaths");return l&&(a.agentPaths=l),d&&(a.projectPaths=d),a}function oe(r){let e=lt(),t=ft.default.dirname(e);Y.default.existsSync(t)||Y.default.mkdirSync(t,{recursive:!0}),Y.default.writeFileSync(e,JSON.stringify(r,null,2),{mode:384})}function hr(r){let e=ft.default.join(r??process.cwd(),".jerico","settings.json");if(!Y.default.existsSync(e))return{};try{let t=Y.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent);let o=Me(s,"hooks"),c=Me(s,"env"),a=Me(s,"agentPaths");return o&&(i.hooks=o),c&&(i.env=c),a&&(i.agentPaths=a),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var Y,ft,_s,ea,Se=Or(()=>{"use strict";Y=_(require("fs")),ft=_(require("path")),_s=_(require("os"));ht();ea=ft.default.join(_s.default.homedir(),".bridge","config.json")});var Br=_($r(),1),{program:rc,createCommand:nc,createArgument:sc,createOption:ic,CommanderError:oc,InvalidArgumentError:ac,InvalidOptionArgumentError:cc,Command:Ur,Argument:lc,Option:dc,Help:uc}=Br.default;var Ns=require("node:http"),ce=require("node:child_process"),A=require("node:fs"),ke=require("node:os"),R=_(require("path"));var an=_(require("node-pty"));var Wt=_(rn()),ue=_(require("fs")),Ie=_(require("path")),sn=_(require("net")),on=require("child_process"),He=r=>r+`
30
+ `,Ve=r=>r.replace(/[\r\n]+$/,"")+"\r",he=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:He},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>Ut(".claude")||de("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:Ve,versionDirGlobs:[".local/share/claude/versions/*"]},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>de("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:Ve},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>Ut(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:Ve,versionDirGlobs:[".local/share/qwen/versions/*"]},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>de("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:He},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>Oi(11434),formatInput:He},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>de("OPENAI_API_KEY")||de("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:He},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>Ut(".kimi")||de("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:Ve,versionDirGlobs:[".local/share/uv/tools/kimi-cli/bin",".local/share/kimi/versions/*"]}];var nn=process.env.HOME??"/Users/unknown";function Ke(r){try{let e=(0,on.spawnSync)(r,["--version"],{timeout:5e3});return e.status!==0?void 0:(e.stdout??e.stderr??Buffer.from("")).toString("utf8").split(`
31
+ `)[0].trim()||void 0}catch{return}}function ki(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=Ie.default.join(nn,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=ue.default.readdirSync(s)}catch{}i.sort((o,c)=>c.localeCompare(o));for(let o of i){let c=Ie.default.join(s,o,r.binary);if(ue.default.existsSync(c)){let a=Ke(c);e.push({path:c,version:a})}}}else{let i=Ie.default.join(nn,n);if(ue.default.existsSync(i)){let o=Ke(i);e.push({path:i,version:o})}}}return e}async function xi(r,e={}){if(e[r.key]){let n=e[r.key],s=Ke(n);if(s)return{path:n,version:s}}try{let n=await(0,Wt.default)(r.binary);if(n&&ue.default.existsSync(n)){let s=Ke(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=ki(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,Wt.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function Ft(r={}){let e=[];for(let t of he)try{let{path:n,version:s}=await xi(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:he.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function Ut(r){return ue.default.existsSync(Ie.default.join(process.env.HOME??"",r))}function de(r){return!!process.env[r]}async function Oi(r){return new Promise(e=>{let t=sn.default.createConnection(r,"127.0.0.1");t.setTimeout(200),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}var Je=class{handles=new Map;nextInstanceId=1;lastErrors=new Map;livenessTimer=null;startLivenessCheck(e=6e4){this.livenessTimer||(this.livenessTimer=setInterval(()=>{for(let[t,n]of this.handles.entries()){if(n.killed)continue;let s=!1;try{s=process.kill(n.pid,0)}catch{s=!1}s||(console.warn("[daemon] pty.liveness.dead",{agentId:t,pid:n.pid}),this.handles.delete(t),n.onExit(137,"SIGKILL"))}},e),console.log("[daemon] pty.liveness.started",{intervalMs:e}))}stopLivenessCheck(){this.livenessTimer&&(clearInterval(this.livenessTimer),this.livenessTimer=null,console.log("[daemon] pty.liveness.stopped"))}spawn(e,t,n,s,i,o,c,a,l){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),p=Math.max(1,Math.min(500,o)),g={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(g.BRIDGE_SERVER_URL=l.serverUrl,g.BRIDGE_TOKEN=l.token,g.BRIDGE_WORKSPACE_ID=l.workspaceId,g.BRIDGE_PROJECT_ID=l.projectId||"",l.projectEnv&&Object.assign(g,l.projectEnv));let h=process.env.BRIDGE_MCP_URL;h&&(g.BRIDGE_MCP_URL=h);let f;try{f=an.spawn(n,s,{name:"xterm-256color",cols:u,rows:p,cwd:l?.cwd,env:g})}catch(S){let N=S instanceof Error?S.message:String(S);return this.lastErrors.set(e,N),console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:N}),!1}let m=this.nextInstanceId++,k={agentId:e,agentKey:t,process:f,pid:f.pid,killed:!1,instanceId:m,onExit:a};return f.onData(S=>{let N=this.handles.get(e);!N||N.instanceId!==m||k.killed||c(Buffer.from(S).toString("base64"))}),f.onExit(({exitCode:S,signal:N})=>{let y=this.handles.get(e);!y||y.instanceId!==m||k.killed||k.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:S,signal:N}),a(S??null,N?String(N):null))}),this.lastErrors.delete(e),this.handles.set(e,k),console.log("[daemon] pty.spawn.success",{agentId:e,agentKey:t,args:s,cwd:l?.cwd}),!0}write(e,t,n){let s=this.handles.get(e);if(!s){console.warn("[daemon] pty.write.no_handle",{agentId:e.slice(-8),source:n,dataLength:t.length});return}let i=Buffer.from(t,"base64").toString(),o=he.find(a=>a.key===s.agentKey),c=n==="orchestrator"&&o?.formatInput?o.formatInput(i):i;s.process.write(c)}kill(e,t=!1){let n=this.handles.get(e);if(!n)return;n.killed=!0,this.handles.delete(e);let s=n.pid;if(t){try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}setTimeout(()=>{try{process.kill(-s,"SIGKILL")}catch{}},2e3)}else try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}console.log("[daemon] pty.kill",{agentId:e,force:t})}resize(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Math.max(1,Math.min(500,t)),o=Math.max(1,Math.min(500,n));s.process.resize(i,o)}getLastError(e){return this.lastErrors.get(e)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}getLiveAgentIds(){return[...this.handles.keys()]}};var Ko=_(rs(),1),Jo=_(nt(),1),Yo=_(ge(),1),zo=_(Zt(),1),Xo=_(rr(),1),Qo=_(cr(),1),us=_(at(),1),Zo=_(ds(),1);var C=us.default;var W=_(require("fs")),j=_(require("path")),F=_(require("os")),yt=require("node:child_process"),Fe=require("node:crypto");var hs=r=>r;var fs=r=>r,ps=r=>r;function dr(r){return(process.env.JERICO_FEATURES??"").split(",").map(t=>t.trim()).filter(Boolean).includes(r)}Se();ht();var $e=_(require("fs")),fr=_(require("path")),bs=_(require("os")),ta=2e5;function ra(r){let e=fr.default.join(bs.default.homedir(),".claude","projects");if($e.default.existsSync(e))try{let t=$e.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=fr.default.join(e,n.name,`${r}.jsonl`);if($e.default.existsSync(s))return s}}catch{}}function na(r){try{let t=$e.default.readFileSync(r,"utf-8").trim().split(`
32
+ `);for(let n=t.length-1;n>=0;n--){let s=t[n]?.trim();if(s)try{let i=JSON.parse(s),o=i.message?.usage??i.usage;if(!o||typeof o!="object")continue;let c=o,a=(c.input_tokens??0)+(c.cache_creation_input_tokens??0)+(c.cache_read_input_tokens??0);if(a===0)continue;return{usedPct:Math.min(100,Math.round(a/ta*100)),usedTokens:a}}catch{continue}}}catch{}return null}function pr(r,e,t){let n,s=-1,i=()=>{if(n||(n=ra(e)),!n)return;let a=na(n);a&&a.usedTokens!==s&&(s=a.usedTokens,t(r,a.usedPct,a.usedTokens))},o=setTimeout(i,2e3),c=setInterval(i,3e3);return()=>{clearTimeout(o),clearInterval(c)}}var Q=_(require("fs")),Be=_(require("path")),gr=_(require("os")),ws=300*60*1e3,Ss={free:10,pro:40,max_5x:200,max_20x:200};function sa(){let r=Be.default.join(gr.default.homedir(),".jerico","settings.json");try{if(!Q.default.existsSync(r))return"pro";let t=JSON.parse(Q.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in Ss)return t}catch{}return"pro"}function ia(){let r=Be.default.join(gr.default.homedir(),".claude","projects");if(!Q.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-ws,n=1/0,s=0;try{let o=Q.default.readdirSync(r,{withFileTypes:!0}).filter(c=>c.isDirectory());for(let c of o){let a=Be.default.join(r,c.name),l;try{l=Q.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of l){let u=Be.default.join(a,d),p;try{if(Q.default.statSync(u).size>20*1024*1024)continue;p=Q.default.readFileSync(u,"utf-8")}catch{continue}for(let g of p.split(`
33
+ `)){let h=g.trim();if(h)try{let f=JSON.parse(h);if(f.type!=="user"||f.message?.role!=="user"||f.userType!==void 0&&f.userType!=="external")continue;let k=f.timestamp;if(typeof k!="string")continue;let S=Date.parse(k);if(isNaN(S)||S<t)continue;s++,S<n&&(n=S)}catch{continue}}}}}catch{}let i=isFinite(n)?n+ws:0;return{prompts5h:s,resetAt:i}}function vs(r){let e=()=>{let n=sa(),s=Ss[n]??40,{prompts5h:i,resetAt:o}=ia();r({prompts5h:i,limit5h:s,resetAt:o,tier:n})};try{e()}catch(n){console.warn("[quota] initial poll failed",n)}let t=setInterval(()=>{try{e()}catch{}},6e4);return()=>clearInterval(t)}var ve=_(require("os")),pt=_(require("fs")),_r=require("node:child_process");function ks(){let r=0,e=0;for(let t of ve.default.cpus())r+=t.times.idle,e+=t.times.user+t.times.nice+t.times.sys+t.times.idle+(t.times.irq??0);return{idle:r,total:e}}var mr=ks();function oa(){let r=ks(),e=r.idle-mr.idle,t=r.total-mr.total;return mr=r,t===0?0:Math.round((1-e/t)*100)}function aa(){let r=ve.default.totalmem(),e=ve.default.freemem(),t=0;try{let n=(0,_r.spawnSync)("vm_stat",["-c","10"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(n.status===0&&n.stdout){let s=n.stdout.match(/page size of (\d+) bytes/),i=n.stdout.match(/Pages speculative:\s*(\d+)/),o=n.stdout.match(/Pages inactive:\s*(\d+)/);if(i&&o){let c=s?parseInt(s[1],10):4096;t=(parseInt(i[1],10)+parseInt(o[1],10))*c}}}catch{}return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:Math.round(t/1024/1024)}}function ca(){if(process.platform==="darwin")return aa();let r=ve.default.totalmem(),e=ve.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:0}}function la(){try{let r=(0,_r.spawnSync)("pmset",["-g","batt"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(r.status!==0||!r.stdout)return;let e=r.stdout.match(/(\d+)%;\s*(charging|discharging|charged|finishing charge)/i);if(!e)return;let t=parseInt(e[1],10),n=/charging|charged|finishing/i.test(e[2]);return{percent:t,charging:n}}catch{return}}function da(){try{let r="/sys/class/power_supply",e=pt.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(pt.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=pt.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function Es(){let r=process.platform;if(r==="darwin")return la();if(r==="linux")return da()}var ua=1e4,ha=3;function xs(r){let e=0,t=Es(),n=setInterval(()=>{e++,e%ha===0&&(t=Es());let s=ca();r({cpu:oa(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,ramCachedMb:s.cachedMb,battery:t})},ua);return()=>clearInterval(n)}var gt=_(require("fs")),mt=_(require("path")),Os=_(require("node-pty"));function fa(){try{let r=require.resolve("node-pty"),e=mt.default.resolve(mt.default.dirname(r),"..");return mt.default.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper")}catch{return}}function Is(){let r=fa();if(!r||!gt.default.existsSync(r))return!0;try{gt.default.accessSync(r,gt.default.constants.X_OK)}catch{return!1}try{Os.spawn("/bin/sh",[],{name:"xterm-256color",cols:80,rows:24}).kill()}catch{return!1}return!0}var ae=new Map,yr,_t;function vr(){try{return(0,Fe.createHash)("sha256").update(F.default.hostname()+":"+F.default.userInfo().username+ms()).digest("hex")}catch{return"unknown"}}var Ue=[];function pa(r){let e=Date.now(),t=e-3e4;for(;Ue.length&&Ue[0].ts<t;)Ue.shift();return Ue.push({agentKey:r,ts:e}),new Set(Ue.map(s=>s.agentKey)).size>=2}var ga=r=>r.replace(/[\r\n]+$/,"")+"\r",wr=null,ma=vs(r=>{wr=r}),_a=Number(process.env.BRIDGE_KEEPALIVE_MS)||3e4,ya=Number(process.env.BRIDGE_PONG_DEADLINE_MS)||5e3,ba=5e3,wa=400;function Sa(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function va(r,e=wa){return r.length<=e?r:`${r.slice(0,e)}...`}function Ea(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function wt(){let r=W.default.realpathSync(process.argv[1]??""),e=j.default.dirname(r);return[j.default.resolve(e,"../../mcp-server/dist/index.cjs"),j.default.resolve(e,"bridge-mcp.cjs"),j.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>W.default.existsSync(n))??"bridge-mcp"}function ka(r){try{let e=process.env.BRIDGE_MCP_URL,t=r.projectId||"workspace",n=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${t}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:wt(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:t,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},s=j.default.join(F.default.tmpdir(),`bridge-mcp-${r.agentId??t}.json`);return W.default.writeFileSync(s,JSON.stringify(n,null,2)+`
34
+ `,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:s,transport:e?"http":"stdio"}),["--mcp-config",s]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var xa={bridge_get_project:"Project metadata: name, cwd, machineId",bridge_get_plan:"Read project spec/description",bridge_update_plan:"Update project spec/description",bridge_get_project_history:"Past run history and failure patterns",bridge_get_execution_status:"Run history with todo completion counts",bridge_get_todos:"List todos + session state for this project",bridge_add_todo:"Create a new todo (title, todoType, dependsOn)",bridge_update_todo:"Update a todo title or status",bridge_cancel_run:"Cancel active run (use before restarting a stale plan)",bridge_list_agents:"All agents: role, status, inRun flag",bridge_get_agent_status:"Single agent status check",bridge_spawn_worker:"Spawn a new worker agent (agentKey, role)",bridge_kill_agent:"Terminate a stuck or dead agent",bridge_get_agent_output:"Read terminal output of any agent",bridge_send_input:"Send text input to an agent PTY",bridge_get_my_task:"Get the task assigned to this agent",bridge_complete_task:"Signal task completion",bridge_fail_task:"Signal task failure with a specific reason",bridge_get_todo_context:"Read todo output/error for a specific todo",bridge_assign_task:"Assign a pending todo to a specific agent",bridge_list_groups:"List all agent groups and their member agentIds",bridge_get_group_status:"Get agents in a group with status and last output line",bridge_dispatch_to_group:"Send a text message/command to every agent in a group",bridge_list_workspace_projects:"List all workspace projects with name, cwd, active run count",bridge_query_workspace:"Natural-language query about orchestration state",bridge_list_active_runs:"All active orchestration runs across workspace projects",bridge_peek_panel:"Read terminal output of any panel workspace-wide (no project boundary)",bridge_status_panel:"Get status of any panel in the workspace regardless of project"};function Ee(...r){return`
35
35
 
36
- **Available MCP tools:** ${r.join(", ")}`}function _a(...r){return`
36
+ **Available MCP tools:** ${r.join(", ")}`}function Oa(...r){return`
37
37
 
38
38
  ## Tool reference (only call tools listed here)
39
39
 
40
40
  | Tool | Purpose |
41
41
  |------|---------|
42
- ${r.map(t=>`| \`${t}\` | ${ma[t]} |`).join(`
43
- `)}`}var ya={developer:`# Bridge Worker \u2014 Developer Role
42
+ ${r.map(t=>`| \`${t}\` | ${xa[t]} |`).join(`
43
+ `)}`}var Ia={developer:`# Bridge Worker \u2014 Developer Role
44
44
 
45
45
  You are a **Developer** worker in a multi-agent orchestration system called Bridge.
46
46
 
@@ -53,7 +53,7 @@ You are a **Developer** worker in a multi-agent orchestration system called Brid
53
53
  - After making changes, check the runner agent (role:'runner' in bridge_list_agents) for build errors: bridge_get_agent_output(runnerAgentId)
54
54
  - Trigger hot reload after file changes: bridge_send_input(runnerAgentId, "r")
55
55
 
56
- ${xe("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,reviewer:`# Bridge Worker \u2014 Reviewer Role
56
+ ${Ee("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,reviewer:`# Bridge Worker \u2014 Reviewer Role
57
57
 
58
58
  You are a **Quality-Obsessed Tech Lead** reviewing code changes in a multi-agent system called Bridge.
59
59
  Your identity: Agile, pragmatic, anti-fragile. You ship with confidence or you send it back.
@@ -137,7 +137,7 @@ If a runner agent exists (bridge_list_agents \u2192 role:'runner'), call bridge_
137
137
  - One \`bridge_fail_task\` per review cycle \u2014 consolidate all issues into a single message
138
138
  - If unsure whether something is a bug or intentional design: flag it as a question, don't reject
139
139
 
140
- ${xe("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output")}`,planner:`# Bridge Worker \u2014 Planner Role
140
+ ${Ee("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output")}`,planner:`# Bridge Worker \u2014 Planner Role
141
141
 
142
142
  You are a **Planner** in Bridge. Your job: understand the project, listen to the user, then create a well-structured and verified execution plan.
143
143
 
@@ -227,7 +227,7 @@ Show the complete todo list with types and dependency chain. Then stop.
227
227
  - To close a stale open todo that's already done: \`bridge_complete_task\` with its ID
228
228
  - Todo titles must be specific: name the files, endpoints, components \u2014 no vague verbs
229
229
 
230
- ${xe("bridge_get_plan","bridge_get_project_history","bridge_get_todos","bridge_add_todo","bridge_complete_task","bridge_fail_task")}`,executor:`# Bridge Worker \u2014 Executor Role
230
+ ${Ee("bridge_get_plan","bridge_get_project_history","bridge_get_todos","bridge_add_todo","bridge_complete_task","bridge_fail_task")}`,executor:`# Bridge Worker \u2014 Executor Role
231
231
 
232
232
  You are an **Executor** worker in a multi-agent orchestration system called Bridge.
233
233
 
@@ -237,7 +237,7 @@ You are an **Executor** worker in a multi-agent orchestration system called Brid
237
237
  - Capture and report all relevant output
238
238
  - Call \`bridge_complete_task\` on success, \`bridge_fail_task\` with error details on failure
239
239
 
240
- ${xe("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,shell:`# Bridge Worker \u2014 Shell Role
240
+ ${Ee("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,shell:`# Bridge Worker \u2014 Shell Role
241
241
 
242
242
  You are a **Shell** worker in a multi-agent orchestration system called Bridge.
243
243
 
@@ -247,7 +247,7 @@ You are a **Shell** worker in a multi-agent orchestration system called Bridge.
247
247
  - Call \`bridge_complete_task\` when the command exits cleanly
248
248
  - Call \`bridge_fail_task\` with the error output if the command fails
249
249
 
250
- ${xe("bridge_get_my_task","bridge_complete_task","bridge_fail_task")}`,orchestrator:`# Bridge Orchestrator
250
+ ${Ee("bridge_get_my_task","bridge_complete_task","bridge_fail_task")}`,orchestrator:`# Bridge Orchestrator
251
251
 
252
252
  You are a **Bridge Orchestrator**. Your sole purpose is to decompose specs into todos, delegate them to worker agents, and report results. Nothing else.
253
253
 
@@ -255,10 +255,29 @@ You are a **Bridge Orchestrator**. Your sole purpose is to decompose specs into
255
255
 
256
256
  ## Identity constraints (absolute)
257
257
 
258
- - Do NOT answer questions, browse files, run bash, or use mem0
258
+ - Do NOT browse files, run bash, or use mem0
259
259
  - Do NOT call any tool not listed in the tool reference below \u2014 if a tool isn't listed, it does not exist
260
260
  - Do NOT ask "should I start?" / "shall I proceed?" \u2014 if you have work and workers, act
261
- - If a user asks you to do something outside orchestration, respond: "I'm an orchestrator. Give me a task spec and I'll delegate it to workers."
261
+ - If a user asks you for IMPLEMENTATION work outside orchestration, respond: "I'm an orchestrator. Give me a task spec and I'll delegate it to workers."
262
+
263
+ ## Workspace queries (exception to the no-questions rule)
264
+ When the user asks about workspace topology \u2014 groups, agents, runs, projects \u2014 answer directly using the workspace tools below. Do NOT delegate these queries to workers.
265
+
266
+ Examples of answerable queries:
267
+ - "What groups are there?" \u2192 bridge_list_groups
268
+ - "What are workers in group X doing?" \u2192 bridge_get_group_status
269
+ - "What runs are active?" \u2192 bridge_list_active_runs
270
+ - "What failed last time?" \u2192 bridge_query_workspace
271
+ - "What is agent-X doing?" \u2192 bridge_peek_panel(agentId, 50)
272
+ - "Show me agent-X status" \u2192 bridge_status_panel(agentId)
273
+
274
+ Only delegate when the user asks for IMPLEMENTATION work (code changes, deployments).
275
+
276
+ ## Runtime context
277
+ Workspace: {{WORKSPACE_ID}}
278
+ Project: {{PROJECT_ID}}
279
+ Group: {{GROUP_ID}}
280
+ Your panel ID: {{PANEL_ID}}
262
281
 
263
282
  **Your own agent ID: \`{{PANEL_ID}}\`**
264
283
  Never call \`bridge_kill_agent\` with this ID \u2014 killing yourself terminates the orchestration session.
@@ -340,7 +359,7 @@ Summarize: todos completed, failed, any blockers. List what workers did.
340
359
 
341
360
  ---
342
361
 
343
- ${_a("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo","bridge_cancel_run","bridge_get_project_history","bridge_get_execution_status","bridge_list_agents","bridge_get_agent_status","bridge_spawn_worker","bridge_assign_task","bridge_get_todo_context","bridge_get_agent_output","bridge_kill_agent")}`},ba=`# Bridge Worker \u2014 Reviewer Role (SCRIPTED TEST MODE)
362
+ ${Oa("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo","bridge_cancel_run","bridge_get_project_history","bridge_get_execution_status","bridge_list_agents","bridge_get_agent_status","bridge_spawn_worker","bridge_assign_task","bridge_get_todo_context","bridge_get_agent_output","bridge_kill_agent","bridge_list_groups","bridge_get_group_status","bridge_dispatch_to_group","bridge_list_workspace_projects","bridge_query_workspace","bridge_list_active_runs","bridge_peek_panel","bridge_status_panel")}`},Ca=`# Bridge Worker \u2014 Reviewer Role (SCRIPTED TEST MODE)
344
363
 
345
364
  You are a test-mode reviewer. DO NOT apply AI judgment. Apply the mechanical rule below.
346
365
 
@@ -359,37 +378,43 @@ You are a test-mode reviewer. DO NOT apply AI judgment. Apply the mechanical rul
359
378
  - Decide solely based on (todo.retryCount ?? 0) > 0
360
379
  - This is a signaling mechanic test, not a code quality review
361
380
 
362
- ${xe("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context")}`;function ys(r){let e=process.env.BRIDGE_TEST_SCRIPTED_REVIEW,t=r==="reviewer"&&e==="1";return console.log("[daemon] getRoleSystemPrompt.called",{role:r,envFlag:e,returning:t?"SCRIPTED":"NORMAL"}),t?ba:ya[r]}function wa(r,e,t){if(!e)return[];let n=ys(e);if(!n)return[];if(r==="claude")try{let s=$.default.join(J.default.tmpdir(),`bridge-role-${t}.md`),i=n.replaceAll("{{PANEL_ID}}",t);return F.default.writeFileSync(s,i+`
363
- `,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:s}),["--append-system-prompt-file",s]}catch(s){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(s)}),[]}return r==="qwen"?["--append-system-prompt",n]:[]}function Be(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Sa(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:ht(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=$.default.join(J.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??r.projectId}.json`);return F.default.writeFileSync(n,JSON.stringify(t,null,2)+`
364
- `,"utf-8"),console.log("[daemon] kimi.mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config-file",n]}catch(e){return console.warn("[daemon] kimi.mcp.config.build.failed",{error:String(e)}),[]}}function Ea(r){try{let e=ht(),t=`{BRIDGE_SERVER_URL=${Be(r.serverUrl)},BRIDGE_TOKEN=${Be(r.token)},BRIDGE_WORKSPACE_ID=${Be(r.workspaceId)},BRIDGE_PROJECT_ID=${Be(r.projectId)},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Be(e)}`,"-c","mcp_servers.bridge.args=[]","-c",`mcp_servers.bridge.env=${t}`]}catch(e){return console.warn("[daemon] codex.mcp.config.build.failed",{error:String(e)}),[]}}function va(r){try{return F.default.statSync(r).isDirectory()}catch{return!1}}function dr(r,e){try{return e(r)}catch{return!1}}function xa(r,e,t,n,s=va){let i=n?.[r];if(i&&dr(i,s))return{path:i,source:"local_override"};if(t){if(dr(t,s))return{path:t,source:"daemon_override"};console.warn("[daemon] spawn.cwd.daemon_override_missing",{projectId:r,daemonLocalPath:t,hint:`Run: jerico link-project ${r} <local-path>`})}return e&&dr(e,s)?{path:e,source:"server_project"}:(console.warn("[daemon] spawn.cwd.fallback_home",{projectId:r,serverCwd:e,localOverride:i,daemonLocalPath:t??void 0,hint:`Set projectPaths["${r}"] in ~/.jerico/settings.json`}),{path:J.default.homedir(),source:"fallback_home"})}function ka(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId}),!1;let e=ht(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,dt.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,dt.spawnSync)("qwen",["mcp","add","--scope","project","-t","stdio","-e",`BRIDGE_SERVER_URL=${r.serverUrl}`,"-e",`BRIDGE_TOKEN=${r.token}`,"-e",`BRIDGE_WORKSPACE_ID=${r.workspaceId}`,"-e",`BRIDGE_PROJECT_ID=${r.projectId}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return n.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:n.status,stderr:(n.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] qwen.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}var ut=[],hr=!1,_s=!1;function bs(){return hr}function ws(r){if(_s)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");if(_s=!0,process.env.BRIDGE_TEST_SCRIPTED_REVIEW!=="1")try{let c=$.default.join(J.default.homedir(),".jerico","settings.json");F.default.existsSync(c)&&JSON.parse(F.default.readFileSync(c,"utf-8")).testScriptedReview===!0&&(process.env.BRIDGE_TEST_SCRIPTED_REVIEW="1",console.log("[daemon] scripted-review-mode enabled from ~/.jerico/settings.json"))}catch{}process.env.BRIDGE_TEST_SCRIPTED_REVIEW==="1"&&console.log("[daemon] scripted-review-mode ENABLED");let e=ie(),t=(0,fr.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0;function l(){s&&(clearTimeout(s),s=null),n=new C(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let c=n,d=null;c.on("open",()=>{hr=!0,console.log("[daemon] ws.connected",{server:e.server}),i=setInterval(()=>{c.readyState===C.OPEN&&c.ping()},la);let u=!ms();c.send(JSON.stringify({type:"ready",version:"1.1",name:e.name,spawnHelperBroken:u,liveAgentIds:r.getLiveAgentIds(),machineFingerprint:ia()})),Dt(e.agentPaths).then(h=>{ut=h,c.readyState===C.OPEN&&c.send(JSON.stringify({type:"agents",list:ut}))}),d=ps(h=>{c.readyState===C.OPEN&&c.send(JSON.stringify({type:"system_metrics",daemonId:t,...h}))})}),c.on("message",u=>{let h;try{h=JSON.parse(u.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}Oa(h,c,r,e)}),c.on("close",u=>{hr=!1,i&&(clearInterval(i),i=null),d?.(),d=null,u===1008?(o++,o>=2&&(console.error("[daemon] ws.auth_failed \u2014 token invalid or expired (2 consecutive rejections), stopping. Re-run: bridge-agent auth"),process.exit(1)),console.warn("[daemon] ws.auth_rejected \u2014 transient 1008, will retry once",{attempt:o})):o=0,!s&&(console.log("[daemon] ws.reconnecting",{attempt:1}),s=setTimeout(l,3e3))}),c.on("error",u=>{console.error("[daemon] ws.error",{message:u.message})})}function a(){i&&(clearInterval(i),i=null),ca();for(let c of ae.values())c();r.killAll(),n?.close()}process.on("SIGINT",()=>{a(),process.exit(0)}),process.on("SIGTERM",()=>{a(),process.exit(0)}),process.on("SIGHUP",()=>{a(),process.exit(0)}),process.on("uncaughtException",c=>{console.error("[daemon] uncaughtException",{error:c.message}),r.killAll(),process.exit(1)}),l()}function Oa(r,e,t,n){switch(r.type){case"spawn":{console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role});let s=ut.find(y=>y.key===r.agentKey);if(!s){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=fe.find(y=>y.key===r.agentKey),o=[];if(r.sessionId&&i?.resumeArgs)o=i.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(ae.get(r.agentId)?.(),ae.set(r.agentId,or(r.agentId,r.sessionId,(y,w,S)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:y,usedPct:w,usedTokens:S,...ur}))})));else if(i?.assignSessionId){let y=crypto.randomUUID(),w=r.agentKey==="kimi"?"--session":"--session-id";o=[...i.spawnArgs??[],w,y],e.readyState===C.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:y})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:y})),r.agentKey==="claude"&&(ae.get(r.agentId)?.(),ae.set(r.agentId,or(r.agentId,y,(S,N,E)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:S,usedPct:N,usedTokens:E,...ur}))})))}else e.readyState===C.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let l,a=!1,c,d;if(r.projectId&&r.workspaceId){let y=pa(n.server),w=xa(r.projectId,r.cwd,r.daemonLocalPath,n.projectPaths),S=w.path;d=w.source;let N=sr(S);if(l={serverUrl:y,token:n.token,workspaceId:ss(r.workspaceId),projectId:is(r.projectId),agentId:r.agentId?ns(r.agentId):void 0,cwd:S,projectEnv:N.env},r.agentKey==="claude"){let E=ga(l);a=E.length>0,c=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...E]}else if(r.agentKey==="codex"){let E=Ea(l);a=E.length>0,c="stdio",o=[...o,...E]}else if(r.agentKey==="qwen")a=ka(l),c=a?"stdio":void 0;else if(r.agentKey==="kimi"){let E=Sa(l);a=E.length>0,c=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...E]}else a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"});if(rr("phase2a.verified_at")&&(w.source==="daemon_override"||w.source==="server_project")){let E=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths/${r.daemonId}/verify`;fetch(E,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:"{}"}).catch(U=>{console.warn("[daemon] verify.patch_failed",{projectId:r.projectId,error:String(U)})})}if(rr("phase2a.auto_register")&&(w.source==="daemon_override"||w.source==="server_project"))try{let E=(0,dt.spawnSync)("git",["remote","get-url","origin"],{cwd:S,timeout:5e3,encoding:"utf-8"});if(E.status===0&&E.stdout&&E.stdout.trim()){let U=E.stdout.trim();n.projectPaths||(n.projectPaths={}),n.projectPaths[r.projectId]=S,oe(n);let pt=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths`;fetch(pt,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({daemonId:r.daemonId,localPath:S,repoUrl:U})}).catch(Ds=>{console.warn("[daemon] auto_register.post_failed",{projectId:r.projectId,error:String(Ds)})}),console.log("[daemon] auto_register.ok",{projectId:r.projectId,localPath:S,repoUrl:U})}}catch(E){console.log("[daemon] auto_register.skipped",{projectId:r.projectId,reason:String(E)})}}let u=wa(r.agentKey,r.role,r.agentId);u.length>0&&(o=[...o,...u]);let h=Math.max(1,Math.min(500,r.cols)),g=Math.max(1,Math.min(500,r.rows)),p=Date.now(),f="",m=0,x=!1,b=!1;if(t.spawn(r.agentId,r.agentKey,s.binaryPath,o,h,g,y=>{m+=y.length;try{let w=Buffer.from(y,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!b&&Date.now()-p<3e4&&(/yolo agent/.test(w)||/●/.test(w)||/○/.test(w))){b=!0;let S=ys(r.role);if(S){let N=S.replaceAll("{{PANEL_ID}}",r.agentId),E=aa(N),U=Buffer.from(E).toString("base64");t.write(r.agentId,U,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let w=Buffer.from(y,"base64").toString("utf-8"),S=ha(w).replace(/\x00/g,"").trim();if(S&&(f=fa(S)),r.agentKey==="codex"&&!x&&Date.now()-p<2e4&&/included in your plan for free|let[’']s build together/i.test(S)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(S)){x=!0;let N=Buffer.from("y").toString("base64");t.write(r.agentId,N,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:y}))},(y,w)=>{let S=Date.now()-p,N=S<=da;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:y,signal:w,uptimeMs:S,earlyExit:N,outputBytes:m,firstOutputSnippet:f||void 0}),N&&e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${y??"null"} signal=${w??"null"} snippet="${f||"no output"}"`})),e.readyState===C.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:y,signal:w}))},l))e.readyState===C.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?c:void 0,projectId:l?.projectId,effectiveCwd:l?.cwd,cwdSource:d}));else{let w=t.getLastError(r.agentId)?.includes("posix_spawnp failed")&&oa(r.agentKey);e.readyState===C.OPEN&&(w?e.send(JSON.stringify({type:"error",code:"SPAWN_HELPER_BROKEN",message:"node-pty spawn-helper is not executable. Upgrade bridge-agent to v0.2.10+."})):e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`})))}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agent_spawned",agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,role:r.role}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":ae.get(r.agentId)?.(),ae.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":Dt(n.agentPaths).then(s=>{ut=s,e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=J.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=$.default.resolve(i);if(o!==s&&!o.startsWith(s+$.default.sep)){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let l=F.default.readdirSync(o,{withFileTypes:!0}).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).map(a=>({name:a.name,path:$.default.join(o,a.name)})).sort((a,c)=>a.name.localeCompare(c.name));e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:l}))}catch(l){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:[],error:l instanceof Error?l.message:"Cannot read directory"}))}break}default:{let s=r}}}var Es="com.jerico.bridge-agent.plist",vs=D.default.join((0,Z.homedir)(),"Library","LaunchAgents"),ft=D.default.join(vs,Es),pr=D.default.join((0,Z.homedir)(),"bridge-daemon.log"),gr=D.default.join((0,Z.homedir)(),"bridge-daemon.err.log"),ce=D.default.join((0,Z.homedir)(),".bridge","daemon.lock");function Ca(){let r=[...process.env.npm_config_global_prefix?[D.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function Ia(){try{(0,P.mkdirSync)(D.default.dirname(ce),{recursive:!0})}catch{}if((0,P.existsSync)(ce))try{let{pid:r}=JSON.parse((0,P.readFileSync)(ce,"utf8"));if(r&&process.kill(r,0))return console.warn("[bridge] daemon.already.running",{pid:r,lock:ce}),!1;(0,P.unlinkSync)(ce)}catch{try{(0,P.unlinkSync)(ce)}catch{}}try{let r=(0,P.openSync)(ce,"wx");return(0,P.writeSync)(r,JSON.stringify({pid:process.pid,startedAt:Date.now()})),(0,P.closeSync)(r),!0}catch{return!1}}function xs(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(D.default.join((0,Z.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(D.default.join((0,Z.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,le.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(D.default.dirname(i))}catch{}let n=D.default.join((0,Z.homedir)(),".vscode","extensions");try{let s=(0,le.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
365
- `);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=D.default.join(n,i,"resources","native-binary");(0,P.existsSync)(o)&&e.add(o)}}catch{}return[...e].join(":")}function Aa(r){try{(0,le.execSync)(`mkdir -p "${vs}"`,{stdio:"pipe"})}catch{}let e=xs(),t=`<?xml version="1.0" encoding="UTF-8"?>
381
+ ${Ee("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context")}`;function As(r){let e=process.env.BRIDGE_TEST_SCRIPTED_REVIEW,t=r==="reviewer"&&e==="1";return console.log("[daemon] getRoleSystemPrompt.called",{role:r,envFlag:e,returning:t?"SCRIPTED":"NORMAL"}),t?Ca:Ia[r]}function Aa(r,e,t,n,s,i){if(!e)return[];let o=As(e);if(!o)return[];let c=o.replaceAll("{{PANEL_ID}}",t).replaceAll("{{WORKSPACE_ID}}",n??"unknown").replaceAll("{{PROJECT_ID}}",s??"none").replaceAll("{{GROUP_ID}}",i??"none");if(r==="claude")try{let a=j.default.join(F.default.tmpdir(),`bridge-role-${t}.md`);return W.default.writeFileSync(a,c+`
382
+ `,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a}),["--append-system-prompt-file",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(a)}),[]}if(r==="qwen")return["--append-system-prompt",c];if(r==="aider")try{let a=j.default.join(F.default.tmpdir(),`bridge-role-${t}.md`);return W.default.writeFileSync(a,c+`
383
+ `,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a,agentKey:"aider"}),["--read",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,agentKey:"aider",error:String(a)}),[]}return r==="codex"?[]:[]}function We(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Pa(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId||"workspace"}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:wt(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId||"workspace",BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=j.default.join(F.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??(r.projectId||"workspace")}.json`);return W.default.writeFileSync(n,JSON.stringify(t,null,2)+`
384
+ `,"utf-8"),console.log("[daemon] kimi.mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config-file",n]}catch(e){return console.warn("[daemon] kimi.mcp.config.build.failed",{error:String(e)}),[]}}function Ta(r){try{let e=wt(),t=`{BRIDGE_SERVER_URL=${We(r.serverUrl)},BRIDGE_TOKEN=${We(r.token)},BRIDGE_WORKSPACE_ID=${We(r.workspaceId)},BRIDGE_PROJECT_ID=${We(r.projectId||"workspace")},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${We(e)}`,"-c","mcp_servers.bridge.args=[]","-c",`mcp_servers.bridge.env=${t}`]}catch(e){return console.warn("[daemon] codex.mcp.config.build.failed",{error:String(e)}),[]}}function Na(r){try{return W.default.statSync(r).isDirectory()}catch{return!1}}function br(r,e){try{return e(r)}catch{return!1}}function Da(r,e,t,n,s=Na){let i=n?.[r];if(i&&br(i,s))return{path:i,source:"local_override"};if(t){if(br(t,s))return{path:t,source:"daemon_override"};console.warn("[daemon] spawn.cwd.daemon_override_missing",{projectId:r,daemonLocalPath:t,hint:`Run: jerico link-project ${r} <local-path>`})}return e&&br(e,s)?{path:e,source:"server_project"}:(console.warn("[daemon] spawn.cwd.fallback_home",{projectId:r,serverCwd:e,localOverride:i,daemonLocalPath:t??void 0,hint:`Set projectPaths["${r}"] in ~/.jerico/settings.json`}),{path:F.default.homedir(),source:"fallback_home"})}function Ra(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId||"workspace"}),!1;let e=wt(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,yt.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,yt.spawnSync)("qwen",["mcp","add","--scope","project","-t","stdio","-e",`BRIDGE_SERVER_URL=${r.serverUrl}`,"-e",`BRIDGE_TOKEN=${r.token}`,"-e",`BRIDGE_WORKSPACE_ID=${r.workspaceId}`,"-e",`BRIDGE_PROJECT_ID=${r.projectId||"workspace"}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return n.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId||"workspace"}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:n.status,stderr:(n.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] qwen.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}var bt=[],Sr=!1,Cs=!1;function Ps(){return Sr}function Ts(r){if(Cs)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");if(Cs=!0,process.env.BRIDGE_TEST_SCRIPTED_REVIEW!=="1")try{let p=j.default.join(F.default.homedir(),".jerico","settings.json");W.default.existsSync(p)&&JSON.parse(W.default.readFileSync(p,"utf-8")).testScriptedReview===!0&&(process.env.BRIDGE_TEST_SCRIPTED_REVIEW="1",console.log("[daemon] scripted-review-mode enabled from ~/.jerico/settings.json"))}catch{}process.env.BRIDGE_TEST_SCRIPTED_REVIEW==="1"&&console.log("[daemon] scripted-review-mode ENABLED");let e=ie(),t=(0,Fe.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0,c=0,a=0n;function l(){s&&(clearTimeout(s),s=null);let p=Date.now(),g=process.hrtime.bigint();n=new C(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let h=n,f=(0,Fe.randomUUID)();yr=f;let m=F.default.networkInterfaces(),k=Object.entries(m).flatMap(([E,b])=>(b||[]).filter(D=>!D.internal).map(D=>({iface:E,address:D.address,family:D.family}))),S=JSON.stringify(k);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"net.interfaces",interfaces:k,connectionId:f})),_t&&_t!==S&&console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"net.interfaces.changed",previous:_t,current:S,connectionId:f})),_t=S;let N=h.send.bind(h);h.send=function(E){if(h.readyState!==C.OPEN){let b="unknown";try{b=JSON.parse(E).type}catch{}console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.send.dropped",messageType:b,readyState:h.readyState,connectionId:f}));return}return N(E)},console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connecting",server:e.server,connectionId:f}));let y=null,v=0,w=null;h.on("open",()=>{Sr=!0,c=0,a=0n,console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connected",server:e.server,connectionId:f})),i=setInterval(()=>{h.readyState===C.OPEN&&(h.ping(),v=Date.now(),w&&clearTimeout(w),w=setTimeout(()=>{console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.heartbeat.timeout",connectionId:f})),h.terminate()},ya))},_a);let E=!Is();h.send(JSON.stringify({type:"ready",version:"1.1",name:e.name,spawnHelperBroken:E,liveAgentIds:r.getLiveAgentIds(),machineFingerprint:vr(),connectionId:f})),Ft(e.agentPaths).then(b=>{bt=b,h.readyState===C.OPEN&&h.send(JSON.stringify({type:"agents",list:bt}))}),y=xs(b=>{h.readyState===C.OPEN&&h.send(JSON.stringify({type:"system_metrics",daemonId:t,...b}))})}),h.on("message",E=>{let b;try{b=JSON.parse(E.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}La(b,h,r,e)}),h.on("pong",()=>{w&&(clearTimeout(w),w=null);let E=Date.now()-v;console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.heartbeat.pong",rttMs:E,connectionId:f}))}),h.on("close",(E,b)=>{Sr=!1,i&&(clearInterval(i),i=null),w&&(clearTimeout(w),w=null),y?.(),y=null,E===1008?(o++,o>=2&&(console.error("[daemon] ws.auth_failed \u2014 token invalid or expired (2 consecutive rejections), stopping. Re-run: bridge-agent auth"),process.exit(1)),console.warn("[daemon] ws.auth_rejected \u2014 transient 1008, will retry once",{attempt:o})):o=0;let D=Number((process.hrtime.bigint()-g)/1000000n);if(console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.closed",code:E,reason:b?.toString()||void 0,uptimeMs:D,connectionId:f})),s)return;c===0&&(a=process.hrtime.bigint()),c++;let xe=Number((process.hrtime.bigint()-a)/1000000n);c>=10&&xe<6e4&&(console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.reconnect.storm",reconnectCount:c,connectionId:f})),process.exit(1));let vt=Math.min(3e4,1e3*Math.pow(2,Math.min(c,5))),xr=Math.round(vt+Math.random()*500);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.reconnect.scheduled",delayMs:xr,reconnectCount:c,connectionId:f})),s=setTimeout(l,xr)}),h.on("error",E=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.error",message:E.message,code:E.code,connectionId:f}))})}function d(){i&&(clearInterval(i),i=null),r.stopLivenessCheck(),ma();for(let p of ae.values())p();r.killAll(),n?.close()}function u(p){console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.signal",signal:p,connectionId:yr})),d(),setTimeout(()=>process.exit(0),100)}process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),process.on("SIGHUP",()=>u("SIGHUP")),process.on("uncaughtException",p=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"daemon.uncaught",error:String(p),stack:p.stack,connectionId:yr})),r.killAll(),process.exit(1)}),l()}function La(r,e,t,n){switch(r.type){case"spawn":{console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role});let s=bt.find(y=>y.key===r.agentKey);if(!s){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=he.find(y=>y.key===r.agentKey),o=[];if(r.sessionId&&i?.resumeArgs)o=i.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(ae.get(r.agentId)?.(),ae.set(r.agentId,pr(r.agentId,r.sessionId,(y,v,w)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:y,usedPct:v,usedTokens:w,...wr}))})));else if(i?.assignSessionId){let y=crypto.randomUUID(),v=r.agentKey==="kimi"?"--session":"--session-id";o=[...i.spawnArgs??[],v,y],e.readyState===C.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:y})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:y})),r.agentKey==="claude"&&(ae.get(r.agentId)?.(),ae.set(r.agentId,pr(r.agentId,y,(w,E,b)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:w,usedPct:E,usedTokens:b,...wr}))})))}else e.readyState===C.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let c,a=!1,l,d;if(r.workspaceId){let y=Ea(n.server),v=Da(r.projectId??"",r.cwd,r.daemonLocalPath,n.projectPaths),w=v.path;d=v.source;let E=hr(w);if(c={serverUrl:y,token:n.token,workspaceId:fs(r.workspaceId),projectId:r.projectId?ps(r.projectId):void 0,agentId:r.agentId?hs(r.agentId):void 0,cwd:w,projectEnv:E.env},r.agentKey==="claude"){let b=ka(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else if(r.agentKey==="codex"){let b=Ta(c);a=b.length>0,l="stdio",o=[...o,...b]}else if(r.agentKey==="qwen")a=Ra(c),l=a?"stdio":void 0;else if(r.agentKey==="kimi"){let b=Pa(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"});if(dr("phase2a.verified_at")&&(v.source==="daemon_override"||v.source==="server_project")){let b=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths/${r.daemonId}/verify`;fetch(b,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:"{}"}).catch(D=>{console.warn("[daemon] verify.patch_failed",{projectId:r.projectId,error:String(D)})})}if(dr("phase2a.auto_register")&&(v.source==="daemon_override"||v.source==="server_project"))try{let b=(0,yt.spawnSync)("git",["remote","get-url","origin"],{cwd:w,timeout:5e3,encoding:"utf-8"});if(b.status===0&&b.stdout&&b.stdout.trim()){let D=b.stdout.trim();r.projectId&&(n.projectPaths||(n.projectPaths={}),n.projectPaths[r.projectId]=w,oe(n));let xe=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths`;fetch(xe,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({daemonId:r.daemonId,localPath:w,repoUrl:D})}).catch(vt=>{console.warn("[daemon] auto_register.post_failed",{projectId:r.projectId,error:String(vt)})}),console.log("[daemon] auto_register.ok",{projectId:r.projectId,localPath:w,repoUrl:D})}}catch(b){console.log("[daemon] auto_register.skipped",{projectId:r.projectId,reason:String(b)})}}let u=Aa(r.agentKey,r.role,r.agentId,r.workspaceId,r.projectId,r.groupId);u.length>0&&(o=[...o,...u]);let p=Math.max(1,Math.min(500,r.cols)),g=Math.max(1,Math.min(500,r.rows)),h=Date.now(),f="",m=0,k=!1,S=!1;if(t.spawn(r.agentId,r.agentKey,s.binaryPath,o,p,g,y=>{m+=y.length;try{let v=Buffer.from(y,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!S&&Date.now()-h<3e4&&(/yolo agent/.test(v)||/●/.test(v)||/○/.test(v))){S=!0;let w=As(r.role);if(w){let E=w.replaceAll("{{PANEL_ID}}",r.agentId).replaceAll("{{WORKSPACE_ID}}",r.workspaceId??"unknown").replaceAll("{{PROJECT_ID}}",r.projectId??"none").replaceAll("{{GROUP_ID}}",r.groupId??"none"),b=ga(E),D=Buffer.from(b).toString("base64");t.write(r.agentId,D,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let v=Buffer.from(y,"base64").toString("utf-8"),w=Sa(v).replace(/\x00/g,"").trim();if(w&&(f=va(w)),r.agentKey==="codex"&&!k&&Date.now()-h<2e4&&/included in your plan for free|let[’']s build together/i.test(w)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(w)){k=!0;let E=Buffer.from("y").toString("base64");t.write(r.agentId,E,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:y}))},(y,v)=>{let w=Date.now()-h,E=w<=ba;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:y,signal:v,uptimeMs:w,earlyExit:E,outputBytes:m,firstOutputSnippet:f||void 0}),E&&e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${y??"null"} signal=${v??"null"} snippet="${f||"no output"}"`})),e.readyState===C.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:y,signal:v}))},c))e.readyState===C.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?l:void 0,projectId:c?.projectId,effectiveCwd:c?.cwd,cwdSource:d}));else{let v=t.getLastError(r.agentId)?.includes("posix_spawnp failed")&&pa(r.agentKey);e.readyState===C.OPEN&&(v?e.send(JSON.stringify({type:"error",code:"SPAWN_HELPER_BROKEN",message:"node-pty spawn-helper is not executable. Upgrade bridge-agent to v0.2.10+."})):e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`})))}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agent_spawned",agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,role:r.role}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":ae.get(r.agentId)?.(),ae.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":Ft(n.agentPaths).then(s=>{bt=s,e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=F.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=j.default.resolve(i);if(o!==s&&!o.startsWith(s+j.default.sep)){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let c=W.default.readdirSync(o,{withFileTypes:!0}).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).map(a=>({name:a.name,path:j.default.join(o,a.name)})).sort((a,l)=>a.name.localeCompare(l.name));e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:c}))}catch(c){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:[],error:c instanceof Error?c.message:"Cannot read directory"}))}break}default:{let s=r}}}ht();var St=R.default.join((0,ke.homedir)(),"Library","LaunchAgents");function ja(){let r=[...process.env.npm_config_global_prefix?[R.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function Ds(){let r=ur();if((0,A.existsSync)(r))try{let{pid:e}=JSON.parse((0,A.readFileSync)(r,"utf8"));if(e&&process.kill(e,0))return;(0,A.unlinkSync)(r)}catch{try{(0,A.unlinkSync)(r)}catch{}}}function Ma(){let r=ur();try{(0,A.mkdirSync)(R.default.dirname(r),{recursive:!0})}catch{}Ds();try{let e=(0,A.openSync)(r,"wx");return(0,A.writeSync)(e,JSON.stringify({pid:process.pid,startedAt:Date.now()})),(0,A.closeSync)(e),!0}catch{return!1}}function Rs(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(R.default.join((0,ke.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(R.default.join((0,ke.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,ce.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(R.default.dirname(i))}catch{}let n=R.default.join((0,ke.homedir)(),".vscode","extensions");try{let s=(0,ce.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
385
+ `);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=R.default.join(n,i,"resources","native-binary");(0,A.existsSync)(o)&&e.add(o)}}catch{}return[...e].join(":")}function $a(r){try{(0,ce.execSync)(`mkdir -p "${St}"`,{stdio:"pipe"})}catch{}let e=dt(),t=R.default.join(St,e),{out:n,err:s}=ut(),i=Rs(),o=process.env.BRIDGE_PROFILE||"",c=e.replace(".plist",""),a=o?` <key>BRIDGE_PROFILE</key>
386
+ <string>${o}</string>
387
+ `:"",l=R.default.join((0,ke.homedir)(),".bridge"),d=R.default.join(l,"bridge-agent-wrapper.sh"),u=`#!/bin/bash
388
+ exec "$(command -v node)" "${r}" start
389
+ `;try{(0,A.mkdirSync)(l,{recursive:!0}),(0,A.writeFileSync)(d,u,{mode:493})}catch{}let p=`<?xml version="1.0" encoding="UTF-8"?>
366
390
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
367
391
  <plist version="1.0">
368
392
  <dict>
369
393
  <key>Label</key>
370
- <string>com.jerico.bridge-agent</string>
394
+ <string>${c}</string>
371
395
  <key>ProgramArguments</key>
372
396
  <array>
373
- <string>${r}</string>
374
- <string>start</string>
397
+ <string>${d}</string>
375
398
  </array>
376
399
  <key>RunAtLoad</key>
377
400
  <true/>
378
401
  <key>KeepAlive</key>
379
402
  <true/>
403
+ <key>ThrottleInterval</key>
404
+ <integer>30</integer>
380
405
  <key>StandardOutPath</key>
381
- <string>${pr}</string>
406
+ <string>${n}</string>
382
407
  <key>StandardErrorPath</key>
383
- <string>${gr}</string>
408
+ <string>${s}</string>
384
409
  <key>EnvironmentVariables</key>
385
410
  <dict>
386
411
  <key>PATH</key>
387
- <string>${e}</string>
412
+ <string>${i}</string>
388
413
  <key>BRIDGE_DAEMON</key>
389
414
  <string>1</string>
390
- </dict>
415
+ ${a} </dict>
391
416
  </dict>
392
417
  </plist>
393
- `;try{return(0,P.writeFileSync)(ft,t,"utf-8"),!0}catch(n){return console.warn("[bridge] launchd.plist.write.failed",{error:String(n)}),!1}}function Pa(){try{return(0,le.execSync)(`launchctl kickstart -kp gui/$(id -u)/${Es} 2>/dev/null; launchctl unload "${ft}" 2>/dev/null; launchctl load "${ft}"`,{stdio:"pipe"}),{ok:!0,permissionDenied:!1}}catch(r){let e=String(r);return{ok:!1,permissionDenied:e.includes("Permission denied")||e.includes("not allowed")||e.includes("bootstrap")}}}function Ta(r){try{let e=(0,le.spawn)(r,["start"],{detached:!0,stdio:"ignore",env:{...process.env,PATH:xs(),BRIDGE_DAEMON:"1"}});e.unref(),setTimeout(()=>{e.pid&&process.kill(e.pid,0)?(console.log("[bridge] daemon.pid",{pid:e.pid}),console.log("[bridge] background.ok",{log:pr})):console.error("[bridge] background.failed \u2014 check: tail -f",{log:gr})},2e3)}catch(e){console.error("[bridge] background.spawn.failed",{error:String(e)})}}function Na(){let r=parseInt(process.env.HEALTH_PORT??"3101",10),e=Date.now()+6e3,t=()=>{if(Date.now()>e){console.error("[bridge] health.verify.timeout \u2014 daemon may have crashed immediately");return}try{let s=require("node:http").get(`http://127.0.0.1:${r}/health`,i=>{i.statusCode===200?console.log("[bridge] health.verify.ok"):setTimeout(t,500)});s.on("error",()=>{setTimeout(t,500)}),s.setTimeout(1e3,()=>{s.destroy(),setTimeout(t,500)})}catch{setTimeout(t,500)}};setTimeout(t,1e3)}function Ra(){let r=new Ve;ws(r);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,Ss.createServer)((n,s)=>{let i=bs(),o=JSON.stringify({status:"ok",connected:i,uptime:process.uptime()});s.writeHead(i?200:503,{"Content-Type":"application/json"}),s.end(o)});t.listen(e,"127.0.0.1",()=>{console.log(`[bridge] health. listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.error",{error:n.message})})}function ks(){let r=process.env.BRIDGE_DAEMON==="1"||process.argv.includes("--daemon");if(console.log("[bridge] Starting bridge-agent daemon..."),r){Ra();return}Ia()||(console.warn("[bridge] start.aborted.already.running"),process.exit(1));let e=Ca(),t=Aa(e),{ok:n,permissionDenied:s}=t?Pa():{ok:!1,permissionDenied:!1};if(n){console.log("[bridge] launchd.ok \u2014 managed, auto-restart enabled"),console.log("[bridge] logs: tail -f",{out:pr,err:gr}),Na(),process.exit(0);return}s&&(console.warn("[bridge] launchd.permission.denied"),console.warn("[bridge] \u2192 Auto-start on login requires:"),console.warn(`[bridge] sudo launchctl bootstrap gui/$(id -u) "${ft}"`),console.warn(`[bridge] Falling back to background process...
394
- `)),Ta(e),process.exit(0)}var Os=_(require("https")),Cs=_(require("http"));Ee();function Da(r){return(r??"").trim()}async function Is(r,e=!1,t){console.log("[bridge] Starting auth flow..."),console.log(`[bridge] Server: ${r}`),console.log("[bridge] Open this URL to generate a daemon token:"),console.log(` ${r}/connect`);let n=Da(t);n&&console.log("[bridge] Using token from --token"),e&&(n?console.log("[bridge] --no-browser ignored because --token is provided."):(console.log("[bridge] --no-browser: exiting after printing URL."),process.exit(0)));let s=n;s||(console.log(),console.log("[bridge] After authenticating, paste your token here:"),s=await ja()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await La(r,s)||(console.error("[bridge] Token validation failed. Please try again."),process.exit(1));let l=r.replace(/^https?:\/\//,a=>a.startsWith("https")?"wss://":"ws://").replace(/\/?$/,"/ws/daemon");oe({server:l,token:s,name:process.env.HOSTNAME??"My Machine"}),console.log("[bridge] Auth successful! Config saved to ~/.bridge/config.json"),console.log("[bridge] Run: bridge-agent start"),process.exit(0)}async function ja(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
395
- `)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function La(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?Os.default:Cs.default,o={hostname:n.hostname,port:n.port||(s?443:80),path:n.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}},l=i.request(o,a=>{t(a.statusCode===200)});l.on("error",()=>t(!1)),l.end()})}var As=_(require("https")),Ps=_(require("http")),mr=_(require("fs")),_r=_(require("path")),Ts=require("node:crypto");Ee();function Ma(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function Ns(r,e,t){let n=ie(),s=(0,Ts.createHash)("sha256").update(n.token).digest("hex"),i=Ma(n.server),o=_r.default.resolve(t);_r.default.isAbsolute(o)||(console.error("[bridge] link-project: path must be absolute"),process.exit(1)),mr.default.existsSync(o)||(console.error("[bridge] link-project: path does not exist:",o),process.exit(1)),mr.default.statSync(o).isDirectory()||(console.error("[bridge] link-project: path must be a directory:",o),process.exit(1));let a=new URL(`/api/workspaces/${r}/projects/${e}/machine-paths`,i),c=a.protocol==="https:",d=c?As.default:Ps.default;n.projectPaths={...n.projectPaths??{},[e]:o},oe(n),console.log("[cli] link-project.local_json_written",{projectId:e,path:o});let u=JSON.stringify({daemonId:s,localPath:o}),h=await new Promise((g,p)=>{let f=d.request({hostname:a.hostname,port:a.port||(c?443:80),path:a.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"Content-Length":Buffer.byteLength(u)}},m=>{let x="";m.on("data",b=>{x+=b}),m.on("end",()=>{if(m.statusCode===200)g(200);else{try{let b=JSON.parse(x);console.error("[bridge] link-project failed:",b.error??`HTTP ${m.statusCode}`)}catch{console.error("[bridge] link-project failed:",`HTTP ${m.statusCode}`)}g(m.statusCode??0)}})});f.on("error",m=>{p(m)}),f.write(u),f.end()});h===200?(console.log("[cli] link-project.server_success",{projectId:e}),console.log("[cli] link-project.success (dual-write)"),console.log(` workspace: ${r}`),console.log(` project: ${e}`),console.log(` daemon: ${s.slice(0,16)}\u2026`),console.log(` path: ${o}`),console.log("[cli] Next spawn for this project will use the linked path."),process.exit(0)):(console.warn("[cli] link-project.server_fail",{projectId:e,statusCode:h}),console.log("[cli] Local override still active \u2014 path will work on this machine"),process.exit(0))}Ee();function $a(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function Rs(){let r=ie(),e=$a(r.server),t=await fetch(`${e}/api/admin/cleanup-orphans`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:"{}"});t.ok||(console.error(`[cli] cleanup-orphans: HTTP ${t.status}`),process.exit(1));let{deleted:n}=await t.json();console.log(`[cli] cleanup-orphans: deleted ${n} orphaned path ${n===1?"entry":"entries"}`),process.exit(0)}var de=new Tr;de.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.3.6");de.command("start").description("Start the bridge-agent daemon").action(()=>{ks()});de.command("auth").description("Authenticate with Bridge server").requiredOption("-s, --server <url>","Server URL (e.g., https://your-server.com)").option("-t, --token <token>","Use token non-interactively").option("--no-browser","Print auth URL without opening browser or interactive prompt").action(r=>{Is(r.server,!r.browser,r.token)});de.command("link-project <workspace-id> <project-id> <local-path>").description("Link a local directory to a project for this machine (Issue #152)").action((r,e,t)=>{Ns(r,e,t)});de.command("cleanup-orphans").description("Remove orphaned daemon_project_paths rows for this user").action(()=>{Rs()});de.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(Ee(),as)),e=r();console.log("[bridge] Config found"),console.log(" Server:",e.server),console.log(" Name:",e.name)}catch{console.log("[bridge] Not authenticated. Run: bridge-agent auth")}});de.parse();
418
+ `;try{return(0,A.writeFileSync)(t,p,"utf-8"),!0}catch(g){return console.warn("[bridge] launchd.plist.write.failed",{error:String(g)}),!1}}function Ba(){let r=dt(),e=R.default.join(St,r);try{return(0,ce.execSync)(`launchctl kickstart -kp gui/$(id -u)/${r} 2>/dev/null; launchctl unload "${e}" 2>/dev/null; launchctl load "${e}"`,{stdio:"pipe"}),{ok:!0,permissionDenied:!1}}catch(t){let n=String(t);return{ok:!1,permissionDenied:n.includes("Permission denied")||n.includes("not allowed")||n.includes("bootstrap")}}}function Ua(r){let{out:e,err:t}=ut();try{let n=(0,ce.spawn)(r,["start"],{detached:!0,stdio:"ignore",env:{...process.env,PATH:Rs(),BRIDGE_DAEMON:"1"}});n.unref(),setTimeout(()=>{n.pid&&process.kill(n.pid,0)?(console.log("[bridge] daemon.pid",{pid:n.pid}),console.log("[bridge] background.ok",{log:e})):console.error("[bridge] background.failed \u2014 check: tail -f",{log:t})},2e3)}catch(n){console.error("[bridge] background.spawn.failed",{error:String(n)})}}function Wa(){let r=parseInt(process.env.HEALTH_PORT??"3101",10),e=Date.now()+6e3,t=()=>{if(Date.now()>e){console.error("[bridge] health.verify.timeout \u2014 daemon may have crashed immediately");return}try{let s=require("node:http").get(`http://127.0.0.1:${r}/health`,i=>{i.statusCode===200?console.log("[bridge] health.verify.ok"):setTimeout(t,500)});s.on("error",()=>{setTimeout(t,500)}),s.setTimeout(1e3,()=>{s.destroy(),setTimeout(t,500)})}catch{setTimeout(t,500)}};setTimeout(t,1e3)}function Fa(){Ds();let r=new Je;Ts(r),r.startLivenessCheck(6e4);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,Ns.createServer)((n,s)=>{let i=Ps(),o=JSON.stringify({status:"ok",connected:i,uptime:process.uptime()});s.writeHead(i?200:503,{"Content-Type":"application/json"}),s.end(o)});t.listen(e,"127.0.0.1",()=>{console.log(`[bridge] health. listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.error",{error:n.message})})}function Ls(){let r=process.env.BRIDGE_DAEMON==="1"||process.argv.includes("--daemon");if(!r&&!process.env.BRIDGE_PROFILE){let a=process.argv[1]??"";(a.includes("packages/daemon/dist")||a.includes("packages/daemon/src"))&&(console.warn("[bridge] WARNING: running monorepo daemon without --profile \u2014 will use prod config (~/.jerico/settings.json)."),console.warn("[bridge] If this is unintentional, stop and rerun with: node packages/daemon/dist/index.js --profile dev start"))}if(console.log("[bridge] Starting bridge-agent daemon..."),r){Fa();return}Ma()||(console.warn("[bridge] start.aborted.already.running"),process.exit(1));let e=ja(),t=$a(e),{ok:n,permissionDenied:s}=t?Ba():{ok:!1,permissionDenied:!1},i=R.default.join(St,dt()),{out:o,err:c}=ut();if(n){console.log("[bridge] launchd.ok \u2014 managed, auto-restart enabled"),console.log("[bridge] logs: tail -f",{out:o,err:c}),Wa(),process.exit(0);return}s&&(console.warn("[bridge] launchd.permission.denied"),console.warn("[bridge] \u2192 Auto-start on login requires:"),console.warn(`[bridge] sudo launchctl bootstrap gui/$(id -u) "${i}"`),console.warn(`[bridge] Falling back to background process...
419
+ `)),Ua(e),process.exit(0)}var js=_(require("https")),Ms=_(require("http"));Se();function Ga(r){return(r??"").trim()}async function $s(r,e=!1,t){console.log("[bridge] Starting auth flow..."),console.log(`[bridge] Server: ${r}`),console.log("[bridge] Open this URL to generate a daemon token:"),console.log(` ${r}/connect`);let n=Ga(t);n&&console.log("[bridge] Using token from --token"),e&&(n?console.log("[bridge] --no-browser ignored because --token is provided."):(console.log("[bridge] --no-browser: exiting after printing URL."),process.exit(0)));let s=n;s||(console.log(),console.log("[bridge] After authenticating, paste your token here:"),s=await qa()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await Ha(r,s)||(console.error("[bridge] Token validation failed. Please try again."),process.exit(1));let c=r.replace(/^https?:\/\//,a=>a.startsWith("https")?"wss://":"ws://").replace(/\/?$/,"/ws/daemon");oe({server:c,token:s,name:process.env.HOSTNAME??"My Machine"}),console.log("[bridge] Auth successful! Config saved to ~/.bridge/config.json"),console.log("[bridge] Run: bridge-agent start"),process.exit(0)}async function qa(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
420
+ `)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function Ha(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?js.default:Ms.default,o={hostname:n.hostname,port:n.port||(s?443:80),path:n.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}},c=i.request(o,a=>{t(a.statusCode===200)});c.on("error",()=>t(!1)),c.end()})}var Bs=_(require("https")),Us=_(require("http")),Er=_(require("fs")),kr=_(require("path")),Ws=require("node:crypto");Se();function Va(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function Fs(r,e,t){let n=ie(),s=(0,Ws.createHash)("sha256").update(n.token).digest("hex"),i=Va(n.server),o=kr.default.resolve(t);kr.default.isAbsolute(o)||(console.error("[bridge] link-project: path must be absolute"),process.exit(1)),Er.default.existsSync(o)||(console.error("[bridge] link-project: path does not exist:",o),process.exit(1)),Er.default.statSync(o).isDirectory()||(console.error("[bridge] link-project: path must be a directory:",o),process.exit(1));let a=new URL(`/api/workspaces/${r}/projects/${e}/machine-paths`,i),l=a.protocol==="https:",d=l?Bs.default:Us.default;n.projectPaths={...n.projectPaths??{},[e]:o},oe(n),console.log("[cli] link-project.local_json_written",{projectId:e,path:o});let u=JSON.stringify({daemonId:s,localPath:o,machineFingerprint:vr()}),p=await new Promise((g,h)=>{let f=d.request({hostname:a.hostname,port:a.port||(l?443:80),path:a.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"Content-Length":Buffer.byteLength(u)}},m=>{let k="";m.on("data",S=>{k+=S}),m.on("end",()=>{if(m.statusCode===200)g(200);else{try{let S=JSON.parse(k);console.error("[bridge] link-project failed:",S.error??`HTTP ${m.statusCode}`)}catch{console.error("[bridge] link-project failed:",`HTTP ${m.statusCode}`)}g(m.statusCode??0)}})});f.on("error",m=>{h(m)}),f.write(u),f.end()});p===200?(console.log("[cli] link-project.server_success",{projectId:e}),console.log("[cli] link-project.success (dual-write)"),console.log(` workspace: ${r}`),console.log(` project: ${e}`),console.log(` daemon: ${s.slice(0,16)}\u2026`),console.log(` path: ${o}`),console.log("[cli] Next spawn for this project will use the linked path."),process.exit(0)):(console.warn("[cli] link-project.server_fail",{projectId:e,statusCode:p}),console.log("[cli] Local override still active \u2014 path will work on this machine"),process.exit(0))}Se();function Ka(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function Gs(){let r=ie(),e=Ka(r.server),t=await fetch(`${e}/api/admin/cleanup-orphans`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:"{}"});t.ok||(console.error(`[cli] cleanup-orphans: HTTP ${t.status}`),process.exit(1));let{deleted:n}=await t.json();console.log(`[cli] cleanup-orphans: deleted ${n} orphaned path ${n===1?"entry":"entries"}`),process.exit(0)}var le=new Ur;le.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.4.0").option("--profile <name>","Config profile name (e.g. dev). Isolates config, lock, and fingerprint from the default prod profile.").hook("preAction",r=>{let e=r.opts().profile;e&&(process.env.BRIDGE_PROFILE=e)});le.command("start").description("Start the bridge-agent daemon").option("--health-port <port>","Health check HTTP port (default: 3101, or 3101+offset per profile)").action(r=>{r.healthPort&&(process.env.HEALTH_PORT=r.healthPort),Ls()});le.command("auth").description("Authenticate with Bridge server").requiredOption("-s, --server <url>","Server URL (e.g., https://your-server.com)").option("-t, --token <token>","Use token non-interactively").option("--no-browser","Print auth URL without opening browser or interactive prompt").action(r=>{$s(r.server,!r.browser,r.token)});le.command("link-project <workspace-id> <project-id> <local-path>").description("Link a local directory to a project for this machine (Issue #152)").action((r,e,t)=>{Fs(r,e,t)});le.command("cleanup-orphans").description("Remove orphaned daemon_project_paths rows for this user").action(()=>{Gs()});le.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(Se(),ys)),e=r();console.log("[bridge] Config found"),console.log(" Server:",e.server),console.log(" Name:",e.name)}catch{console.log("[bridge] Not authenticated. Run: bridge-agent auth")}});le.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bridge-agent",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "description": "Bridge local agent — connects your AI tools to Jerico",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",