@slayzone/cli 0.36.1 → 0.36.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/slay.js +618 -276
  2. package/package.json +1 -1
package/dist/slay.js CHANGED
@@ -5027,7 +5027,7 @@ var require_abort_controller = __commonJS({
5027
5027
  value: "AbortSignal"
5028
5028
  });
5029
5029
  }
5030
- var AbortController = class {
5030
+ var AbortController2 = class {
5031
5031
  /**
5032
5032
  * Initialize this controller.
5033
5033
  */
@@ -5055,21 +5055,21 @@ var require_abort_controller = __commonJS({
5055
5055
  }
5056
5056
  return signal;
5057
5057
  }
5058
- Object.defineProperties(AbortController.prototype, {
5058
+ Object.defineProperties(AbortController2.prototype, {
5059
5059
  signal: { enumerable: true },
5060
5060
  abort: { enumerable: true }
5061
5061
  });
5062
5062
  if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
5063
- Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
5063
+ Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, {
5064
5064
  configurable: true,
5065
5065
  value: "AbortController"
5066
5066
  });
5067
5067
  }
5068
- exports2.AbortController = AbortController;
5068
+ exports2.AbortController = AbortController2;
5069
5069
  exports2.AbortSignal = AbortSignal2;
5070
- exports2.default = AbortController;
5071
- module2.exports = AbortController;
5072
- module2.exports.AbortController = module2.exports["default"] = AbortController;
5070
+ exports2.default = AbortController2;
5071
+ module2.exports = AbortController2;
5072
+ module2.exports.AbortController = module2.exports["default"] = AbortController2;
5073
5073
  module2.exports.AbortSignal = AbortSignal2;
5074
5074
  }
5075
5075
  });
@@ -5085,7 +5085,7 @@ var require_util2 = __commonJS({
5085
5085
  } = require_errors();
5086
5086
  var { kResistStopPropagation, AggregateError, SymbolDispose } = require_primordials();
5087
5087
  var AbortSignal2 = globalThis.AbortSignal || require_abort_controller().AbortSignal;
5088
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
5088
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
5089
5089
  var AsyncFunction = Object.getPrototypeOf(async function() {
5090
5090
  }).constructor;
5091
5091
  var Blob = globalThis.Blob || bufferModule.Blob;
@@ -5189,7 +5189,7 @@ var require_util2 = __commonJS({
5189
5189
  if (signals.length === 1) {
5190
5190
  return signals[0];
5191
5191
  }
5192
- const ac = new AbortController();
5192
+ const ac = new AbortController2();
5193
5193
  const abort = () => ac.abort();
5194
5194
  signals.forEach((signal) => {
5195
5195
  validateAbortSignal(signal, "signals");
@@ -8547,7 +8547,7 @@ var require_duplexify = __commonJS({
8547
8547
  } : function isBlob2(b) {
8548
8548
  return false;
8549
8549
  };
8550
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
8550
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
8551
8551
  var { FunctionPrototypeCall } = require_primordials();
8552
8552
  var Duplexify = class extends Duplex {
8553
8553
  constructor(options) {
@@ -8703,7 +8703,7 @@ var require_duplexify = __commonJS({
8703
8703
  };
8704
8704
  function fromAsyncGen(fn) {
8705
8705
  let { promise, resolve: resolve2 } = createDeferredPromise();
8706
- const ac = new AbortController();
8706
+ const ac = new AbortController2();
8707
8707
  const signal = ac.signal;
8708
8708
  const value = fn(
8709
8709
  (async function* () {
@@ -9130,7 +9130,7 @@ var require_pipeline = __commonJS({
9130
9130
  isReadableStream,
9131
9131
  isReadableFinished
9132
9132
  } = require_utils();
9133
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
9133
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
9134
9134
  var PassThrough3;
9135
9135
  var Readable3;
9136
9136
  var addAbortListener;
@@ -9266,7 +9266,7 @@ var require_pipeline = __commonJS({
9266
9266
  if (streams.length < 2) {
9267
9267
  throw new ERR_MISSING_ARGS("streams");
9268
9268
  }
9269
- const ac = new AbortController();
9269
+ const ac = new AbortController2();
9270
9270
  const signal = ac.signal;
9271
9271
  const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal;
9272
9272
  const lastStreamCleanup = [];
@@ -9724,7 +9724,7 @@ var require_compose = __commonJS({
9724
9724
  var require_operators = __commonJS({
9725
9725
  "../../../node_modules/readable-stream/lib/internal/streams/operators.js"(exports2, module2) {
9726
9726
  "use strict";
9727
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
9727
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
9728
9728
  var {
9729
9729
  codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },
9730
9730
  AbortError
@@ -9982,7 +9982,7 @@ var require_operators = __commonJS({
9982
9982
  await finished(this.destroy(err));
9983
9983
  throw err;
9984
9984
  }
9985
- const ac = new AbortController();
9985
+ const ac = new AbortController2();
9986
9986
  const signal = ac.signal;
9987
9987
  if (options !== null && options !== void 0 && options.signal) {
9988
9988
  const opts = {
@@ -16217,14 +16217,16 @@ var HUB_SWITCH_ENV = {
16217
16217
  enablePassword: "SLAYZONE_HUB_ENABLE_PASSWORD",
16218
16218
  enableSso: "SLAYZONE_HUB_ENABLE_SSO",
16219
16219
  enableProcesses: "SLAYZONE_HUB_ENABLE_PROCESSES",
16220
- enableIntegrations: "SLAYZONE_HUB_ENABLE_INTEGRATIONS"
16220
+ enableIntegrations: "SLAYZONE_HUB_ENABLE_INTEGRATIONS",
16221
+ enableTelemetry: "SLAYZONE_HUB_ENABLE_TELEMETRY"
16221
16222
  };
16222
16223
  var HUB_SWITCH_DEFAULTS = {
16223
16224
  requireLogin: false,
16224
16225
  enablePassword: true,
16225
16226
  enableSso: false,
16226
16227
  enableProcesses: true,
16227
- enableIntegrations: true
16228
+ enableIntegrations: true,
16229
+ enableTelemetry: true
16228
16230
  };
16229
16231
  var HUB_SSO_ENV = {
16230
16232
  tenantId: "SLAYZONE_HUB_SSO_TENANT_ID",
@@ -16275,7 +16277,7 @@ var SIDECAR_FIXED_PORT = {
16275
16277
  var HUB_PORT_BLOCK = { start: 51100, end: 51199 };
16276
16278
 
16277
16279
  // ../../shared/platform/src/hub-discovery.ts
16278
- var DEFAULT_TIMEOUT_MS = 300;
16280
+ var DEFAULT_TIMEOUT_MS = 3e3;
16279
16281
  var DEFAULT_CONCURRENCY = 32;
16280
16282
  function probe(host, port, timeoutMs) {
16281
16283
  return new Promise((resolve2) => {
@@ -16346,8 +16348,10 @@ function parseSwitches(raw) {
16346
16348
  const o = raw;
16347
16349
  const out = { ...HUB_SWITCH_DEFAULTS };
16348
16350
  for (const key of Object.keys(HUB_SWITCH_ENV)) {
16349
- if (typeof o[key] !== "boolean") return null;
16350
- out[key] = o[key];
16351
+ const value = o[key];
16352
+ if (value === void 0) continue;
16353
+ if (typeof value !== "boolean") return null;
16354
+ out[key] = value;
16351
16355
  }
16352
16356
  return out;
16353
16357
  }
@@ -16441,7 +16445,8 @@ var MESSAGES = {
16441
16445
  NO_COMPUTER_CONNECTED: `Connect a computer: this hub does not read project files or run git, gh or other commands itself (${HUB_SWITCH_ENV.enableProcesses}=0).`,
16442
16446
  HUB_PASSWORD_DISABLED: `Password sign-in is switched off on this hub (${HUB_SWITCH_ENV.enablePassword}=0).`,
16443
16447
  HUB_CONVEX_NOT_CONFIGURED: `GitHub sign-in is off on this hub: no Convex deployment is configured (${HUB_CONVEX_ADDRESS_ENV}).`,
16444
- HUB_CONVEX_MISMATCH: `This hub starts GitHub sign-in only against its own Convex deployment (${HUB_CONVEX_ADDRESS_ENV}); the request named another.`
16448
+ HUB_CONVEX_MISMATCH: `This hub starts GitHub sign-in only against its own Convex deployment (${HUB_CONVEX_ADDRESS_ENV}); the request named another.`,
16449
+ HUB_TELEMETRY_DISABLED: `GitHub sign-in (leaderboard, feedback) is off on this hub: third-party telemetry is switched off (${HUB_SWITCH_ENV.enableTelemetry}=0).`
16445
16450
  };
16446
16451
  var VARIABLES = {
16447
16452
  HUB_PROCESSES_DISABLED: HUB_SWITCH_ENV.enableProcesses,
@@ -16449,7 +16454,8 @@ var VARIABLES = {
16449
16454
  NO_COMPUTER_CONNECTED: HUB_SWITCH_ENV.enableProcesses,
16450
16455
  HUB_PASSWORD_DISABLED: HUB_SWITCH_ENV.enablePassword,
16451
16456
  HUB_CONVEX_NOT_CONFIGURED: HUB_CONVEX_ADDRESS_ENV,
16452
- HUB_CONVEX_MISMATCH: HUB_CONVEX_ADDRESS_ENV
16457
+ HUB_CONVEX_MISMATCH: HUB_CONVEX_ADDRESS_ENV,
16458
+ HUB_TELEMETRY_DISABLED: HUB_SWITCH_ENV.enableTelemetry
16453
16459
  };
16454
16460
 
16455
16461
  // ../../shared/platform/src/cli-install.ts
@@ -16486,6 +16492,10 @@ function getHubTargetPath() {
16486
16492
  const name = process.env.SLAYZONE_DEV === "1" ? "hub-target.dev.json" : "hub-target.json";
16487
16493
  return import_path2.default.join(getCliStateDir(), name);
16488
16494
  }
16495
+ function getBreakGlassPath() {
16496
+ const name = process.env.SLAYZONE_DEV === "1" ? "break-glass.dev.json" : "break-glass.json";
16497
+ return import_path2.default.join(getCliStateDir(), name);
16498
+ }
16489
16499
  function getServiceRuntimeDir(kind) {
16490
16500
  return import_path2.default.join(getCliStateDir(), `${kind}-runtime`);
16491
16501
  }
@@ -16503,9 +16513,15 @@ var hubOverride = null;
16503
16513
  function setHubOverride(target) {
16504
16514
  hubOverride = target;
16505
16515
  }
16516
+ function isTaskTerminal() {
16517
+ return (process.env.SLAYZONE_TASK_ID ?? "").trim() !== "";
16518
+ }
16506
16519
  function getHubConfigPath() {
16507
16520
  return getHubTargetPath();
16508
16521
  }
16522
+ function getBreakGlassSessionPath() {
16523
+ return getBreakGlassPath();
16524
+ }
16509
16525
  function normalizeHubUrl(raw) {
16510
16526
  const trimmed = raw.trim();
16511
16527
  if (!trimmed) return null;
@@ -16523,80 +16539,130 @@ function hubFilePathForRead() {
16523
16539
  if (import_fs2.default.existsSync(current)) return current;
16524
16540
  return legacyHubTargetPaths()[0] ?? current;
16525
16541
  }
16526
- function readHubFile() {
16527
- const configPath = hubFilePathForRead();
16542
+ function readJsonObject(file, label) {
16528
16543
  let rawText;
16529
16544
  try {
16530
- rawText = import_fs2.default.readFileSync(configPath, "utf-8");
16545
+ rawText = import_fs2.default.readFileSync(file, "utf-8");
16531
16546
  } catch (e) {
16532
- if (e.code !== "ENOENT") {
16533
- console.error(`Warning: could not read hub config at ${configPath} \u2014 using local app.`);
16547
+ if (label && e.code !== "ENOENT") {
16548
+ console.error(`Warning: could not read ${label} at ${file} \u2014 ignoring it.`);
16534
16549
  }
16535
16550
  return null;
16536
16551
  }
16537
16552
  try {
16538
16553
  const parsed = JSON.parse(rawText);
16539
- if (typeof parsed !== "object" || parsed === null) {
16540
- throw new Error("not an object");
16541
- }
16542
- const config = parsed;
16543
- if (typeof config.url !== "string" || config.url.trim() === "") {
16544
- throw new Error("missing url");
16545
- }
16546
- return config;
16554
+ if (typeof parsed !== "object" || parsed === null) throw new Error("not an object");
16555
+ return parsed;
16547
16556
  } catch {
16548
- console.error(`Warning: ignoring invalid hub config at ${configPath} \u2014 using local app.`);
16557
+ if (label) console.error(`Warning: ignoring invalid ${label} at ${file}.`);
16549
16558
  return null;
16550
16559
  }
16551
16560
  }
16552
- function resolveHubTarget() {
16553
- if (hubOverride) return hubOverride;
16554
- const envAddress = process.env.SLAYZONE_HUB_ADDRESS;
16561
+ function readHubFile(warn) {
16562
+ const configPath = hubFilePathForRead();
16563
+ const config = readJsonObject(configPath, warn ? "hub config" : null);
16564
+ if (!config) return null;
16565
+ if (typeof config.url !== "string" || config.url.trim() === "") {
16566
+ if (warn) console.error(`Warning: ignoring invalid hub config at ${configPath}.`);
16567
+ return null;
16568
+ }
16569
+ return config;
16570
+ }
16571
+ function storedTarget(warn) {
16572
+ const file = readHubFile(warn);
16573
+ if (!file) return null;
16574
+ const baseUrl = normalizeHubUrl(file.url);
16575
+ if (!baseUrl) {
16576
+ if (warn) console.error(`Warning: ignoring invalid hub URL in ${getHubConfigPath()}.`);
16577
+ return null;
16578
+ }
16579
+ const fileToken = typeof file.token === "string" && file.token !== "" ? file.token : null;
16555
16580
  const envToken = process.env.SLAYZONE_HUB_TOKEN;
16556
- if (envAddress && envAddress.trim() !== "") {
16557
- const addr = envAddress.trim();
16558
- const baseUrl = isBareAuthority(addr) ? normalizeHubUrl(hubUrlFromAddr(addr, "http")) : null;
16559
- if (!baseUrl) {
16560
- console.error(
16561
- `Invalid SLAYZONE_HUB_ADDRESS (expected host[:port], no scheme/path): ${envAddress}`
16562
- );
16563
- process.exit(1);
16564
- }
16565
- return { baseUrl, token: envToken || null };
16581
+ return { baseUrl, token: envToken !== void 0 ? envToken || null : fileToken, source: "file" };
16582
+ }
16583
+ function envTarget() {
16584
+ const envAddress = process.env.SLAYZONE_HUB_ADDRESS;
16585
+ if (!envAddress || envAddress.trim() === "") return null;
16586
+ const addr = envAddress.trim();
16587
+ const baseUrl = isBareAuthority(addr) ? normalizeHubUrl(hubUrlFromAddr(addr, "http")) : null;
16588
+ if (!baseUrl) {
16589
+ console.error(
16590
+ `Invalid SLAYZONE_HUB_ADDRESS (expected host[:port], no scheme/path): ${envAddress}`
16591
+ );
16592
+ process.exit(1);
16566
16593
  }
16567
- const file = readHubFile();
16568
- if (file) {
16569
- const baseUrl = normalizeHubUrl(file.url);
16570
- if (!baseUrl) {
16571
- console.error(`Warning: ignoring invalid hub URL in ${getHubConfigPath()} \u2014 using local app.`);
16572
- return null;
16573
- }
16574
- const fileToken = typeof file.token === "string" && file.token !== "" ? file.token : null;
16575
- return { baseUrl, token: envToken !== void 0 ? envToken || null : fileToken };
16594
+ const envToken = process.env.SLAYZONE_HUB_TOKEN;
16595
+ if (envToken !== void 0) return { baseUrl, token: envToken || null, source: "env" };
16596
+ const stored = storedTarget(false);
16597
+ return { baseUrl, token: stored?.baseUrl === baseUrl ? stored.token : null, source: "env" };
16598
+ }
16599
+ function flagTarget() {
16600
+ return hubOverride ? { ...hubOverride, source: "flag" } : null;
16601
+ }
16602
+ function resolveTaskCommandTarget() {
16603
+ return flagTarget() ?? envTarget() ?? (isTaskTerminal() ? null : storedTarget(true));
16604
+ }
16605
+ function resolveHubCommandTarget() {
16606
+ const flag = flagTarget();
16607
+ if (flag) return flag;
16608
+ const session = readBreakGlassSession();
16609
+ if (session && !isBreakGlassExpired(session)) {
16610
+ return { baseUrl: session.url, token: session.token, source: "break-glass" };
16576
16611
  }
16577
- return null;
16612
+ return isTaskTerminal() ? storedTarget(true) ?? envTarget() : envTarget() ?? storedTarget(true);
16613
+ }
16614
+ function writePrivateJson(file, payload) {
16615
+ import_fs2.default.mkdirSync(import_path3.default.dirname(file), { recursive: true });
16616
+ import_fs2.default.writeFileSync(file, `${JSON.stringify(payload, null, 2)}
16617
+ `, { mode: 384 });
16618
+ import_fs2.default.chmodSync(file, 384);
16578
16619
  }
16579
16620
  function writeHubConfig(url, token) {
16580
16621
  const configPath = getHubConfigPath();
16581
- import_fs2.default.mkdirSync(import_path3.default.dirname(configPath), { recursive: true });
16582
16622
  const payload = token ? { url, token } : { url };
16583
- import_fs2.default.writeFileSync(configPath, `${JSON.stringify(payload, null, 2)}
16584
- `, { mode: 384 });
16585
- import_fs2.default.chmodSync(configPath, 384);
16623
+ writePrivateJson(configPath, payload);
16586
16624
  return configPath;
16587
16625
  }
16588
16626
  function removeHubConfig() {
16589
16627
  let removed = false;
16590
16628
  for (const target of [getHubConfigPath(), ...legacyHubTargetPaths()]) {
16591
- try {
16592
- import_fs2.default.unlinkSync(target);
16593
- removed = true;
16594
- } catch (e) {
16595
- if (e.code !== "ENOENT") throw e;
16596
- }
16629
+ if (unlinkIfPresent(target)) removed = true;
16597
16630
  }
16598
16631
  return removed;
16599
16632
  }
16633
+ function readBreakGlassSession() {
16634
+ const file = getBreakGlassSessionPath();
16635
+ const raw = readJsonObject(file, "break-glass session");
16636
+ if (!raw) return null;
16637
+ const { url, token, expiresAt } = raw;
16638
+ const baseUrl = typeof url === "string" ? normalizeHubUrl(url) : null;
16639
+ if (!baseUrl || typeof token !== "string" || token === "") {
16640
+ console.error(`Warning: ignoring invalid break-glass session at ${file}.`);
16641
+ return null;
16642
+ }
16643
+ return { url: baseUrl, token, expiresAt: typeof expiresAt === "string" ? expiresAt : "?" };
16644
+ }
16645
+ function isBreakGlassExpired(session, now = Date.now()) {
16646
+ const at = Date.parse(session.expiresAt);
16647
+ return !Number.isNaN(at) && at <= now;
16648
+ }
16649
+ function writeBreakGlassSession(session) {
16650
+ const file = getBreakGlassSessionPath();
16651
+ writePrivateJson(file, session);
16652
+ return file;
16653
+ }
16654
+ function removeBreakGlassSession() {
16655
+ return unlinkIfPresent(getBreakGlassSessionPath());
16656
+ }
16657
+ function unlinkIfPresent(file) {
16658
+ try {
16659
+ import_fs2.default.unlinkSync(file);
16660
+ return true;
16661
+ } catch (e) {
16662
+ if (e.code !== "ENOENT") throw e;
16663
+ return false;
16664
+ }
16665
+ }
16600
16666
 
16601
16667
  // src/local-hub.ts
16602
16668
  var import_node_path3 = __toESM(require("node:path"), 1);
@@ -16607,8 +16673,7 @@ function expectedRoot() {
16607
16673
  const root = process.env.SLAYZONE_ROOT?.trim();
16608
16674
  return root ? import_node_path3.default.resolve(root) : null;
16609
16675
  }
16610
- async function probeFixedPort() {
16611
- const port = fixedPortForChannel();
16676
+ async function probeFixedPort(port = fixedPortForChannel()) {
16612
16677
  const hub = await findHub(String(port));
16613
16678
  if (!hub) return { kind: "absent" };
16614
16679
  const expected = expectedRoot();
@@ -16618,7 +16683,7 @@ async function probeFixedPort() {
16618
16683
  return { kind: "found", port: hub.port, root: hub.root, authRequired: hub.authRequired };
16619
16684
  }
16620
16685
  async function isCoLocatedHub() {
16621
- const configured = resolveHubTarget();
16686
+ const configured = resolveTaskCommandTarget();
16622
16687
  if (!configured) return true;
16623
16688
  try {
16624
16689
  const host = new URL(configured.baseUrl).hostname.replace(/^\[|\]$/g, "");
@@ -16630,8 +16695,14 @@ async function isCoLocatedHub() {
16630
16695
 
16631
16696
  // src/api.ts
16632
16697
  async function resolveTarget() {
16633
- const hub = resolveHubTarget();
16698
+ const hub = resolveTaskCommandTarget();
16634
16699
  if (hub) return { baseUrl: hub.baseUrl, token: hub.token, hub: true };
16700
+ if (isTaskTerminal() && !process.env.SLAYZONE_ROOT?.trim()) {
16701
+ console.error(
16702
+ "This is a task terminal (SLAYZONE_TASK_ID is set), but it does not say which app\nspawned it: neither SLAYZONE_HUB_ADDRESS nor SLAYZONE_ROOT is set. Refusing to guess.\nOpen a new terminal from the app, or name the hub with `slay --hub <name|port>`."
16703
+ );
16704
+ process.exit(1);
16705
+ }
16635
16706
  const probe2 = await probeFixedPort();
16636
16707
  if (probe2.kind === "foreign") {
16637
16708
  console.error(
@@ -17031,7 +17102,7 @@ async function postHubNotify(hub, timeoutMs = 3e3) {
17031
17102
  }
17032
17103
  }
17033
17104
  async function notifyApp() {
17034
- const hub = resolveHubTarget();
17105
+ const hub = resolveTaskCommandTarget();
17035
17106
  if (hub) {
17036
17107
  const ok = await postHubNotify(hub);
17037
17108
  if (!ok) {
@@ -21835,7 +21906,7 @@ var import_path8 = __toESM(require("path"), 1);
21835
21906
  var import_node_stream = require("node:stream");
21836
21907
  var import_promises2 = require("node:stream/promises");
21837
21908
 
21838
- // ../../domains/task/src/shared/types.ts
21909
+ // ../../domains/task-contracts/src/types.ts
21839
21910
  var COLD_RESPAWN_MS = 30 * 60 * 1e3;
21840
21911
  var px = (value) => ({ value, unit: "px" });
21841
21912
  var PANEL_LAYOUT_DEFAULTS = {
@@ -22769,7 +22840,7 @@ function safeRandomUUID() {
22769
22840
  return `insecure-ctx-${Date.now()}-${fallbackUuidCounter}`;
22770
22841
  }
22771
22842
 
22772
- // ../../domains/projects/src/shared/create-project.ts
22843
+ // ../../domains/projects-contracts/src/create-project.ts
22773
22844
  var HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
22774
22845
  function normalizeProjectName(name) {
22775
22846
  const trimmed = name.trim();
@@ -22803,6 +22874,9 @@ function prepareProjectCreate(input) {
22803
22874
  };
22804
22875
  }
22805
22876
 
22877
+ // ../../shared/platform/src/computer-identity.ts
22878
+ var DEFAULT_LOCAL_COMPUTER_NAME = "local-computer";
22879
+
22806
22880
  // src/commands/projects.ts
22807
22881
  var DEFAULT_PROJECT_COLOR = "#3b82f6";
22808
22882
  function narrowProject(p) {
@@ -25212,21 +25286,22 @@ ${parts.join(", ")} for "${projectName}"`);
25212
25286
  console.log(`All ${stats.skipped} skills up to date for "${projectName}"`);
25213
25287
  }
25214
25288
  }
25215
- async function resolveTargetProjectRef(explicit) {
25216
- if (explicit) return explicit;
25289
+ async function resolveTargetProject(explicit) {
25290
+ if (explicit) return { ref: explicit, localFolder: null };
25217
25291
  const { data } = await apiGet(
25218
25292
  `/api/projects/resolve-by-path?path=${encodeURIComponent(process.cwd())}`
25219
25293
  );
25220
- return data.id;
25294
+ return { ref: data.id, localFolder: data.path };
25221
25295
  }
25222
25296
  async function runInstall(opts) {
25223
- const projectRef = await resolveTargetProjectRef(opts.project);
25297
+ const { ref: projectRef, localFolder } = await resolveTargetProject(opts.project);
25224
25298
  const { data } = await apiPost(
25225
25299
  `/api/projects/${encodeURIComponent(projectRef)}/skills`,
25226
25300
  {}
25227
25301
  );
25228
25302
  const { project, providers, stats, skills } = data;
25229
- const localPath = project.path && import_node_fs3.default.existsSync(project.path) ? project.path : null;
25303
+ const candidate = localFolder ?? project.path;
25304
+ const localPath = candidate && import_node_fs3.default.existsSync(candidate) ? candidate : null;
25230
25305
  if (opts.writeInstructions && localPath) {
25231
25306
  const written = writeInstructionsToDisk(localPath, providers);
25232
25307
  for (const f of written) console.log(` Appended instructions to ${f}`);
@@ -26045,17 +26120,13 @@ var import_node_path9 = require("node:path");
26045
26120
  // ../../shared/platform/src/slayzone-config.ts
26046
26121
  var import_node_fs5 = require("node:fs");
26047
26122
  var import_node_path6 = require("node:path");
26048
-
26049
- // ../../shared/platform/src/computer-identity.ts
26050
- var DEFAULT_LOCAL_COMPUTER_NAME = "local-computer";
26051
-
26052
- // ../../shared/platform/src/slayzone-config.ts
26053
26123
  var HUB_CONFIG_SWITCH_KEYS = [
26054
26124
  "requireLogin",
26055
26125
  "enablePassword",
26056
26126
  "enableSso",
26057
26127
  "enableProcesses",
26058
- "enableIntegrations"
26128
+ "enableIntegrations",
26129
+ "enableTelemetry"
26059
26130
  ];
26060
26131
  function getHubConfigFilePath() {
26061
26132
  return (0, import_node_path6.join)(getSlayzoneHomeDir(), "hub.config.json");
@@ -26095,7 +26166,7 @@ function coerceComputerConfig(raw) {
26095
26166
  }
26096
26167
  return cfg;
26097
26168
  }
26098
- function readJsonObject(path12) {
26169
+ function readJsonObject2(path12) {
26099
26170
  let raw;
26100
26171
  try {
26101
26172
  raw = (0, import_node_fs5.readFileSync)(path12, "utf8");
@@ -26141,7 +26212,7 @@ function saveHubConfigFile(cfg, path12 = getHubConfigFilePath()) {
26141
26212
  writeJsonAtomic(path12, cfg);
26142
26213
  }
26143
26214
  function updateHubConfigFile(patch, path12 = getHubConfigFilePath()) {
26144
- const current = readJsonObject(path12);
26215
+ const current = readJsonObject2(path12);
26145
26216
  const merged = current ? coerceHubConfig(current) : {};
26146
26217
  for (const [k, v] of Object.entries(patch)) {
26147
26218
  if (v !== void 0) merged[k] = v;
@@ -26150,16 +26221,16 @@ function updateHubConfigFile(patch, path12 = getHubConfigFilePath()) {
26150
26221
  return merged;
26151
26222
  }
26152
26223
  function loadComputerConfigFile(path12 = getComputerConfigFilePath()) {
26153
- const raw = readJsonObject(path12);
26224
+ const raw = readJsonObject2(path12);
26154
26225
  if (raw) return coerceComputerConfig(raw);
26155
- const legacy = readJsonObject(legacyConfigFilePathFor(path12));
26226
+ const legacy = readJsonObject2(legacyConfigFilePathFor(path12));
26156
26227
  return legacy ? coerceComputerConfig(legacy) : {};
26157
26228
  }
26158
26229
  function saveComputerConfigFile(cfg, path12 = getComputerConfigFilePath()) {
26159
26230
  writeJsonAtomic(path12, cfg);
26160
26231
  }
26161
26232
  function updateComputerConfigFile(patch, path12 = getComputerConfigFilePath()) {
26162
- const current = readJsonObject(path12);
26233
+ const current = readJsonObject2(path12);
26163
26234
  const merged = current ? coerceComputerConfig(current) : {};
26164
26235
  for (const [k, v] of Object.entries(patch)) {
26165
26236
  if (v !== void 0) merged[k] = v;
@@ -26468,7 +26539,7 @@ var import_node_child_process3 = require("node:child_process");
26468
26539
  var import_node_fs7 = require("node:fs");
26469
26540
  var import_node_module = require("node:module");
26470
26541
  var import_node_path8 = require("node:path");
26471
- var CLI_VERSION = true ? "0.36.1" : "";
26542
+ var CLI_VERSION = true ? "0.36.3" : "";
26472
26543
  function fail(message) {
26473
26544
  console.error(message);
26474
26545
  process.exit(1);
@@ -26792,7 +26863,7 @@ function supervisorStatus(kind, backend, name) {
26792
26863
 
26793
26864
  // src/hub-request.ts
26794
26865
  async function resolveHubRequestTarget(what, discover = () => discoverHubs()) {
26795
- const configured = resolveHubTarget();
26866
+ const configured = resolveHubCommandTarget();
26796
26867
  if (configured) return configured;
26797
26868
  const running = await discover();
26798
26869
  if (running.length === 0) {
@@ -26845,57 +26916,336 @@ ${hint}` : ""}`);
26845
26916
 
26846
26917
  // src/hub-sign-in.ts
26847
26918
  var import_node_child_process4 = require("node:child_process");
26848
- var import_node_http3 = __toESM(require("node:http"), 1);
26849
- var import_node_https = __toESM(require("node:https"), 1);
26850
- var CLI_DEVICE_CLIENT_ID = "slayzone-cli";
26851
- var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
26852
- function postAuthJson(url, body, timeoutMs = 1e4) {
26853
- const payload = JSON.stringify(body);
26854
- const request2 = url.startsWith("https:") ? import_node_https.default.request : import_node_http3.default.request;
26855
- return new Promise((resolve2, reject) => {
26856
- const req = request2(
26857
- url,
26858
- {
26859
- method: "POST",
26860
- timeout: timeoutMs,
26861
- headers: {
26862
- "content-type": "application/json",
26863
- "content-length": Buffer.byteLength(payload)
26864
- }
26865
- },
26866
- (res) => {
26867
- const chunks = [];
26868
- res.on("data", (chunk) => chunks.push(chunk));
26869
- res.on("end", () => {
26870
- const headers = new Headers();
26871
- for (const [name, value] of Object.entries(res.headers)) {
26872
- for (const v of Array.isArray(value) ? value : value === void 0 ? [] : [value]) {
26873
- headers.append(name, v);
26874
- }
26875
- }
26876
- resolve2(new Response(Buffer.concat(chunks), { status: res.statusCode ?? 500, headers }));
26877
- });
26878
- res.on("error", reject);
26879
- }
26880
- );
26881
- req.on("error", reject);
26882
- req.on("timeout", () => req.destroy(new Error(`timed out after ${timeoutMs}ms`)));
26883
- req.end(payload);
26919
+
26920
+ // ../../domains/hub-auth/src/client/transport.ts
26921
+ var HUB_TRANSPORT_TIMEOUT = "HUB_TRANSPORT_TIMEOUT";
26922
+ var HubTransportTimeoutError = class extends Error {
26923
+ code = HUB_TRANSPORT_TIMEOUT;
26924
+ timeoutMs;
26925
+ constructor(timeoutMs) {
26926
+ super(`timed out after ${timeoutMs}ms`);
26927
+ this.name = "HubTransportTimeoutError";
26928
+ this.timeoutMs = timeoutMs;
26929
+ }
26930
+ };
26931
+ function isHubTransportTimeout(err) {
26932
+ return typeof err === "object" && err !== null && err.code === HUB_TRANSPORT_TIMEOUT;
26933
+ }
26934
+ function transportErrorText(err) {
26935
+ return err instanceof Error ? err.message : String(err);
26936
+ }
26937
+
26938
+ // ../../domains/hub-auth/src/client/protocol.ts
26939
+ var HUB_AUTH_PATHS = {
26940
+ health: "/health",
26941
+ signInEmail: "/api/auth/sign-in/email",
26942
+ deviceCode: "/api/auth/device/code",
26943
+ deviceToken: "/api/auth/device/token",
26944
+ session: "/api/auth/get-session"
26945
+ };
26946
+ var HUB_DEVICE_CLIENT_IDS = {
26947
+ cli: "slayzone-cli",
26948
+ desktop: "slayzone-desktop"
26949
+ };
26950
+ var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
26951
+ var HEALTH_MAX_CHARS = 4096;
26952
+ var AUTH_MAX_CHARS = 65536;
26953
+ var AUTH_TIMEOUT_MS = 1e4;
26954
+ function parseJson(text) {
26955
+ try {
26956
+ return JSON.parse(text);
26957
+ } catch {
26958
+ return void 0;
26959
+ }
26960
+ }
26961
+ function jsonObject(text) {
26962
+ const parsed = parseJson(text);
26963
+ return parsed && typeof parsed === "object" ? parsed : {};
26964
+ }
26965
+ function stringOf(value) {
26966
+ return typeof value === "string" ? value : void 0;
26967
+ }
26968
+ function postJson2(transport, url, body, timeoutMs) {
26969
+ return transport({
26970
+ method: "POST",
26971
+ url,
26972
+ headers: { "content-type": "application/json" },
26973
+ body: JSON.stringify(body),
26974
+ timeoutMs,
26975
+ maxResponseChars: AUTH_MAX_CHARS
26884
26976
  });
26885
26977
  }
26886
- async function readSignInMethods(baseUrl) {
26978
+
26979
+ // ../../domains/hub-auth/src/client/sign-in-error.ts
26980
+ var ASK_ADMIN = "If it keeps failing, ask your administrator.";
26981
+ var MESSAGES2 = {
26982
+ // T-09 refuses every ID token that fails its checks with this generic code: another
26983
+ // tenant, no MFA, no SlayZone app role, no email (the audit line names which).
26984
+ unable_to_get_user_info: "Microsoft refused this account for this hub: it may belong to another organisation, have signed in without multi-factor authentication, or not be assigned to SlayZone. Ask your administrator.",
26985
+ ACCOUNT_DISABLED: "This account is disabled on this hub. Ask your administrator.",
26986
+ account_not_linked: "The email of this Microsoft account already belongs to another account on this hub, so it cannot sign in. Ask your administrator.",
26987
+ unable_to_link_account: "This Microsoft account could not be connected to an account on this hub. Ask your administrator.",
26988
+ access_denied: "Sign-in was cancelled at Microsoft. Try again.",
26989
+ state_mismatch: "The sign-in took too long or was started in another tab. Try again.",
26990
+ please_restart_the_process: "The sign-in took too long or was started in another tab. Try again.",
26991
+ invalid_callback_request: "The sign-in took too long or was started in another tab. Try again.",
26992
+ no_session: `Microsoft sign-in did not complete. Try again. ${ASK_ADMIN}`,
26993
+ // App sign-in (`src/server/app-sign-in.ts`).
26994
+ flow_expired: "The sign-in took too long or its browser window was closed. Try again.",
26995
+ temporarily_unavailable: "Too many sign-ins are waiting on this hub. Try again in a few minutes."
26996
+ };
26997
+
26998
+ // ../../domains/hub-auth/src/client/health.ts
26999
+ async function fetchHubHealth(transport, baseUrl, timeoutMs) {
27000
+ try {
27001
+ const res = await transport({
27002
+ method: "GET",
27003
+ url: `${baseUrl}${HUB_AUTH_PATHS.health}`,
27004
+ headers: {},
27005
+ timeoutMs,
27006
+ maxResponseChars: HEALTH_MAX_CHARS
27007
+ });
27008
+ return { reachable: true, status: res.status, json: parseJson(res.text) };
27009
+ } catch (err) {
27010
+ return isHubTransportTimeout(err) ? {
27011
+ reachable: false,
27012
+ reason: "timeout",
27013
+ error: `Health check timed out after ${timeoutMs}ms`
27014
+ } : { reachable: false, reason: "unreachable", error: transportErrorText(err) };
27015
+ }
27016
+ }
27017
+ function signInMethodsOf(health) {
27018
+ if (health === null || health === void 0) return void 0;
27019
+ const switches = health.switches;
27020
+ if (!switches) return void 0;
27021
+ const sw = switches;
27022
+ return { sso: sw.enableSso === true, password: sw.enablePassword !== false };
27023
+ }
27024
+
27025
+ // ../../domains/hub-auth/src/client/password.ts
27026
+ async function signInWithPassword(transport, baseUrl, credentials, timeoutMs = AUTH_TIMEOUT_MS) {
26887
27027
  let res;
26888
27028
  try {
26889
- res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(1e4) });
26890
- } catch {
26891
- fail(`Could not reach the hub at ${baseUrl}.`);
27029
+ res = await postJson2(
27030
+ transport,
27031
+ `${baseUrl}${HUB_AUTH_PATHS.signInEmail}`,
27032
+ { email: credentials.email, password: credentials.password },
27033
+ timeoutMs
27034
+ );
27035
+ } catch (err) {
27036
+ return isHubTransportTimeout(err) ? { ok: false, reason: "timeout", error: `Sign-in timed out after ${timeoutMs}ms` } : { ok: false, reason: "unreachable", error: transportErrorText(err) };
27037
+ }
27038
+ const { status } = res;
27039
+ if (status >= 400) {
27040
+ const body2 = jsonObject(res.text);
27041
+ return {
27042
+ ok: false,
27043
+ reason: "refused",
27044
+ status,
27045
+ code: stringOf(body2.code),
27046
+ hubError: stringOf(body2.error),
27047
+ error: `Sign-in failed (HTTP ${status})`
27048
+ };
27049
+ }
27050
+ const headerToken = res.header("set-auth-token");
27051
+ if (headerToken) return { ok: true, token: headerToken };
27052
+ const body = parseJson(res.text);
27053
+ if (body === null || body === void 0) {
27054
+ return { ok: false, reason: "bad-response", status, error: "Bad sign-in response" };
27055
+ }
27056
+ const token = body.token;
27057
+ if (typeof token === "string" && token) return { ok: true, token };
27058
+ return { ok: false, reason: "no-token", status, error: "Hub returned no token" };
27059
+ }
27060
+
27061
+ // ../../domains/hub-auth/src/client/device.ts
27062
+ async function requestDeviceCode(transport, baseUrl, clientId, timeoutMs = AUTH_TIMEOUT_MS) {
27063
+ let res;
27064
+ try {
27065
+ res = await postJson2(
27066
+ transport,
27067
+ `${baseUrl}${HUB_AUTH_PATHS.deviceCode}`,
27068
+ { client_id: clientId },
27069
+ timeoutMs
27070
+ );
27071
+ } catch (err) {
27072
+ return {
27073
+ ok: false,
27074
+ reason: isHubTransportTimeout(err) ? "timeout" : "unreachable",
27075
+ error: transportErrorText(err)
27076
+ };
27077
+ }
27078
+ const j = jsonObject(res.text);
27079
+ const deviceCode = stringOf(j.device_code) ?? "";
27080
+ const userCode = stringOf(j.user_code) ?? "";
27081
+ const page = stringOf(j.verification_uri_complete) || stringOf(j.verification_uri) || "";
27082
+ if (res.status !== 200 || !deviceCode || !userCode || !page) {
27083
+ const description = stringOf(j.error_description);
27084
+ return {
27085
+ ok: false,
27086
+ reason: "refused",
27087
+ status: res.status,
27088
+ description,
27089
+ error: `The hub did not start a sign-in (HTTP ${res.status})${description ? `: ${description}` : ""}`
27090
+ };
26892
27091
  }
26893
- const health = await res.json().catch(() => ({}));
26894
27092
  return {
26895
- sso: health.switches?.enableSso === true,
26896
- password: health.switches?.enablePassword !== false
27093
+ ok: true,
27094
+ deviceCode,
27095
+ userCode: `${userCode.slice(0, 4)}-${userCode.slice(4)}`,
27096
+ verificationUri: page,
27097
+ expiresInSec: typeof j.expires_in === "number" ? j.expires_in : 600,
27098
+ intervalSec: typeof j.interval === "number" ? Math.max(5, j.interval) : 5
26897
27099
  };
26898
27100
  }
27101
+ function isHubOwnPage(baseUrl, page) {
27102
+ try {
27103
+ const target = new URL(page);
27104
+ return (target.protocol === "https:" || target.protocol === "http:") && target.host === new URL(baseUrl).host;
27105
+ } catch {
27106
+ return false;
27107
+ }
27108
+ }
27109
+ var POLL_TIMEOUT_MS = 1e4;
27110
+ var SLOW_DOWN_STEP_MS = 5e3;
27111
+ var defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
27112
+ async function waitForDeviceToken(transport, baseUrl, clientId, code, opts = {}) {
27113
+ const tokenUrl = `${baseUrl}${HUB_AUTH_PATHS.deviceToken}`;
27114
+ const sleep = opts.sleep ?? defaultSleep;
27115
+ const now = opts.now ?? Date.now;
27116
+ let intervalMs = code.intervalSec * 1e3;
27117
+ const deadline = now() + code.expiresInSec * 1e3;
27118
+ while (now() < deadline + intervalMs) {
27119
+ await sleep(intervalMs);
27120
+ if (opts.signal?.aborted) return { ok: false, reason: "cancelled", error: "Sign-in cancelled" };
27121
+ let res;
27122
+ try {
27123
+ res = await postJson2(
27124
+ transport,
27125
+ tokenUrl,
27126
+ { grant_type: DEVICE_CODE_GRANT_TYPE, device_code: code.deviceCode, client_id: clientId },
27127
+ POLL_TIMEOUT_MS
27128
+ );
27129
+ } catch {
27130
+ continue;
27131
+ }
27132
+ const { status } = res;
27133
+ const body = jsonObject(res.text);
27134
+ const { error, access_token: token } = body;
27135
+ if (status === 200 && typeof token === "string" && token) return { ok: true, token };
27136
+ if (error === "authorization_pending") continue;
27137
+ if (error === "slow_down") {
27138
+ intervalMs += SLOW_DOWN_STEP_MS;
27139
+ continue;
27140
+ }
27141
+ if (error === "access_denied") {
27142
+ return { ok: false, reason: "denied", status, error: "Sign-in was denied in the browser" };
27143
+ }
27144
+ if (error === "expired_token") {
27145
+ return { ok: false, reason: "expired", status, error: "The sign-in code expired" };
27146
+ }
27147
+ if (body.code === "ACCOUNT_DISABLED") {
27148
+ return {
27149
+ ok: false,
27150
+ reason: "disabled",
27151
+ status,
27152
+ error: "This account is disabled on the hub"
27153
+ };
27154
+ }
27155
+ const description = stringOf(body.error_description);
27156
+ return {
27157
+ ok: false,
27158
+ reason: "failed",
27159
+ status,
27160
+ description,
27161
+ error: `Sign-in failed (HTTP ${status})${description === void 0 ? "" : `: ${description}`}`
27162
+ };
27163
+ }
27164
+ return { ok: false, reason: "expired", error: "The sign-in code expired" };
27165
+ }
27166
+
27167
+ // ../../domains/hub-auth/src/client/session.ts
27168
+ async function fetchSessionEmail(transport, baseUrl, token, timeoutMs = AUTH_TIMEOUT_MS) {
27169
+ try {
27170
+ const res = await transport({
27171
+ method: "GET",
27172
+ url: `${baseUrl}${HUB_AUTH_PATHS.session}`,
27173
+ headers: { authorization: `Bearer ${token}` },
27174
+ timeoutMs,
27175
+ maxResponseChars: AUTH_MAX_CHARS
27176
+ });
27177
+ const body = parseJson(res.text);
27178
+ return typeof body?.user?.email === "string" ? body.user.email : null;
27179
+ } catch {
27180
+ return null;
27181
+ }
27182
+ }
27183
+
27184
+ // ../../domains/hub-auth/src/client-node/index.ts
27185
+ var import_node_http3 = __toESM(require("node:http"), 1);
27186
+ var import_node_https = __toESM(require("node:https"), 1);
27187
+ function firstValue(value) {
27188
+ if (Array.isArray(value)) return value[0] ?? null;
27189
+ return value ?? null;
27190
+ }
27191
+ var nodeHubTransport = (request2) => new Promise((resolve2, reject) => {
27192
+ const send = request2.url.startsWith("https:") ? import_node_https.default.request : import_node_http3.default.request;
27193
+ const headers = { ...request2.headers };
27194
+ if (request2.body !== void 0) headers["content-length"] = Buffer.byteLength(request2.body);
27195
+ const req = send(
27196
+ request2.url,
27197
+ { method: request2.method, timeout: request2.timeoutMs, headers },
27198
+ (res) => {
27199
+ let text = "";
27200
+ res.setEncoding("utf8");
27201
+ res.on("data", (chunk) => {
27202
+ if (text.length < request2.maxResponseChars) text += chunk;
27203
+ });
27204
+ res.on(
27205
+ "end",
27206
+ () => resolve2({
27207
+ status: res.statusCode ?? 0,
27208
+ header: (name) => firstValue(res.headers[name.toLowerCase()]),
27209
+ text
27210
+ })
27211
+ );
27212
+ res.on("error", reject);
27213
+ }
27214
+ );
27215
+ req.on("error", reject);
27216
+ req.on("timeout", () => req.destroy(new HubTransportTimeoutError(request2.timeoutMs)));
27217
+ req.end(request2.body);
27218
+ });
27219
+
27220
+ // src/hub-sign-in.ts
27221
+ var CLI_DEVICE_CLIENT_ID = HUB_DEVICE_CLIENT_IDS.cli;
27222
+ async function readSignInMethods(baseUrl) {
27223
+ const health = await fetchHubHealth(nodeHubTransport, baseUrl, 1e4);
27224
+ if (!health.reachable) fail(`Could not reach the hub at ${baseUrl}.`);
27225
+ return signInMethodsOf(health.json) ?? { sso: false, password: true };
27226
+ }
27227
+ async function hubSignIn(baseUrl, email, password) {
27228
+ const result = await signInWithPassword(nodeHubTransport, baseUrl, { email, password });
27229
+ if (result.ok) return result.token;
27230
+ if (result.reason === "unreachable" || result.reason === "timeout") {
27231
+ fail(`Could not reach the hub at ${baseUrl}.`);
27232
+ }
27233
+ if (result.reason === "refused") {
27234
+ if (result.code === "HUB_PASSWORD_DISABLED") {
27235
+ fail(`Sign-in refused: ${result.hubError ?? "password sign-in is off on this hub"}`);
27236
+ }
27237
+ if (result.code === "ACCOUNT_DISABLED") {
27238
+ fail(
27239
+ "Sign-in refused: this account is disabled on the hub. An operator can enable it with `slay hub users enable <email>`."
27240
+ );
27241
+ }
27242
+ fail(
27243
+ `Sign-in failed (HTTP ${result.status}).
27244
+ Check the email and password. List the accounts on the hub box with \`slay hub users ls\`, or create one with \`slay hub users add <email>\`.`
27245
+ );
27246
+ }
27247
+ fail("The hub accepted the sign-in but returned no token.");
27248
+ }
26899
27249
  function tryOpenBrowser(url) {
26900
27250
  if (!/^https?:\/\//.test(url)) return;
26901
27251
  if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return;
@@ -26917,76 +27267,44 @@ function tryOpenBrowser(url) {
26917
27267
  } catch {
26918
27268
  }
26919
27269
  }
26920
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27270
+ function openApprovalPage(baseUrl, page, open = tryOpenBrowser) {
27271
+ if (!isHubOwnPage(baseUrl, page)) return false;
27272
+ open(page);
27273
+ return true;
27274
+ }
26921
27275
  async function deviceSignIn(baseUrl, opts) {
26922
27276
  const clientId = opts.clientId ?? CLI_DEVICE_CLIENT_ID;
26923
- let res;
26924
- try {
26925
- res = await postAuthJson(`${baseUrl}/api/auth/device/code`, { client_id: clientId });
26926
- } catch {
26927
- fail(`Could not reach the hub at ${baseUrl}.`);
26928
- }
26929
- const code = await res.json().catch(() => ({}));
26930
- if (!res.ok || !code.device_code || !code.user_code || !code.verification_uri) {
27277
+ const code = await requestDeviceCode(nodeHubTransport, baseUrl, clientId);
27278
+ if (!code.ok) {
27279
+ if (code.reason !== "refused") fail(`Could not reach the hub at ${baseUrl}.`);
26931
27280
  fail(
26932
- `The hub did not start a sign-in (HTTP ${res.status})` + (typeof code.error_description === "string" ? `: ${code.error_description}` : ".")
27281
+ `The hub did not start a sign-in (HTTP ${code.status})` + (code.description !== void 0 ? `: ${code.description}` : ".")
26933
27282
  );
26934
27283
  }
26935
- const page = code.verification_uri_complete ?? code.verification_uri;
26936
- const userCode = `${code.user_code.slice(0, 4)}-${code.user_code.slice(4)}`;
26937
- const minutes = Math.round((code.expires_in ?? 600) / 60);
27284
+ const page = code.verificationUri;
27285
+ const minutes = Math.round(code.expiresInSec / 60);
26938
27286
  console.log("To sign in, open this page in a browser (on any device) and approve:");
26939
27287
  console.log(` ${page}`);
26940
- console.log(`Check that the page shows this code: ${userCode} (valid ${minutes} min)`);
26941
- if (opts.openBrowser) tryOpenBrowser(page);
27288
+ console.log(`Check that the page shows this code: ${code.userCode} (valid ${minutes} min)`);
27289
+ if (opts.openBrowser && !openApprovalPage(baseUrl, page)) {
27290
+ console.log("Not opening it automatically: the page is not on this hub.");
27291
+ }
26942
27292
  console.log("Waiting for approval\u2026");
26943
- let intervalMs = Math.max(5, code.interval ?? 5) * 1e3;
26944
- const deadline = Date.now() + (code.expires_in ?? 600) * 1e3;
26945
- while (Date.now() < deadline + intervalMs) {
26946
- await sleep(intervalMs);
26947
- let poll;
26948
- try {
26949
- poll = await postAuthJson(`${baseUrl}/api/auth/device/token`, {
26950
- grant_type: DEVICE_GRANT,
26951
- device_code: code.device_code,
26952
- client_id: clientId
26953
- });
26954
- } catch {
26955
- continue;
26956
- }
26957
- const body = await poll.json().catch(() => ({}));
26958
- if (poll.ok && typeof body.access_token === "string" && body.access_token) {
26959
- return body.access_token;
26960
- }
26961
- if (body.error === "authorization_pending") continue;
26962
- if (body.error === "slow_down") {
26963
- intervalMs += 5e3;
26964
- continue;
26965
- }
26966
- if (body.error === "access_denied") fail("Sign-in was denied in the browser.");
26967
- if (body.error === "expired_token") {
26968
- fail("The code expired before it was approved. Run `slay hub login` again.");
26969
- }
26970
- if (body.code === "ACCOUNT_DISABLED") {
26971
- fail("Sign-in refused: this account is disabled on the hub. Ask a hub admin to enable it.");
26972
- }
26973
- fail(
26974
- `Sign-in failed (HTTP ${poll.status})` + (typeof body.error_description === "string" ? `: ${body.error_description}` : ".")
26975
- );
27293
+ const result = await waitForDeviceToken(nodeHubTransport, baseUrl, clientId, code);
27294
+ if (result.ok) return result.token;
27295
+ if (result.reason === "denied") fail("Sign-in was denied in the browser.");
27296
+ if (result.reason === "expired") {
27297
+ fail("The code expired before it was approved. Run `slay hub login` again.");
26976
27298
  }
26977
- fail("The code expired before it was approved. Run `slay hub login` again.");
26978
- }
26979
- async function signedInEmail(baseUrl, token) {
26980
- try {
26981
- const res = await fetch(`${baseUrl}/api/auth/get-session`, {
26982
- headers: { authorization: `Bearer ${token}` },
26983
- signal: AbortSignal.timeout(1e4)
26984
- });
26985
- const body = await res.json().catch(() => null);
26986
- return typeof body?.user?.email === "string" ? body.user.email : null;
26987
- } catch {
26988
- return null;
27299
+ if (result.reason === "disabled") {
27300
+ fail("Sign-in refused: this account is disabled on the hub. Ask a hub admin to enable it.");
26989
27301
  }
27302
+ fail(
27303
+ `Sign-in failed (HTTP ${result.status})` + (result.description !== void 0 ? `: ${result.description}` : ".")
27304
+ );
27305
+ }
27306
+ function signedInEmail(baseUrl, token) {
27307
+ return fetchSessionEmail(nodeHubTransport, baseUrl, token);
26990
27308
  }
26991
27309
 
26992
27310
  // ../../shared/platform/src/hub-auth-secret.ts
@@ -27102,21 +27420,22 @@ function hubBreakGlassCommand() {
27102
27420
  }
27103
27421
  const outcome = await redeem(url, verifier);
27104
27422
  if (outcome.ok) {
27105
- const configPath = writeHubConfig(url, outcome.token);
27423
+ const sessionPath = writeBreakGlassSession({
27424
+ url,
27425
+ token: outcome.token,
27426
+ expiresAt: outcome.expiresAt
27427
+ });
27106
27428
  console.log(
27107
27429
  `
27108
27430
  Break-glass session open as ${outcome.email} until ${outcome.expiresAt}.`
27109
27431
  );
27110
- console.log(`Token stored: ${configPath} (it replaces the stored hub target).`);
27432
+ console.log(
27433
+ `Session stored: ${sessionPath}. Hub commands use it until it ends; the stored hub target is unchanged.`
27434
+ );
27111
27435
  console.log("");
27112
27436
  console.log(" slay hub users ls | disable <email> | enable <email>");
27113
27437
  console.log(" slay hub computers ls | revoke <id> | unrevoke <id>");
27114
27438
  console.log(" slay hub break-glass end (when done)");
27115
- if (process.env.SLAYZONE_HUB_TOKEN) {
27116
- console.error(
27117
- "Note: SLAYZONE_HUB_TOKEN is set in the environment and takes precedence over this token."
27118
- );
27119
- }
27120
27439
  return;
27121
27440
  }
27122
27441
  if (outcome.status === 403) {
@@ -27130,21 +27449,37 @@ Break-glass session open as ${outcome.email} until ${outcome.expiresAt}.`
27130
27449
  }
27131
27450
  });
27132
27451
  cmd.command("end").description("End this CLI\u2019s break-glass session now and forget its token").action(async () => {
27133
- const target = resolveHubTarget();
27452
+ const session = readBreakGlassSession();
27453
+ const target = session ? { baseUrl: session.url, token: session.token, source: "break-glass" } : resolveHubCommandTarget();
27134
27454
  if (!target?.token?.startsWith(BREAK_GLASS_TOKEN_PREFIX)) {
27135
27455
  fail(
27136
27456
  "No break-glass session is stored for this CLI. On the hub machine, `slayzone-hub break-glass end` ends any."
27137
27457
  );
27138
27458
  }
27139
- await hubRequest({
27140
- target,
27141
- path: BREAK_GLASS_PATH,
27142
- method: "DELETE",
27143
- unwrap: "raw",
27144
- hints: { 401: "The session has already ended (expired, or ended on the hub machine)." }
27145
- });
27146
- if (!process.env.SLAYZONE_HUB_ADDRESS) removeHubConfig();
27147
- console.log("Break-glass session ended: the account is disabled and its token forgotten.");
27459
+ let res;
27460
+ try {
27461
+ res = await fetch(`${target.baseUrl}${BREAK_GLASS_PATH}`, {
27462
+ method: "DELETE",
27463
+ headers: { Authorization: `Bearer ${target.token}` },
27464
+ signal: AbortSignal.timeout(1e4)
27465
+ });
27466
+ } catch {
27467
+ fail(
27468
+ `Could not reach the hub at ${target.baseUrl}. The session stays stored; it ends on its own when it expires.`
27469
+ );
27470
+ }
27471
+ const alreadyEnded = res.status === 401;
27472
+ if (!res.ok && !alreadyEnded) {
27473
+ const body = await res.json().catch(() => ({}));
27474
+ fail(
27475
+ `Break-glass end failed: ${typeof body.error === "string" ? body.error : `HTTP ${res.status}`}`
27476
+ );
27477
+ }
27478
+ if (target.source === "break-glass") removeBreakGlassSession();
27479
+ else if (target.source === "file") removeHubConfig();
27480
+ console.log(
27481
+ alreadyEnded ? "The break-glass session had already ended (expired, or ended on the hub machine); its token is forgotten." : "Break-glass session ended: the account is disabled and its token forgotten."
27482
+ );
27148
27483
  });
27149
27484
  return cmd;
27150
27485
  }
@@ -27409,37 +27744,6 @@ async function readPasswordFromStdin() {
27409
27744
  for await (const chunk of process.stdin) chunks.push(chunk);
27410
27745
  return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
27411
27746
  }
27412
- async function hubSignIn(baseUrl, email, password) {
27413
- let res;
27414
- try {
27415
- res = await postAuthJson(`${baseUrl}/api/auth/sign-in/email`, { email, password });
27416
- } catch {
27417
- fail(`Could not reach the hub at ${baseUrl}.`);
27418
- }
27419
- if (!res.ok) {
27420
- const body2 = await res.json().catch(() => ({}));
27421
- const code = body2.code;
27422
- if (code === "HUB_PASSWORD_DISABLED") {
27423
- fail(
27424
- `Sign-in refused: ${typeof body2.error === "string" ? body2.error : "password sign-in is off on this hub"}`
27425
- );
27426
- }
27427
- if (code === "ACCOUNT_DISABLED") {
27428
- fail(
27429
- "Sign-in refused: this account is disabled on the hub. An operator can enable it with `slay hub users enable <email>`."
27430
- );
27431
- }
27432
- fail(
27433
- `Sign-in failed (HTTP ${res.status}).
27434
- Check the email and password. List the accounts on the hub box with \`slay hub users ls\`, or create one with \`slay hub users add <email>\`.`
27435
- );
27436
- }
27437
- const header = res.headers.get("set-auth-token");
27438
- if (header) return header;
27439
- const body = await res.json().catch(() => ({}));
27440
- if (typeof body.token === "string" && body.token) return body.token;
27441
- fail("The hub accepted the sign-in but returned no token.");
27442
- }
27443
27747
  function hubUsersRequest(method, body) {
27444
27748
  return resolveHubRequestTarget("hub users \u2026", discoverAllHubs).then(
27445
27749
  (target) => hubRequest({
@@ -27519,6 +27823,38 @@ function hubUsersCommand() {
27519
27823
  });
27520
27824
  return users;
27521
27825
  }
27826
+ function noteStoredTargetScope() {
27827
+ if (isTaskTerminal()) {
27828
+ console.error(
27829
+ "Note: this is a task terminal. Task commands here (tasks, artifacts, pty, \u2026) keep\ngoing to the hub that spawned it; hub commands (hub users, hub computers,\ncomputer mint) use this target. `slay hub current` shows both."
27830
+ );
27831
+ } else if (process.env.SLAYZONE_HUB_ADDRESS) {
27832
+ console.error("Note: SLAYZONE_HUB_ADDRESS is set and takes precedence over this config.");
27833
+ }
27834
+ }
27835
+ function describeTargetSource(target) {
27836
+ switch (target.source) {
27837
+ case "flag":
27838
+ return "--hub";
27839
+ case "break-glass":
27840
+ return `break-glass session, ${getBreakGlassSessionPath()}`;
27841
+ case "env":
27842
+ return isTaskTerminal() ? "SLAYZONE_HUB_ADDRESS (the hub that spawned this task terminal)" : "SLAYZONE_HUB_ADDRESS env";
27843
+ case "file":
27844
+ return `${getHubConfigPath()} (slay hub use / login)`;
27845
+ }
27846
+ }
27847
+ async function probeHealth(target) {
27848
+ try {
27849
+ const res = await fetch(`${target.baseUrl}/health`, {
27850
+ headers: target.token ? { Authorization: `Bearer ${target.token}` } : {},
27851
+ signal: AbortSignal.timeout(5e3)
27852
+ });
27853
+ return res.ok ? { ok: true, line: `Health: ok (HTTP ${res.status})` } : { ok: false, line: `Health: failed (HTTP ${res.status})` };
27854
+ } catch {
27855
+ return { ok: false, line: `Health: unreachable (could not connect to ${target.baseUrl})` };
27856
+ }
27857
+ }
27522
27858
  function hubCommand() {
27523
27859
  const cmd = new Command("hub").description("Run, list and target SlayZone hubs").showSuggestionAfterError(true).showHelpAfterError(true);
27524
27860
  cmd.command("ls").description("List the hubs running on this machine").option("--json", "Output as JSON").action(async (opts) => {
@@ -27815,9 +28151,7 @@ then \`slay hub start ${name}\`.`
27815
28151
  const configPath = writeHubConfig(url, opts.token ?? null);
27816
28152
  console.log(`Now targeting: ${url}`);
27817
28153
  console.log(`Config written: ${configPath}`);
27818
- if (process.env.SLAYZONE_HUB_ADDRESS) {
27819
- console.error("Note: SLAYZONE_HUB_ADDRESS is set and takes precedence over this config.");
27820
- }
28154
+ noteStoredTargetScope();
27821
28155
  });
27822
28156
  cmd.command("login <url>").description("Sign in to a hub and store its bearer token for this CLI").option(
27823
28157
  "--email <email>",
@@ -27858,6 +28192,7 @@ then \`slay hub start ${name}\`.`
27858
28192
  const configPath = writeHubConfig(url, token);
27859
28193
  console.log(`Signed in to ${url} as ${who}.`);
27860
28194
  console.log(`Token stored: ${configPath}`);
28195
+ noteStoredTargetScope();
27861
28196
  if (process.env.SLAYZONE_HUB_TOKEN) {
27862
28197
  console.error(
27863
28198
  "Note: SLAYZONE_HUB_TOKEN is set in the environment and takes precedence over this config."
@@ -27865,37 +28200,44 @@ then \`slay hub start ${name}\`.`
27865
28200
  }
27866
28201
  }
27867
28202
  );
27868
- cmd.command("current").description("Show which hub this CLI targets, and probe it").action(async () => {
27869
- const target = resolveHubTarget();
27870
- if (!target) {
27871
- console.log("No hub configured \u2014 using the local app.");
27872
- return;
27873
- }
27874
- const source = process.env.SLAYZONE_HUB_ADDRESS ? "SLAYZONE_HUB_ADDRESS env" : getHubConfigPath();
27875
- console.log(`Hub: ${target.baseUrl}`);
27876
- console.log(`Source: ${source}`);
27877
- console.log(`Token: ${target.token ? "set" : "not set"}`);
27878
- try {
27879
- const headers = target.token ? { Authorization: `Bearer ${target.token}` } : {};
27880
- const res = await fetch(`${target.baseUrl}/health`, {
27881
- headers,
27882
- signal: AbortSignal.timeout(5e3)
27883
- });
27884
- if (res.ok) {
27885
- console.log(`Health: ok (HTTP ${res.status})`);
27886
- } else {
27887
- console.error(`Health: failed (HTTP ${res.status})`);
27888
- process.exit(1);
28203
+ cmd.command("current").description("Show which hub task commands and hub commands target, and probe them").action(async () => {
28204
+ const probes = /* @__PURE__ */ new Map();
28205
+ let healthy = true;
28206
+ const blocks = [
28207
+ [
28208
+ "Task commands (tasks, artifacts, pty, \u2026)",
28209
+ resolveTaskCommandTarget(),
28210
+ "the local app (no hub configured)"
28211
+ ],
28212
+ [
28213
+ "Hub commands (hub users, hub computers, computer mint)",
28214
+ resolveHubCommandTarget(),
28215
+ "none configured: the one hub running on this machine, if exactly one is"
28216
+ ]
28217
+ ];
28218
+ for (const [label, target, none] of blocks) {
28219
+ console.log(`${label}:`);
28220
+ if (!target) {
28221
+ console.log(` Hub: ${none}`);
28222
+ continue;
27889
28223
  }
27890
- } catch {
27891
- console.error(`Health: unreachable (could not connect to ${target.baseUrl})`);
27892
- process.exit(1);
27893
- }
28224
+ console.log(` Hub: ${target.baseUrl}`);
28225
+ console.log(` Source: ${describeTargetSource(target)}`);
28226
+ console.log(` Token: ${target.token ? "set" : "not set"}`);
28227
+ const key = `${target.baseUrl}
28228
+ ${target.token ?? ""}`;
28229
+ if (!probes.has(key)) probes.set(key, probeHealth(target));
28230
+ const result = await probes.get(key);
28231
+ if (result.ok) console.log(` ${result.line}`);
28232
+ else console.error(` ${result.line}`);
28233
+ healthy &&= result.ok;
28234
+ }
28235
+ if (!healthy) process.exit(1);
27894
28236
  });
27895
28237
  cmd.command("forget").description("Drop the stored hub target (back to the local app)").action(() => {
27896
28238
  const removed = removeHubConfig();
27897
28239
  console.log(removed ? `Removed: ${getHubConfigPath()}` : "No hub target to remove.");
27898
- if (process.env.SLAYZONE_HUB_ADDRESS) {
28240
+ if (process.env.SLAYZONE_HUB_ADDRESS && !isTaskTerminal()) {
27899
28241
  console.error("Note: SLAYZONE_HUB_ADDRESS is still set in the environment.");
27900
28242
  }
27901
28243
  });
@@ -27977,7 +28319,7 @@ async function hubComputers() {
27977
28319
  let baseUrl;
27978
28320
  let token = null;
27979
28321
  try {
27980
- const configured = resolveHubTarget();
28322
+ const configured = resolveHubCommandTarget();
27981
28323
  if (configured) {
27982
28324
  baseUrl = configured.baseUrl;
27983
28325
  token = configured.token;
@@ -28762,7 +29104,7 @@ function updateCommand() {
28762
29104
  }
28763
29105
 
28764
29106
  // src/index.ts
28765
- var program2 = new Command().name("slay").description("SlayZone CLI").version("0.36.1").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
29107
+ var program2 = new Command().name("slay").description("SlayZone CLI").version("0.36.3").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
28766
29108
  const root = thisCommand.parent ?? thisCommand;
28767
29109
  const opts = root.opts();
28768
29110
  if (opts.dev) process.env.SLAYZONE_DEV = "1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slayzone/cli",
3
- "version": "0.36.1",
3
+ "version": "0.36.3",
4
4
  "description": "SlayZone CLI — run, list and target SlayZone hubs; drive tasks, ptys and projects",
5
5
  "license": "GPL-3.0-only",
6
6
  "private": false,