@deslop/deploy 0.1.1290 → 0.1.1295

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env -S node --max-old-space-size=16384 --heapsnapshot-near-heap-limit=3 --report-on-fatalerror
2
2
  import { createRequire } from "node:module";
3
- import { cwd, execPath } from "node:process";
3
+ import { cwd, execPath, pid, platform } from "node:process";
4
4
  import * as OS from "node:os";
5
+ import { cpus, hostname, loadavg, totalmem, userInfo } from "node:os";
5
6
  import * as NodeChildProcess from "node:child_process";
6
7
  import { Duplex, PassThrough, Readable, Transform, finished, pipeline } from "node:stream";
7
8
  import { Buffer as Buffer$1 } from "node:buffer";
@@ -4182,7 +4183,7 @@ const match$8 = /*#__PURE__*/ dual(2, (self, { onNone, onSome }) => isNone(self)
4182
4183
  * @category getters
4183
4184
  * @since 2.0.0
4184
4185
  */
4185
- const getOrElse = /*#__PURE__*/ dual(2, (self, onNone) => isNone(self) ? onNone() : self.value);
4186
+ const getOrElse$1 = /*#__PURE__*/ dual(2, (self, onNone) => isNone(self) ? onNone() : self.value);
4186
4187
  /**
4187
4188
  * Returns the fallback `Option` if `self` is `None`; otherwise returns `self`.
4188
4189
  *
@@ -4338,7 +4339,7 @@ const fromNullOr = (a) => a === null ? none() : some$1(a);
4338
4339
  * @category getters
4339
4340
  * @since 2.0.0
4340
4341
  */
4341
- const getOrNull = /*#__PURE__*/ getOrElse(constNull);
4342
+ const getOrNull = /*#__PURE__*/ getOrElse$1(constNull);
4342
4343
  /**
4343
4344
  * Extracts the value from a `Some`, or returns `undefined` for `None`.
4344
4345
  *
@@ -4368,7 +4369,7 @@ const getOrNull = /*#__PURE__*/ getOrElse(constNull);
4368
4369
  * @category getters
4369
4370
  * @since 2.0.0
4370
4371
  */
4371
- const getOrUndefined$1 = /*#__PURE__*/ getOrElse(constUndefined);
4372
+ const getOrUndefined$1 = /*#__PURE__*/ getOrElse$1(constUndefined);
4372
4373
  /**
4373
4374
  * Lifts a function that may throw into one that returns an `Option`.
4374
4375
  *
@@ -5858,6 +5859,40 @@ const map$10 = /*#__PURE__*/ dual(2, (self, f) => isSuccess$1(self) ? succeed$10
5858
5859
  */
5859
5860
  const match$7 = /*#__PURE__*/ dual(2, (self, { onFailure, onSuccess }) => isFailure$1(self) ? onFailure(self.failure) : onSuccess(self.success));
5860
5861
  /**
5862
+ * Extracts the success value, or computes a fallback from the error.
5863
+ *
5864
+ * **When to use**
5865
+ *
5866
+ * Use when you need the success value from a `Result`, with a fallback computed
5867
+ * from the failure value.
5868
+ *
5869
+ * **Details**
5870
+ *
5871
+ * - `Success<A>` returns the inner value
5872
+ * - `Failure<E>` applies `onFailure` to the error and returns the result
5873
+ * - The return type is `A | A2` (union of both branches)
5874
+ *
5875
+ * **Example** (Providing a fallback)
5876
+ *
5877
+ * ```ts import.meta.vitest
5878
+ * import { Result } from "effect"
5879
+ *
5880
+ * Result.getOrElse(Result.succeed(1), () => 0) // => 1
5881
+ *
5882
+ * Result.getOrElse(Result.fail("err"), () => 0) // => 0
5883
+ * ```
5884
+ *
5885
+ * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks
5886
+ * @see {@link getOrThrow} to throw on failure
5887
+ * @see {@link match} to map both branches
5888
+ * @see {@link orElse} to recover with another Result instead of unwrapping
5889
+ *
5890
+ * @stability stable
5891
+ * @category getters
5892
+ * @since 2.0.0
5893
+ */
5894
+ const getOrElse = /*#__PURE__*/ dual(2, (self, onFailure) => isFailure$1(self) ? onFailure(self.failure) : self.success);
5895
+ /**
5861
5896
  * Extracts the success value or throws the raw failure value `E`.
5862
5897
  *
5863
5898
  * **When to use**
@@ -11885,6 +11920,8 @@ const currentTimeMillis$1 = /*#__PURE__*/ clockWith$1((clock) => clock.currentTi
11885
11920
  /** @internal */
11886
11921
  const currentTimeNanos$1 = /*#__PURE__*/ clockWith$1((clock) => clock.currentTimeNanos);
11887
11922
  /** @internal */
11923
+ const monotonicTimeNanos$1 = /*#__PURE__*/ clockWith$1((clock) => clock.monotonicTimeNanos);
11924
+ /** @internal */
11888
11925
  const TimeoutErrorTypeId = "~effect/Cause/TimeoutError";
11889
11926
  /** @internal */
11890
11927
  const isTimeoutError$1 = (u) => hasProperty(u, TimeoutErrorTypeId);
@@ -15491,6 +15528,27 @@ const currentTimeMillis = currentTimeMillis$1;
15491
15528
  * @since 2.0.0
15492
15529
  */
15493
15530
  const currentTimeNanos = currentTimeNanos$1;
15531
+ /**
15532
+ * Returns an Effect that succeeds with the current monotonic time in
15533
+ * nanoseconds.
15534
+ *
15535
+ * **When to use**
15536
+ *
15537
+ * Use to measure elapsed time by subtracting two readings.
15538
+ *
15539
+ * **Gotchas**
15540
+ *
15541
+ * The value has an arbitrary origin and is unsuitable for serialization. Use
15542
+ * it only to subtract readings produced by the same clock. Whether it advances
15543
+ * while the host is suspended depends on the runtime.
15544
+ *
15545
+ * @see {@link currentTimeNanos} for Unix wall-clock timestamps
15546
+ *
15547
+ * @stability stable
15548
+ * @category accessors
15549
+ * @since 4.0.0
15550
+ */
15551
+ const monotonicTimeNanos = monotonicTimeNanos$1;
15494
15552
  // ../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/dateTime.js
15495
15553
  /** @internal */
15496
15554
  const TypeId$64 = "~effect/DateTime";
@@ -80367,7 +80425,7 @@ const watchNode = (path, info, options) => callback((queue) => acquireRelease(sy
80367
80425
  });
80368
80426
  return watcher;
80369
80427
  }), (watcher) => sync(() => watcher.close())).pipe(tap$1(() => sync(() => options?.onReady?.()))));
80370
- const watch = (backend, path, options) => all$1([stat(path), serviceOption(WatchBackend)]).pipe(map$5(([stat, callerBackend]) => orElse$3(callerBackend, () => backend).pipe(flatMap$7((_) => _.register(path, stat, options)), getOrElse(() => watchNode(path, stat, options)))), unwrap$4);
80428
+ const watch = (backend, path, options) => all$1([stat(path), serviceOption(WatchBackend)]).pipe(map$5(([stat, callerBackend]) => orElse$3(callerBackend, () => backend).pipe(flatMap$7((_) => _.register(path, stat, options)), getOrElse$1(() => watchNode(path, stat, options)))), unwrap$4);
80371
80429
  const writeFile = (path, data, options) => callback$1((resume, signal) => {
80372
80430
  try {
80373
80431
  NFS.writeFile(path, data, {
@@ -81038,7 +81096,7 @@ const make$9 = /*#__PURE__*/ make$26({
81038
81096
  return raw(stream, {
81039
81097
  headers: {
81040
81098
  ...headers,
81041
- "content-type": headers["content-type"] ?? getOrElse(getType(path), () => "application/octet-stream"),
81099
+ "content-type": headers["content-type"] ?? getOrElse$1(getType(path), () => "application/octet-stream"),
81042
81100
  "content-length": contentLength.toString()
81043
81101
  },
81044
81102
  status,
@@ -81048,7 +81106,7 @@ const make$9 = /*#__PURE__*/ make$26({
81048
81106
  fileWebResponse(file, status, statusText, headers, _options) {
81049
81107
  return raw(lazyReadable(() => Readable.fromWeb(file.stream())), {
81050
81108
  headers: merge$3(headers, fromRecordUnsafe({
81051
- "content-type": headers["content-type"] ?? (file.type === "" ? getOrElse(getType(file.name), () => "application/octet-stream") : file.type),
81109
+ "content-type": headers["content-type"] ?? (file.type === "" ? getOrElse$1(getType(file.name), () => "application/octet-stream") : file.type),
81052
81110
  "content-length": file.size.toString()
81053
81111
  })),
81054
81112
  status,
@@ -83839,7 +83897,7 @@ const handleConfirmRender = (options) => {
83839
83897
  const TRUE_VALUE_REGEXP = /^y|t$/;
83840
83898
  const FALSE_VALUE_REGEXP = /^n|f$/;
83841
83899
  const handleConfirmProcess = (input, defaultValue) => {
83842
- const value = getOrElse(input.input, () => "");
83900
+ const value = getOrElse$1(input.input, () => "");
83843
83901
  if (input.key.name === "enter" || input.key.name === "return") return succeed$5(Action$1.Submit({ value: defaultValue }));
83844
83902
  if (TRUE_VALUE_REGEXP.test(value.toLowerCase())) return succeed$5(Action$1.Submit({ value: true }));
83845
83903
  if (FALSE_VALUE_REGEXP.test(value.toLowerCase())) return succeed$5(Action$1.Submit({ value: false }));
@@ -84026,7 +84084,7 @@ const handleDateProcess = (options) => {
84026
84084
  } }),
84027
84085
  onSuccess: (value) => Action$1.Submit({ value })
84028
84086
  });
84029
- default: return succeed$5(defaultDateProcessor(getOrElse(input.input, () => ""), state));
84087
+ default: return succeed$5(defaultDateProcessor(getOrElse$1(input.input, () => ""), state));
84030
84088
  }
84031
84089
  };
84032
84090
  };
@@ -84096,7 +84154,7 @@ var DatePart = class {
84096
84154
  * Retrieves the next date part in the list of parts.
84097
84155
  */
84098
84156
  nextPart() {
84099
- const currentPartIndex = getOrElse(findFirstIndex(this.parts, (part) => part === this), () => 0);
84157
+ const currentPartIndex = getOrElse$1(findFirstIndex(this.parts, (part) => part === this), () => 0);
84100
84158
  return findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken());
84101
84159
  }
84102
84160
  /**
@@ -84418,7 +84476,7 @@ const handleProcessInteger = (options) => {
84418
84476
  onSuccess: (value) => Action$1.Submit({ value })
84419
84477
  });
84420
84478
  }
84421
- default: return defaultIntProcessor(getOrElse(input.input, () => ""), state);
84479
+ default: return defaultIntProcessor(getOrElse$1(input.input, () => ""), state);
84422
84480
  }
84423
84481
  };
84424
84482
  };
@@ -84463,7 +84521,7 @@ const handleProcessFloat = (options) => {
84463
84521
  onSuccess: (value) => Action$1.Submit({ value })
84464
84522
  }));
84465
84523
  }
84466
- default: return defaultFloatProcessor(getOrElse(input.input, () => ""), state);
84524
+ default: return defaultFloatProcessor(getOrElse$1(input.input, () => ""), state);
84467
84525
  }
84468
84526
  };
84469
84527
  };
@@ -84716,7 +84774,7 @@ const handleTextProcess = (options) => {
84716
84774
  });
84717
84775
  }
84718
84776
  case "tab": return processTab(state, options);
84719
- default: return defaultTextProcessor(getOrElse(input.input, () => ""), state);
84777
+ default: return defaultTextProcessor(getOrElse$1(input.input, () => ""), state);
84720
84778
  }
84721
84779
  };
84722
84780
  };
@@ -85268,7 +85326,7 @@ const optional$1 = (param) => {
85268
85326
  * @since 4.0.0
85269
85327
  */
85270
85328
  const withDefault$1 = /*#__PURE__*/ dual(2, (self, defaultValue) => {
85271
- if (!isEffect(defaultValue)) return map(optional$1(self), getOrElse(() => defaultValue));
85329
+ if (!isEffect(defaultValue)) return map(optional$1(self), getOrElse$1(() => defaultValue));
85272
85330
  return mapEffect(optional$1(self), match$8({
85273
85331
  onNone: () => defaultValue,
85274
85332
  onSome: succeed$5
@@ -85912,7 +85970,7 @@ const formatHelpDocImpl = (doc, colors, options) => {
85912
85970
  const optionalSuffix = arg.required ? "" : colors.dim(" (optional)");
85913
85971
  return {
85914
85972
  left: nameType,
85915
- right: getOrElse(arg.description, () => "") + optionalSuffix
85973
+ right: getOrElse$1(arg.description, () => "") + optionalSuffix
85916
85974
  };
85917
85975
  });
85918
85976
  sections.push(renderTable(argRows, 25));
@@ -85923,7 +85981,7 @@ const formatHelpDocImpl = (doc, colors, options) => {
85923
85981
  sections.push(renderTable(flags.map((flag) => {
85924
85982
  return {
85925
85983
  left: [`--${flag.name}`, ...flag.aliases].map(colors.green).join(", ") + (flag.type !== "boolean" ? ` ${colors.dim(flag.type)}` : ""),
85926
- right: getOrElse(flag.description, () => "")
85984
+ right: getOrElse$1(flag.description, () => "")
85927
85985
  };
85928
85986
  })));
85929
85987
  sections.push("");
@@ -88759,8 +88817,8 @@ const promptParam = /*#__PURE__*/ fnUntraced(function* (param) {
88759
88817
  }
88760
88818
  const count = !metadata.isVariadic ? 1 : yield* run$2(Int({
88761
88819
  message: `${renderParamLabel(single)} count`,
88762
- default: getOrElse(metadata.variadicMin, () => 0),
88763
- min: getOrElse(metadata.variadicMin, () => 0),
88820
+ default: getOrElse$1(metadata.variadicMin, () => 0),
88821
+ min: getOrElse$1(metadata.variadicMin, () => 0),
88764
88822
  ...isSome(metadata.variadicMax) ? { max: metadata.variadicMax.value } : {}
88765
88823
  }));
88766
88824
  const values = [];
@@ -91666,7 +91724,7 @@ const decodeUnverified = /*#__PURE__*/ fnUntraced(function* (token) {
91666
91724
  });
91667
91725
  // ../../packages/runtime/src/auth/sessions.ts
91668
91726
  const Stored = Struct({
91669
- access: NonEmptyString,
91727
+ access: RedactedFromValue(NonEmptyString),
91670
91728
  clientId: NonEmptyString,
91671
91729
  createdAt: Finite,
91672
91730
  expiresAt: Finite,
@@ -91696,7 +91754,7 @@ var Sessions = class Sessions extends Service$1()("@deslop/runtime/auth/sessions
91696
91754
  return digest.digestHex(sha256, new TextEncoder().encode(id));
91697
91755
  }
91698
91756
  function lockOf(key) {
91699
- return getOrElse(get$9(locks, key), () => {
91757
+ return getOrElse$1(get$9(locks, key), () => {
91700
91758
  const lock = makeUnsafe$5(1);
91701
91759
  set$5(locks, key, lock);
91702
91760
  return lock;
@@ -91710,14 +91768,14 @@ var Sessions = class Sessions extends Service$1()("@deslop/runtime/auth/sessions
91710
91768
  });
91711
91769
  const granted = fnUntraced(function* (params) {
91712
91770
  const response = yield* post$1(TOKEN_PATH, params);
91713
- if (response.status === 400 || response.status === 401) return yield* Refused.make({ message: getOrElse(flatMap$7(yield* option$1(schemaBodyJson$1(Refusal$1)(response)), (body) => fromUndefinedOr(body.error_description)), () => "Auth refused the sign-in") });
91771
+ if (response.status === 400 || response.status === 401) return yield* Refused.make({ message: getOrElse$1(flatMap$7(yield* option$1(schemaBodyJson$1(Refusal$1)(response)), (body) => fromUndefinedOr(body.error_description)), () => "Auth refused the sign-in") });
91714
91772
  return yield* schemaBodyJson$1(TokenResponse)(yield* filterStatusOk$1(response));
91715
91773
  });
91716
91774
  const stored = fnUntraced(function* (tokens, clientId, createdAt) {
91717
91775
  const claims = yield* decodeUnknownEffect(AccessClaims)((yield* decodeUnverified(tokens.access_token)).claims);
91718
91776
  const now = yield* currentTimeMillis;
91719
91777
  return Stored.make({
91720
- access: tokens.access_token,
91778
+ access: make$65(tokens.access_token),
91721
91779
  clientId,
91722
91780
  createdAt,
91723
91781
  expiresAt: now + tokens.expires_in * 1e3,
@@ -91749,14 +91807,14 @@ var Sessions = class Sessions extends Service$1()("@deslop/runtime/auth/sessions
91749
91807
  value
91750
91808
  }))), { concurrency: "unbounded" });
91751
91809
  for (const session of matchingSessions(saved, userId)) {
91752
- if (yield* fresh(session.value)) return session.value.access;
91810
+ if (yield* fresh(session.value)) return value$2(session.value.access);
91753
91811
  const renewed = yield* result$1(pipe(refreshed(session.key), rejected("AI access is temporarily unavailable")));
91754
- if (renewed._tag === "Success") return renewed.success.access;
91812
+ if (renewed._tag === "Success") return value$2(renewed.success.access);
91755
91813
  if (is$2(AuthError)(renewed.failure) && renewed.failure.error === "temporarily_unavailable") return yield* renewed.failure;
91756
91814
  }
91757
91815
  const now = yield* currentTimeMillis;
91758
91816
  const bearer = getOrUndefined$1(filter$5(get$9(bearers, userId), (access) => access.expiresAt >= now + 6e4));
91759
- if (bearer !== void 0) return bearer.token;
91817
+ if (bearer !== void 0) return value$2(bearer.token);
91760
91818
  remove$3(bearers, userId);
91761
91819
  return yield* AuthError.make({ message: `Open ${capitalize(split$2(new URL(app).hostname, ".")[0])} once so it can use AI for you` });
91762
91820
  }, rejected("AI access is temporarily unavailable"));
@@ -91765,12 +91823,12 @@ var Sessions = class Sessions extends Service$1()("@deslop/runtime/auth/sessions
91765
91823
  const key = yield* keyOf(id);
91766
91824
  const saved = yield* fromOption(yield* store.get(key));
91767
91825
  if (yield* fresh(saved)) return {
91768
- token: saved.access,
91826
+ token: value$2(saved.access),
91769
91827
  user: saved.user
91770
91828
  };
91771
91829
  const renewed = yield* refreshed(key);
91772
91830
  return {
91773
- token: renewed.access,
91831
+ token: value$2(renewed.access),
91774
91832
  user: renewed.user
91775
91833
  };
91776
91834
  }, rejected("Sign in first")),
@@ -91790,7 +91848,7 @@ var Sessions = class Sessions extends Service$1()("@deslop/runtime/auth/sessions
91790
91848
  remember: (token, claims) => sync(() => {
91791
91849
  set$5(bearers, claims.sub, {
91792
91850
  expiresAt: claims.exp * 1e3,
91793
- token
91851
+ token: make$65(token)
91794
91852
  });
91795
91853
  }),
91796
91854
  start: fn("Sessions.start")(function* (grant) {
@@ -92283,10 +92341,7 @@ var AppError = class extends TaggedError()("AppError", {
92283
92341
  cause: optional$8(Defect()),
92284
92342
  message: String$6
92285
92343
  }) {};
92286
- // ../../packages/runtime/src/cli/service.ts
92287
- function systemdArgument(value) {
92288
- return `"${pipe(value, replaceAll("\\", "\\\\"), replaceAll("\"", "\\\""), replaceAll("%", "%%"), replaceAll("$", "$$$$"), replaceAll("\n", "\\n"), replaceAll("\r", "\\r"))}"`;
92289
- }
92344
+ // ../../packages/runtime/src/cli/command.ts
92290
92345
  const execute = fnUntraced(function* (command, args) {
92291
92346
  const process = yield* make$12(command, args, {
92292
92347
  stderr: "pipe",
@@ -92300,6 +92355,86 @@ const execute = fnUntraced(function* (command, args) {
92300
92355
  if (result.code !== 0) return yield* AppError.make({ message: `${command} failed: ${result.stderr}` });
92301
92356
  return result.stdout;
92302
92357
  }, scoped);
92358
+ // ../../packages/runtime/src/cli/launchd.ts
92359
+ function xml(value) {
92360
+ return pipe(value, replaceAll("&", "&amp;"), replaceAll("<", "&lt;"), replaceAll(">", "&gt;"), replaceAll("\"", "&quot;"), replaceAll("'", "&apos;"));
92361
+ }
92362
+ function domain() {
92363
+ return `gui/${userInfo().uid}`;
92364
+ }
92365
+ function launchctl(...args) {
92366
+ return execute("launchctl", args);
92367
+ }
92368
+ function bootout(file) {
92369
+ return launchctl("bootout", domain(), file);
92370
+ }
92371
+ const loaded = fnUntraced(function* (target) {
92372
+ const process = yield* make$12("launchctl", ["print", target], {
92373
+ stderr: "pipe",
92374
+ stdout: "ignore"
92375
+ });
92376
+ const result = yield* all$1({
92377
+ code: process.exitCode,
92378
+ stderr: mkString(decodeText$1(process.stderr))
92379
+ }, { concurrency: "unbounded" });
92380
+ if (result.code === 113) return false;
92381
+ if (result.code !== 0) return yield* AppError.make({ message: `launchctl failed: ${result.stderr}` });
92382
+ return true;
92383
+ }, scoped);
92384
+ const agentDirectory = gen(function* () {
92385
+ return (yield* Path$1).join(yield* String$5("HOME"), "Library", "LaunchAgents");
92386
+ });
92387
+ const writeAgent = fnUntraced(function* (label, name, command, schedule) {
92388
+ const fs = yield* FileSystem;
92389
+ const path = yield* Path$1;
92390
+ const home = yield* String$5("HOME");
92391
+ const directory = yield* agentDirectory;
92392
+ const args = [
92393
+ execPath,
92394
+ `--env-file-if-exists=${home}/.deslop/${name}.env`,
92395
+ ...drop$1(command, 1)
92396
+ ];
92397
+ const file = path.join(directory, `${label}.plist`);
92398
+ yield* fs.makeDirectory(directory, { recursive: true });
92399
+ yield* fs.writeFileString(file, `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n<key>Label</key><string>${xml(label)}</string>\n<key>ProgramArguments</key>\n<array>\n${join$2(map$8(args, (arg) => `<string>${xml(arg)}</string>`), "\n")}\n</array>\n<key>EnvironmentVariables</key>\n<dict>\n<key>NODE_ENV</key><string>production</string>\n<key>PATH</key><string>${xml(`${home}/.vite-plus/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`)}</string>\n</dict>\n<key>Umask</key><integer>63</integer>\n${schedule}\n</dict>\n</plist>\n`, { mode: 384 });
92400
+ return file;
92401
+ });
92402
+ const installAgent = fnUntraced(function* (name, command) {
92403
+ const label = `deslop-${name}`;
92404
+ const target = `${domain()}/${label}`;
92405
+ const file = yield* writeAgent(label, name, command, "<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>3</integer>");
92406
+ if (yield* loaded(target)) yield* bootout(file);
92407
+ yield* launchctl("bootstrap", domain(), file);
92408
+ return `${label}.plist installed\n`;
92409
+ });
92410
+ const installUpdateAgent = fnUntraced(function* (name, command) {
92411
+ const label = `deslop-${name}-update`;
92412
+ const target = `${domain()}/${label}`;
92413
+ const file = yield* writeAgent(label, name, command, "<key>StartInterval</key><integer>900</integer>");
92414
+ if (yield* loaded(target)) yield* bootout(file);
92415
+ yield* launchctl("bootstrap", domain(), file);
92416
+ });
92417
+ const uninstallAgents = fnUntraced(function* (name) {
92418
+ const fs = yield* FileSystem;
92419
+ const path = yield* Path$1;
92420
+ const directory = yield* agentDirectory;
92421
+ yield* forEach$1([`deslop-${name}-update`, `deslop-${name}`], fnUntraced(function* (label) {
92422
+ const file = path.join(directory, `${label}.plist`);
92423
+ if (yield* loaded(`${domain()}/${label}`)) yield* bootout(file);
92424
+ yield* fs.remove(file, { force: true });
92425
+ }), { concurrency: 1 });
92426
+ return `deslop-${name}.plist removed; application data preserved\n`;
92427
+ });
92428
+ function agentStatus(name) {
92429
+ return pipe(launchctl("print", `${domain()}/deslop-${name}`), map$5((output) => `${join$2(map$8(filter$3(split$2(output, "\n"), (line) => isSome(match$3(/^\s*(?:path|state|pid|last exit code|last terminating signal) =/u)(line))), trim), "\n")}\n`));
92430
+ }
92431
+ function restartAgent(name) {
92432
+ return pipe(launchctl("kickstart", "-k", `${domain()}/deslop-${name}`), timeout$1("30 seconds"));
92433
+ }
92434
+ // ../../packages/runtime/src/cli/service.ts
92435
+ function systemdArgument(value) {
92436
+ return `"${pipe(value, replaceAll("\\", "\\\\"), replaceAll("\"", "\\\""), replaceAll("%", "%%"), replaceAll("$", "$$$$"), replaceAll("\n", "\\n"), replaceAll("\r", "\\r"))}"`;
92437
+ }
92303
92438
  function systemctl(...args) {
92304
92439
  return execute("systemctl", ["--user", ...args]);
92305
92440
  }
@@ -92307,6 +92442,7 @@ const unitDirectory = gen(function* () {
92307
92442
  return (yield* Path$1).join(yield* String$5("HOME"), ".config", "systemd", "user");
92308
92443
  });
92309
92444
  const install = fnUntraced(function* (name, command, options) {
92445
+ if (platform === "darwin") return yield* installAgent(name, command);
92310
92446
  const fs = yield* FileSystem;
92311
92447
  const path = yield* Path$1;
92312
92448
  const home = yield* String$5("HOME");
@@ -92323,6 +92459,7 @@ const install = fnUntraced(function* (name, command, options) {
92323
92459
  return `${unit} installed\n`;
92324
92460
  });
92325
92461
  const installUpdates = fnUntraced(function* (name, command) {
92462
+ if (platform === "darwin") return yield* installUpdateAgent(name, command);
92326
92463
  const fs = yield* FileSystem;
92327
92464
  const path = yield* Path$1;
92328
92465
  const directory = yield* unitDirectory;
@@ -92333,6 +92470,7 @@ const installUpdates = fnUntraced(function* (name, command) {
92333
92470
  yield* systemctl("enable", "--now", `${unit}.timer`);
92334
92471
  });
92335
92472
  const uninstall = fnUntraced(function* (name) {
92473
+ if (platform === "darwin") return yield* uninstallAgents(name);
92336
92474
  const fs = yield* FileSystem;
92337
92475
  const path = yield* Path$1;
92338
92476
  const directory = yield* unitDirectory;
@@ -92346,9 +92484,11 @@ const uninstall = fnUntraced(function* (name) {
92346
92484
  return `deslop-${name}.service removed; application data preserved\n`;
92347
92485
  });
92348
92486
  function status$1(name) {
92487
+ if (platform === "darwin") return agentStatus(name);
92349
92488
  return systemctl("show", `deslop-${name}.service`, "--property=LoadState,ActiveState,SubState,MainPID");
92350
92489
  }
92351
92490
  function restart(name) {
92491
+ if (platform === "darwin") return restartAgent(name);
92352
92492
  return pipe(systemctl("restart", `deslop-${name}.service`), timeout$1("30 seconds"));
92353
92493
  }
92354
92494
  // ../../packages/runtime/src/cli/update.ts
@@ -92619,7 +92759,7 @@ const RunRequest = Struct({
92619
92759
  });
92620
92760
  const RunJobInput = Struct({
92621
92761
  job: String$6.annotate({ description: "A scheduled job name as list_apps shows it." }),
92622
- worker: optionalKey(String$6.annotate({ description: "The worker running the job, when both do." }))
92762
+ worker: optionalKey(String$6.annotate({ description: "The worker running the job, when several do." }))
92623
92763
  });
92624
92764
  const ListAppsInput = Struct({
92625
92765
  app: optionalKey(String$6.annotate({ description: "A substring of an app or unit name; returns that app's process tree." })),
@@ -92816,10 +92956,10 @@ var Exposures = class Exposures extends Service$1()("@deslop/deploy/services/exp
92816
92956
  recursive: true
92817
92957
  });
92818
92958
  const store = toSchemaStore(yield* KeyValueStore, Record$1(String$6, Exposure));
92819
- const state = yield* make$41(getOrElse(yield* store.get("exposures"), () => ({})));
92959
+ const state = yield* make$41(getOrElse$1(yield* store.get("exposures"), () => ({})));
92820
92960
  const lock = yield* make$70(1);
92821
92961
  const spawner = yield* ChildProcessSpawner;
92822
- const worker = trim(yield* fs.readFileString("/proc/sys/kernel/hostname"));
92962
+ const worker = hostname();
92823
92963
  const path = yield* Path$1;
92824
92964
  const caddy = pipe((yield* ToolPath)("caddy"), provideService(FileSystem, fs), provideService(Path$1, path));
92825
92965
  const configFile = path.join(directory, "Caddyfile");
@@ -92886,6 +93026,7 @@ var Exposures = class Exposures extends Service$1()("@deslop/deploy/services/exp
92886
93026
  if (has$6(rows, input.name)) return yield* DeployError.make({ message: "Remove the existing owned exposure before changing it" });
92887
93027
  if (some(values(rows), (row) => row.hostname === input.hostname && (row.kind === "public" || row.port === input.port))) return yield* DeployError.make({ message: "This hostname or port already has an owned exposure" });
92888
93028
  if (input.kind === "public" && !input.publicAccess) return yield* DeployError.make({ message: "Explicitly confirm public access before publishing a port" });
93029
+ if (input.kind === "public" && platform !== "linux") return yield* DeployError.make({ message: "Public exposure needs a Linux worker; expose this port to the tailnet" });
92889
93030
  if (input.kind === "tailnet") yield* checkTailnet(input);
92890
93031
  const next = set$6(rows, input.name, input);
92891
93032
  yield* save(next);
@@ -92953,6 +93094,10 @@ function failureReason(result, status, ran) {
92953
93094
  onSome: (name) => `Exited with code ${status} (${name})`
92954
93095
  })), when("signal", () => `Killed by ${signal}`), when("core-dump", () => `Crashed with ${signal}`), when("oom-kill", () => "Killed for running out of memory"), when("timeout", () => "Timed out"), when("watchdog", () => "Stopped answering its watchdog"), when("start-limit-hit", () => "Restarted too often"), orElse(() => `Failed: ${result}`));
92955
93096
  }
93097
+ function exitFailure(status) {
93098
+ if (status < 0) return failureReason("signal", -status, true);
93099
+ return failureReason("exit-code", status, true);
93100
+ }
92956
93101
  function unitFailures(text) {
92957
93102
  return fromEntries(map$8(filter$3(split$2(trim(text), /\n\s*\n/u), isNonEmpty$1), (block) => {
92958
93103
  const fields = fromEntries(map$8(filter$3(split$2(block, "\n"), includes("=")), (line) => {
@@ -92964,10 +93109,21 @@ function unitFailures(text) {
92964
93109
  onNone: () => ({}),
92965
93110
  onSome: (seconds) => ({ at: seconds * 1e3 })
92966
93111
  }),
92967
- reason: failureReason(fields["Result"] ?? "", getOrElse(parse$3(fields["ExecMainStatus"] ?? ""), () => 0), fields["ExecMainCode"] !== "0")
93112
+ reason: failureReason(fields["Result"] ?? "", getOrElse$1(parse$3(fields["ExecMainStatus"] ?? ""), () => 0), fields["ExecMainCode"] !== "0")
92968
93113
  }];
92969
93114
  }));
92970
93115
  }
93116
+ // src/services/inventory/lib/launchd.ts
93117
+ function launchAgents(text) {
93118
+ return getSomes(map$8(drop$1(split$2(trim(text), "\n"), 1), (line) => {
93119
+ const [pid, status, label] = split$2(line, " ");
93120
+ return map$11(liftPredicate(label ?? "", (name) => startsWith("deslop-")(name) && !endsWith("-update")(name)), (name) => ({
93121
+ label: name,
93122
+ pid: parse$3(pid),
93123
+ status: getOrElse$1(parse$3(status ?? ""), () => 0)
93124
+ }));
93125
+ }));
93126
+ }
92971
93127
  // src/services/inventory/lib/command.ts
92972
93128
  const WRAPPERS = [
92973
93129
  "env",
@@ -93019,7 +93175,7 @@ const SUBJECT = {
93019
93175
  vp: ["filter"]
93020
93176
  };
93021
93177
  function basename(value) {
93022
- return getOrElse(last(filter$3(split$2(value, "/"), isNonEmpty$1)), () => value);
93178
+ return getOrElse$1(last(filter$3(split$2(value, "/"), isNonEmpty$1)), () => value);
93023
93179
  }
93024
93180
  function isFlag(token) {
93025
93181
  return startsWith("-")(token) && token !== "-" && token !== "--";
@@ -93037,7 +93193,7 @@ function flagParts(token) {
93037
93193
  inline: none()
93038
93194
  }),
93039
93195
  onSome: (match) => ({
93040
- flag: getOrElse(fromUndefinedOr(match[1]), () => ""),
93196
+ flag: getOrElse$1(fromUndefinedOr(match[1]), () => ""),
93041
93197
  inline: fromUndefinedOr(match[2])
93042
93198
  })
93043
93199
  });
@@ -93046,17 +93202,17 @@ function alias(value$4) {
93046
93202
  return pipe(value(value$4), when("vite-plus", () => "vp"), orElse(() => value$4));
93047
93203
  }
93048
93204
  function shellRest(tokens) {
93049
- const script = getOrElse(get$10(tokens, 2), () => "");
93205
+ const script = getOrElse$1(get$10(tokens, 2), () => "");
93050
93206
  const shifts = match$8(match$3(/\bshift\b/gu)(script), {
93051
93207
  onNone: () => 0,
93052
93208
  onSome: (matches) => matches.length
93053
93209
  });
93054
93210
  if (includes("exec \"$@\"")(script)) return drop$1(tokens, 4 + shifts);
93055
93211
  const segments = filter$3(map$8(split$2(replaceAll(/\d*[<>]+\|?\s*\S+/gu, "")(replaceAll(/['"]/gu, "")(script)), /\s*(?:\|\|?|;|&&)\s*/u), (segment) => dropWhile(split$2(replace(/^eval\s+/u, "")(trim(segment)), /\s+/u), assignment)), (words) => isNonEmpty$1(words[0] ?? ""));
93056
- return pipe(findFirst(segments, (words) => words[0] === "exec"), map$11((words) => drop$1(words, 1)), orElse$3(() => findFirst(segments, (words) => !contains(SETUP, words[0] ?? ""))), getOrElse(() => take$3(tokens, 1)));
93212
+ return pipe(findFirst(segments, (words) => words[0] === "exec"), map$11((words) => drop$1(words, 1)), orElse$3(() => findFirst(segments, (words) => !contains(SETUP, words[0] ?? ""))), getOrElse$1(() => take$3(tokens, 1)));
93057
93213
  }
93058
93214
  function unwrapTokens(tokens, cwd) {
93059
- const name = basename(getOrElse(head(tokens), () => ""));
93215
+ const name = basename(getOrElse$1(head(tokens), () => ""));
93060
93216
  if (contains(WRAPPERS, name)) return unwrapTokens(pipe(findFirstIndex(tokens, (token) => token === "--"), filter$5((index) => index > 0), match$8({
93061
93217
  onNone: () => {
93062
93218
  const tail = drop$1(tokens, 1);
@@ -93067,14 +93223,14 @@ function unwrapTokens(tokens, cwd) {
93067
93223
  },
93068
93224
  onSome: (index) => drop$1(tokens, index + 1)
93069
93225
  })), cwd);
93070
- if (contains(SHELLS, name) && getOrElse(get$10(tokens, 1), () => "") === "-c") return unwrapTokens(shellRest(tokens), cwd);
93226
+ if (contains(SHELLS, name) && getOrElse$1(get$10(tokens, 1), () => "") === "-c") return unwrapTokens(shellRest(tokens), cwd);
93071
93227
  if (contains(RUNTIMES, name)) return pipe(findFirstIndex(tokens, (token, index) => index > 0 && !isFlag(token)), match$8({
93072
93228
  onNone: () => tokens,
93073
93229
  onSome: (index) => {
93074
- const script = getOrElse(get$10(tokens, index), () => "");
93230
+ const script = getOrElse$1(get$10(tokens, index), () => "");
93075
93231
  const pkg = capture(/.*node_modules\/((?:@[^/]+\/)?[^/.][^/]*)\//u, script);
93076
93232
  const app = pipe(capture(/\.deslop\/([^/]+)\//u, script), orElse$3(() => flatMap$7(cwd, (value) => capture(/\/apps\/([^/]+)$/u, value))));
93077
- return [getOrElse(pipe(pkg, orElse$3(() => app)), () => basename(script)), ...drop$1(tokens, index + 1)];
93233
+ return [getOrElse$1(pipe(pkg, orElse$3(() => app)), () => basename(script)), ...drop$1(tokens, index + 1)];
93078
93234
  }
93079
93235
  }));
93080
93236
  return tokens;
@@ -93082,9 +93238,9 @@ function unwrapTokens(tokens, cwd) {
93082
93238
  function unwrap(argv, cwd) {
93083
93239
  const tokens = match$1(length$2(argv) === 1, {
93084
93240
  onFalse: () => argv,
93085
- onTrue: () => filter$3(split$2(getOrElse(head(argv), () => ""), /\s+/u), isNonEmpty$1)
93241
+ onTrue: () => filter$3(split$2(getOrElse$1(head(argv), () => ""), /\s+/u), isNonEmpty$1)
93086
93242
  });
93087
- return unwrapTokens([replace(/:$/u, "")(getOrElse(head(tokens), () => "")), ...drop$1(tokens, 1)], cwd);
93243
+ return unwrapTokens([replace(/:$/u, "")(getOrElse$1(head(tokens), () => "")), ...drop$1(tokens, 1)], cwd);
93088
93244
  }
93089
93245
  function scan(name, subject, args, words, values) {
93090
93246
  return match$8(head(args), {
@@ -93114,7 +93270,7 @@ function scan(name, subject, args, words, values) {
93114
93270
  }
93115
93271
  if (name === "ssh") return {
93116
93272
  ssh: some$1({
93117
- host: getOrElse(last(split$2(token, "@")), () => token),
93273
+ host: getOrElse$1(last(split$2(token, "@")), () => token),
93118
93274
  remote: drop$1(args, 1)
93119
93275
  }),
93120
93276
  values,
@@ -93132,10 +93288,10 @@ function scan(name, subject, args, words, values) {
93132
93288
  function commandLabel(argv, cwd) {
93133
93289
  const [head = "", ...args] = unwrap(argv, cwd);
93134
93290
  const name = alias(basename(head));
93135
- const subject = getOrElse(get$11(SUBJECT, name), () => empty$12());
93291
+ const subject = getOrElse$1(get$11(SUBJECT, name), () => empty$12());
93136
93292
  const scanned = scan(name, subject, args, [], {});
93137
93293
  if (contains(SHELLS, name) && isReadonlyArrayEmpty(scanned.words)) return {
93138
- detail: getOrElse(map$11(cwd, basename), () => ""),
93294
+ detail: getOrElse$1(map$11(cwd, basename), () => ""),
93139
93295
  name
93140
93296
  };
93141
93297
  return match$8(scanned.ssh, {
@@ -93160,8 +93316,8 @@ function processOwner(cgroup) {
93160
93316
  const container = getOrUndefined$1(match$3(/\/(?:docker-|docker\/)([a-f0-9]{12,64})(?:\.scope)?(?:\/|\n|$)/u)(cgroup))?.[1];
93161
93317
  if (container !== void 0) return `container:${slice$1(0, 12)(container)}`;
93162
93318
  const segments = split$2(cgroup, /[/\n]/u);
93163
- const service = getOrElse(findLastIndex(segments, endsWith(".service")), () => -1);
93164
- const manager = getOrElse(findFirstIndex(segments, (segment) => isSome(match$3(/^user@[0-9]+\.service$/u)(segment))), () => Infinity);
93319
+ const service = getOrElse$1(findLastIndex(segments, endsWith(".service")), () => -1);
93320
+ const manager = getOrElse$1(findFirstIndex(segments, (segment) => isSome(match$3(/^user@[0-9]+\.service$/u)(segment))), () => Infinity);
93165
93321
  return match$8(flatMap$7(liftPredicate(drop$1(segments, manager + 1), () => service <= manager), (below) => findFirst(below, (segment) => match$3(/^app-(.+)\.slice$/u)(segment))), {
93166
93322
  onNone: () => `service:${match$1(service > manager, {
93167
93323
  onFalse: () => "system",
@@ -93175,7 +93331,7 @@ function loopbackPort(item) {
93175
93331
  return item.kind === "port" && item.protocol === "tcp" && item.port !== void 0 && item.port >= 1024 && isSome(match$3(/^(?:127\.0\.0\.1|0\.0\.0\.0):/u)(item.address ?? ""));
93176
93332
  }
93177
93333
  function appPort(item) {
93178
- return loopbackPort(item) && item.process !== void 0 && item.process !== "" && !contains([5353, 5355], item.port ?? 0) && isNone(match$3(/^(?:ssh|cloudflared|tailscaled|caddy)$/u)(item.process ?? ""));
93334
+ return loopbackPort(item) && item.process !== void 0 && item.process !== "" && !contains([5353, 5355], item.port ?? 0) && isNone(match$3(/^(?:ssh|cloudflared|tailscaled|caddy|ControlCenter)$/u)(item.process ?? ""));
93179
93335
  }
93180
93336
  function important(item) {
93181
93337
  if (includes("failed")(item.state) || includes("unhealthy")(item.detail)) return true;
@@ -93190,7 +93346,7 @@ function ports(items) {
93190
93346
  return pipe(items, filter$3((item) => appPort(item) && item.http === true && !startsWith("stale")(item.state)), sort(mapInput(String$10, (item) => `${item.worker}:${item.port}:${item.address}`)), dedupeWith((a, b) => a.worker === b.worker && a.port === b.port));
93191
93347
  }
93192
93348
  function itemOwner(item) {
93193
- if (item.kind === "container") return `container:${slice$1(0, 12)(getOrElse(last(split$2(item.id, ":docker:")), () => ""))}`;
93349
+ if (item.kind === "container") return `container:${slice$1(0, 12)(getOrElse$1(last(split$2(item.id, ":docker:")), () => ""))}`;
93194
93350
  return `service:${item.scope ?? "system"}:${item.name}`;
93195
93351
  }
93196
93352
  function fullName(item) {
@@ -93226,7 +93382,7 @@ function workloads(items) {
93226
93382
  const attached = filter$3(byUnit[item.worker]?.[item.name] ?? [], (listener) => listener.unit === item.name);
93227
93383
  const bindings = map$8(item.bindings ?? [], (binding) => ({
93228
93384
  ...item,
93229
- ...getOrElse(filter$5(get$7(bySocket, socket(item.worker, binding)), () => binding.address !== "container"), () => ({})),
93385
+ ...getOrElse$1(filter$5(get$7(bySocket, socket(item.worker, binding)), () => binding.address !== "container"), () => ({})),
93230
93386
  ...binding,
93231
93387
  bindings: [],
93232
93388
  id: `${item.id}:port:${binding.address}`,
@@ -93396,7 +93552,7 @@ const PROCESS_INTERVAL = 2e3;
93396
93552
  const SECRET = /(?:token|secret|passw(?:or)?d|key|auth|credential|cookie|session)/iu;
93397
93553
  function processStatus(status) {
93398
93554
  const values = fromEntries(map$8(split$2(trim(status), "\n"), (line) => {
93399
- const at = getOrElse(indexOf(":")(line), () => -1);
93555
+ const at = getOrElse$1(indexOf(":")(line), () => -1);
93400
93556
  return [slice$1(0, at)(line), trim(slice$1(at + 1)(line))];
93401
93557
  }));
93402
93558
  return {
@@ -93427,7 +93583,7 @@ const processes = gen(function* () {
93427
93583
  const stat = yield* fs.readFileString(`/proc/${pid}/stat`);
93428
93584
  const cwd = yield* option$1(fs.readLink(`/proc/${pid}/cwd`));
93429
93585
  const command = map$11(yield* option$1(fs.readFileString(`/proc/${pid}/cmdline`)), commandArgs);
93430
- const fields = split$2(slice$1(getOrElse(lastIndexOf(")")(stat), () => -1) + 2)(stat), /\s+/u);
93586
+ const fields = split$2(slice$1(getOrElse$1(lastIndexOf(")")(stat), () => -1) + 2)(stat), /\s+/u);
93431
93587
  const parsed = yield* try_({
93432
93588
  catch: (cause) => DeployError.make({
93433
93589
  cause,
@@ -93436,7 +93592,7 @@ const processes = gen(function* () {
93436
93592
  try: () => processStatus(status)
93437
93593
  });
93438
93594
  return {
93439
- cgroup: yield* fs.readFileString(`/proc/${pid}/cgroup`),
93595
+ owner: processOwner(yield* fs.readFileString(`/proc/${pid}/cgroup`)),
93440
93596
  process: {
93441
93597
  ...parsed,
93442
93598
  ...match$8(command, {
@@ -93499,8 +93655,41 @@ function processReadings(current, previous) {
93499
93655
  readings: processUsage(current, previous?.baseline)
93500
93656
  };
93501
93657
  }
93658
+ function launchdProcesses(text, agents) {
93659
+ const rows = getSomes(map$8(split$2(text, "\n"), (line) => map$11(match$3(/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+(\S+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/u)(line), (match) => ({
93660
+ args: match[6] ?? "",
93661
+ cpu: match[4] ?? "",
93662
+ memory: match[3] ?? "",
93663
+ parent: match[2] ?? "",
93664
+ pid: match[1] ?? "",
93665
+ start: match[5] ?? ""
93666
+ }))));
93667
+ const parents = fromEntries(map$8(rows, (row) => [row.pid, row.parent]));
93668
+ function agent(pid) {
93669
+ return orElse$3(get$11(agents, pid), () => flatMap$7(filter$5(get$11(parents, pid), (parent) => parent !== pid), agent));
93670
+ }
93671
+ return getSomes(map$8(rows, (row) => flatMap$7(agent(row.pid), (unit) => pipe(all$4({
93672
+ start: map$11(make$66(row.start), toEpochMillis),
93673
+ ticks: map$11(match$3(/^(?:([0-9]+):)?([0-9]+):([0-9]+(?:\.[0-9]+)?)$/u)(row.cpu), (match) => ((getOrElse$1(parse$3(match[1] ?? ""), () => 0) * 60 + getOrElse$1(parse$3(match[2] ?? ""), () => 0)) * 60 + getOrElse$1(parse$3(match[3] ?? ""), () => 0)) * 1e3)
93674
+ }), map$11((times) => {
93675
+ const command = commandArgs(join$2(split$2(trim(row.args), /\s+/u), "\0"));
93676
+ return {
93677
+ ...times,
93678
+ owner: `service:user:${unit}`,
93679
+ process: {
93680
+ command,
93681
+ label: commandLabel(command, none()),
93682
+ memory: decodeSync(FiniteFromString)(row.memory) * 1024,
93683
+ name: getOrElse$1(flatMap$7(head(command), (head) => last(split$2(head, "/"))), () => ""),
93684
+ parent: decodeSync(FiniteFromString.check(isInt()))(row.parent),
93685
+ pid: decodeSync(FiniteFromString.check(isInt()))(row.pid)
93686
+ },
93687
+ unit
93688
+ };
93689
+ })))));
93690
+ }
93502
93691
  function attachProcesses(items, records) {
93503
- const owners = groupBy(records, (record) => processOwner(record.cgroup));
93692
+ const owners = groupBy(records, (record) => record.owner);
93504
93693
  return map$8(items, (item) => ({
93505
93694
  ...item,
93506
93695
  processes: map$8(match$1(item.kind === "service" || item.kind === "container", {
@@ -93513,7 +93702,7 @@ function attachProcesses(items, records) {
93513
93702
  function socketLine(line) {
93514
93703
  const fields = split$2(trim(line), /\s+/u);
93515
93704
  const address = fields[4] ?? "";
93516
- return map$11(parse$3(getOrElse(last(split$2(address, ":")), () => "")), (port) => ({
93705
+ return map$11(parse$3(getOrElse$1(last(split$2(address, ":")), () => "")), (port) => ({
93517
93706
  address,
93518
93707
  port,
93519
93708
  process: map$11(match$3(/users:\(\("([^"]+)",pid=([0-9]+)/u)(line), (match) => ({
@@ -93524,8 +93713,97 @@ function socketLine(line) {
93524
93713
  state: fields[1] ?? "listening"
93525
93714
  }));
93526
93715
  }
93716
+ function lsofSocket(file) {
93717
+ if (includes("->")(file.address) || !contains(["TCP", "UDP"], file.protocol)) return none();
93718
+ const address = replace(/^\*:/u, match$1(file.type === "IPv4", {
93719
+ onFalse: () => "*:",
93720
+ onTrue: () => "0.0.0.0:"
93721
+ }))(file.address);
93722
+ return map$11(parse$3(getOrElse$1(last(split$2(address, ":")), () => "")), (port) => ({
93723
+ address,
93724
+ port,
93725
+ process: some$1({
93726
+ name: file.process,
93727
+ pid: file.pid
93728
+ }),
93729
+ protocol: toLowerCase(file.protocol),
93730
+ state: match$1(file.protocol === "TCP", {
93731
+ onFalse: () => "UNCONN",
93732
+ onTrue: () => replace(/^ST=/u, "")(file.state) || "LISTEN"
93733
+ })
93734
+ }));
93735
+ }
93736
+ function lsofSockets(text) {
93737
+ const empty = {
93738
+ address: "",
93739
+ pid: "",
93740
+ process: "",
93741
+ protocol: "",
93742
+ state: "",
93743
+ type: ""
93744
+ };
93745
+ const scanned = reduce(split$2(text, "\n"), {
93746
+ file: empty,
93747
+ sockets: empty$12()
93748
+ }, (scan, line) => {
93749
+ const value = slice$1(1)(line);
93750
+ const flushed = [...scan.sockets, ...toArray$1(lsofSocket(scan.file))];
93751
+ if (startsWith("p")(line)) return {
93752
+ file: {
93753
+ ...empty,
93754
+ pid: value
93755
+ },
93756
+ sockets: flushed
93757
+ };
93758
+ if (startsWith("c")(line)) return {
93759
+ ...scan,
93760
+ file: {
93761
+ ...scan.file,
93762
+ process: value
93763
+ }
93764
+ };
93765
+ if (startsWith("f")(line)) return {
93766
+ file: {
93767
+ ...empty,
93768
+ pid: scan.file.pid,
93769
+ process: scan.file.process
93770
+ },
93771
+ sockets: flushed
93772
+ };
93773
+ if (startsWith("t")(line)) return {
93774
+ ...scan,
93775
+ file: {
93776
+ ...scan.file,
93777
+ type: value
93778
+ }
93779
+ };
93780
+ if (startsWith("P")(line)) return {
93781
+ ...scan,
93782
+ file: {
93783
+ ...scan.file,
93784
+ protocol: value
93785
+ }
93786
+ };
93787
+ if (startsWith("n")(line)) return {
93788
+ ...scan,
93789
+ file: {
93790
+ ...scan.file,
93791
+ address: value
93792
+ }
93793
+ };
93794
+ if (startsWith("TST=")(line)) return {
93795
+ ...scan,
93796
+ file: {
93797
+ ...scan.file,
93798
+ state: value
93799
+ }
93800
+ };
93801
+ return scan;
93802
+ });
93803
+ return dedupeWith([...scanned.sockets, ...toArray$1(lsofSocket(scanned.file))], (a, b) => a.protocol === b.protocol && a.address === b.address);
93804
+ }
93527
93805
  function socketUnit(cgroup) {
93528
- return getOrElse(map$11(findLast$1(matchAll(/\/([^/]+\.service)(?=\/|\n|$)/gu)(cgroup), () => true), (match) => match[1] ?? ""), () => "");
93806
+ return getOrElse$1(map$11(findLast$1(matchAll(/\/([^/]+\.service)(?=\/|\n|$)/gu)(cgroup), () => true), (match) => match[1] ?? ""), () => "");
93529
93807
  }
93530
93808
  function socketProcess(name, cwd) {
93531
93809
  return match$8(match$3(/\/apps\/([^/]+)(?:\/|$)/u)(cwd), {
@@ -93537,19 +93815,20 @@ function probeSocket(listener, process) {
93537
93815
  return listener.protocol === "tcp" && listener.port >= 1024 && isSome(match$3(/^(?:127\.0\.0\.1|0\.0\.0\.0):/u)(listener.address)) && isNone(match$3(/^(?:postgres|redis|ssh|cloudflared|tailscaled|caddy)$/u)(process));
93538
93816
  }
93539
93817
  // src/services/inventory/service.ts
93540
- function portItems(text, worker, fs, http) {
93541
- return forEach$1(getSomes(map$8(split$2(trim(text), "\n"), socketLine)), fnUntraced(function* (socket) {
93542
- const unit = socketUnit(yield* match$8(socket.process, {
93818
+ function portItems(sockets, worker, http, origin) {
93819
+ return forEach$1(sockets, fnUntraced(function* (socket) {
93820
+ const unit = yield* match$8(socket.process, {
93543
93821
  onNone: () => succeed$5(""),
93544
- onSome: fnUntraced(function* (match) {
93545
- return getOrElse(yield* option$1(fs.readFileString(`/proc/${match.pid}/cgroup`)), () => "");
93546
- })
93547
- }));
93822
+ onSome: (match) => origin.unit(match.pid ?? "")
93823
+ });
93548
93824
  const process = yield* match$8(socket.process, {
93549
93825
  onNone: () => succeed$5(""),
93550
93826
  onSome: fnUntraced(function* (match) {
93551
93827
  if (!startsWith("node")(match.name)) return match.name;
93552
- return yield* pipe(fs.readLink(`/proc/${match.pid}/cwd`), map$5((cwd) => socketProcess(match.name, cwd)), orElseSucceed(() => match.name));
93828
+ return match$8(yield* origin.cwd(match.pid ?? ""), {
93829
+ onNone: () => match.name,
93830
+ onSome: (cwd) => socketProcess(match.name, cwd)
93831
+ });
93553
93832
  })
93554
93833
  });
93555
93834
  const response = yield* match$1(probeSocket(socket, process), {
@@ -93570,7 +93849,7 @@ function portItems(text, worker, fs, http) {
93570
93849
  })
93571
93850
  });
93572
93851
  return InventoryItem.make({
93573
- ...getOrElse(response, () => ({
93852
+ ...getOrElse$1(response, () => ({
93574
93853
  http: false,
93575
93854
  ui: false
93576
93855
  })),
@@ -93621,7 +93900,7 @@ var Inventory = class Inventory extends Service$1()("@deslop/deploy/services/inv
93621
93900
  message: cause.message
93622
93901
  })), provideService(ChildProcessSpawner, spawner));
93623
93902
  }
93624
- const worker = trim(yield* fs.readFileString("/proc/sys/kernel/hostname"));
93903
+ const worker = hostname();
93625
93904
  const processState = yield* make$44(none());
93626
93905
  const units = fnUntraced(function* (system) {
93627
93906
  const scope = match$1(system, {
@@ -93648,7 +93927,7 @@ var Inventory = class Inventory extends Service$1()("@deslop/deploy/services/inv
93648
93927
  "--no-pager"
93649
93928
  ]), flatMap$2(decodeUnknownEffect(fromJsonString(ArraySchema(Unit)))));
93650
93929
  const failed = map$8(filter$3(rows, (row) => row.active === "failed"), (row) => row.unit);
93651
- const failures = getOrElse(flatten$5(yield* pipe(command("systemctl", [
93930
+ const failures = getOrElse$1(flatten$5(yield* pipe(command("systemctl", [
93652
93931
  ...manager,
93653
93932
  "show",
93654
93933
  ...failed,
@@ -93681,8 +93960,119 @@ var Inventory = class Inventory extends Service$1()("@deslop/deploy/services/inv
93681
93960
  worker
93682
93961
  }));
93683
93962
  });
93963
+ const docker = pipe(command("docker", [
93964
+ "ps",
93965
+ "--all",
93966
+ "--format",
93967
+ "{{json .}}"
93968
+ ]), flatMap$2((text) => forEach$1(filter$3(split$2(text, "\n"), isNonEmpty$1), (line) => decodeEffect(fromJsonString(Container))(line), { concurrency: 1 })), map$5((rows) => map$8(rows, (row) => InventoryItem.make({
93969
+ bindings: [...map$8(fromIterable$8(matchAll(/traefik\.http\.services\.[^=,]+\.loadbalancer\.server\.port=([0-9]+)/gu)(row.Labels ?? "")), (match) => ({
93970
+ address: "container",
93971
+ port: getOrElse$1(parse$3(match[1] ?? ""), () => 0),
93972
+ protocol: "tcp"
93973
+ })), ...map$8(fromIterable$8(matchAll(/((?:[0-9.]+|\[::\])):([0-9]+)->[0-9]+\/(tcp|udp)/gu)(row.Ports)), (match) => ({
93974
+ address: `${match[1]}:${match[2]}`,
93975
+ port: getOrElse$1(parse$3(match[2] ?? ""), () => 0),
93976
+ protocol: match$1(match[3] === "udp", {
93977
+ onFalse: () => "tcp",
93978
+ onTrue: () => "udp"
93979
+ })
93980
+ }))],
93981
+ detail: row.Status,
93982
+ id: `${worker}:docker:${row.ID}`,
93983
+ kind: "container",
93984
+ links: dedupe(map$8(fromIterable$8(matchAll(/Host\(`([^`]+)`\)/gu)(row.Labels ?? "")), (match) => `https://${match[1]}`)),
93985
+ name: row.Names,
93986
+ state: row.State,
93987
+ url: "",
93988
+ worker
93989
+ }))));
93990
+ const linux = succeed$5({
93991
+ processes: pipe(processes, provideService(FileSystem, fs), mapError$2((cause) => DeployError.make({
93992
+ cause,
93993
+ message: cause.message
93994
+ }))),
93995
+ sources: [
93996
+ collect("User services", units(false)),
93997
+ collect("System services", units(true)),
93998
+ collect("Docker", docker),
93999
+ collect("Listening ports", flatMap$2(command("ss", ["-H", "-lntup"]), (text) => portItems(getSomes(map$8(split$2(trim(text), "\n"), socketLine)), worker, http, {
94000
+ cwd: (processId) => option$1(fs.readLink(`/proc/${processId}/cwd`)),
94001
+ unit: (processId) => map$5(option$1(fs.readFileString(`/proc/${processId}/cgroup`)), (cgroup) => socketUnit(getOrElse$1(cgroup, () => "")))
94002
+ })))
94003
+ ]
94004
+ });
94005
+ const darwin = gen(function* () {
94006
+ const launchd = yield* all$1({
94007
+ agents: result$1(map$5(command("launchctl", ["list"]), launchAgents)),
94008
+ table: result$1(command("env", [
94009
+ "LC_ALL=C",
94010
+ "ps",
94011
+ "-axww",
94012
+ "-o",
94013
+ "pid=,ppid=,rss=,time=,lstart=,args="
94014
+ ]))
94015
+ }, { concurrency: "unbounded" });
94016
+ const time = yield* currentTimeMillis;
94017
+ const total = sumAll(flatMap$5(cpus(), (cpu) => values(cpu.times)));
94018
+ const records = map$10(launchd.table, (text) => {
94019
+ const agents = fromEntries(getSomes(map$8(getOrElse(launchd.agents, () => []), (agent) => map$11(agent.pid, (processId) => [`${processId}`, agent.label]))));
94020
+ return filter$3(launchdProcesses(text, agents), (record) => record.process.pid === pid || record.unit !== agents[`${pid}`]);
94021
+ });
94022
+ const owned = getOrElse(records, () => []);
94023
+ return {
94024
+ processes: map$5(fromResult(records), (found) => ({
94025
+ records: found,
94026
+ time,
94027
+ total
94028
+ })),
94029
+ sources: [collect("Launch agents", map$5(fromResult(launchd.agents), (agents) => map$8(agents, (agent) => InventoryItem.make({
94030
+ detail: "user · launch agent",
94031
+ ...match$1(isNone(agent.pid) && agent.status !== 0, {
94032
+ onFalse: () => ({}),
94033
+ onTrue: () => ({ failure: { reason: exitFailure(agent.status) } })
94034
+ }),
94035
+ id: `${worker}:user:${agent.label}`,
94036
+ kind: "service",
94037
+ name: agent.label,
94038
+ scope: "user",
94039
+ state: match$8(agent.pid, {
94040
+ onNone: () => match$1(agent.status === 0, {
94041
+ onFalse: () => "failed · failed",
94042
+ onTrue: () => "inactive · dead"
94043
+ }),
94044
+ onSome: () => "active · running"
94045
+ }),
94046
+ url: "",
94047
+ worker
94048
+ })))), collect("Listening ports", flatMap$2(command("lsof", [
94049
+ "-nP",
94050
+ "+c0",
94051
+ "-iTCP",
94052
+ "-sTCP:LISTEN",
94053
+ "-iUDP",
94054
+ "-F",
94055
+ "pctPnT"
94056
+ ]), (text) => portItems(lsofSockets(text), worker, http, {
94057
+ cwd: fnUntraced(function* (processId) {
94058
+ const lines = split$2(getOrElse$1(yield* option$1(command("lsof", [
94059
+ "-nP",
94060
+ "-a",
94061
+ "-p",
94062
+ processId,
94063
+ "-d",
94064
+ "cwd",
94065
+ "-Fn"
94066
+ ])), () => ""), "\n");
94067
+ return map$11(findFirst(lines, startsWith("n")), slice$1(1));
94068
+ }),
94069
+ unit: (processId) => succeed$5(getOrElse$1(map$11(findFirst(owned, (record) => `${record.process.pid}` === processId), (record) => record.unit), () => ""))
94070
+ })))]
94071
+ };
94072
+ });
93684
94073
  return Inventory.of({
93685
94074
  run: fnUntraced(function* (input) {
94075
+ if (platform === "darwin") return yield* DeployError.make({ message: `${input.name} is not started by a timer` });
93686
94076
  const timers = yield* pipe(command("systemctl", [
93687
94077
  ...match$1(input.scope === "system", {
93688
94078
  onFalse: () => ["--user"],
@@ -93717,37 +94107,12 @@ var Inventory = class Inventory extends Service$1()("@deslop/deploy/services/inv
93717
94107
  });
93718
94108
  })),
93719
94109
  snapshot: scoped(gen(function* () {
94110
+ const machine = yield* match$1(platform === "darwin", {
94111
+ onFalse: () => linux,
94112
+ onTrue: () => darwin
94113
+ });
93720
94114
  const sources = yield* all$1([
93721
- collect("User services", units(false)),
93722
- collect("System services", units(true)),
93723
- collect("Docker", pipe(command("docker", [
93724
- "ps",
93725
- "--all",
93726
- "--format",
93727
- "{{json .}}"
93728
- ]), flatMap$2((text) => forEach$1(filter$3(split$2(text, "\n"), isNonEmpty$1), (line) => decodeEffect(fromJsonString(Container))(line), { concurrency: 1 })), map$5((rows) => map$8(rows, (row) => InventoryItem.make({
93729
- bindings: [...map$8(fromIterable$8(matchAll(/traefik\.http\.services\.[^=,]+\.loadbalancer\.server\.port=([0-9]+)/gu)(row.Labels ?? "")), (match) => ({
93730
- address: "container",
93731
- port: getOrElse(parse$3(match[1] ?? ""), () => 0),
93732
- protocol: "tcp"
93733
- })), ...map$8(fromIterable$8(matchAll(/((?:[0-9.]+|\[::\])):([0-9]+)->[0-9]+\/(tcp|udp)/gu)(row.Ports)), (match) => ({
93734
- address: `${match[1]}:${match[2]}`,
93735
- port: getOrElse(parse$3(match[2] ?? ""), () => 0),
93736
- protocol: match$1(match[3] === "udp", {
93737
- onFalse: () => "tcp",
93738
- onTrue: () => "udp"
93739
- })
93740
- }))],
93741
- detail: row.Status,
93742
- id: `${worker}:docker:${row.ID}`,
93743
- kind: "container",
93744
- links: dedupe(map$8(fromIterable$8(matchAll(/Host\(`([^`]+)`\)/gu)(row.Labels ?? "")), (match) => `https://${match[1]}`)),
93745
- name: row.Names,
93746
- state: row.State,
93747
- url: "",
93748
- worker
93749
- }))))),
93750
- collect("Listening ports", flatMap$2(command("ss", ["-H", "-lntup"]), (text) => portItems(text, worker, fs, http))),
94115
+ ...machine.sources,
93751
94116
  collect("Tailnet", pipe(command("tailscale", ["status", "--json"]), flatMap$2(decodeEffect(fromJsonString(Tailnet))), map$5((status) => map$8([...toArray$1(fromUndefinedOr(status.Self)), ...values(status.Peer ?? {})], (peer) => InventoryItem.make({
93752
94117
  detail: `${peer.OS} · ${join$2(peer.TailscaleIPs, ", ")}`,
93753
94118
  hostname: replace(/\.$/u, "")(peer.DNSName),
@@ -93785,7 +94150,7 @@ var Inventory = class Inventory extends Service$1()("@deslop/deploy/services/inv
93785
94150
  worker
93786
94151
  }))))))
93787
94152
  ], { concurrency: "unbounded" });
93788
- const collected = yield* pipe(processes, provideService(FileSystem, fs), flatMap$2((current) => modify$1(processState, (previous) => {
94153
+ const collected = yield* pipe(machine.processes, flatMap$2((current) => modify$1(processState, (previous) => {
93789
94154
  const next = processReadings(current, getOrUndefined$1(previous));
93790
94155
  return [next.readings, some$1(next)];
93791
94156
  })), timeout$1("3 seconds"), match$2({
@@ -93838,7 +94203,7 @@ function cpuFields(fields) {
93838
94203
  return decodeSync(ArraySchema(FiniteFromString).check(isMinLength(5)))(take$3(drop$1(fields, 1), 8));
93839
94204
  }
93840
94205
  function counters(stat, uptime, time) {
93841
- const values = cpuFields(pipe(stat, split$2("\n"), head, getOrElse(() => ""), trim, split$2(/\s+/u)));
94206
+ const values = cpuFields(pipe(stat, split$2("\n"), head, getOrElse$1(() => ""), trim, split$2(/\s+/u)));
93842
94207
  return {
93843
94208
  cores: pipe(stat, split$2("\n"), filter$3((line) => isSome(match$3(/^cpu[0-9]+\s/u)(line))), map$8((line) => {
93844
94209
  const fields = split$2(trim(line), /\s+/u);
@@ -93869,46 +94234,90 @@ function coreUsages(current, seconds, old) {
93869
94234
  ...getSomes$1({ usage: cpuUsage(core, seconds, getOrUndefined$1(head(oldCores[core.id] ?? []))) })
93870
94235
  }));
93871
94236
  }
93872
- function sample(current, memory, disk, previous, load) {
93873
- const values = fromEntries(map$8(split$2(trim(memory), "\n"), (line) => {
93874
- const fields = split$2(line, /\s+/u);
93875
- return [fields[0], decodeSync(FiniteFromString)(fields[1] ?? "") * 1024];
94237
+ function cpuCounters(cpus, uptime, time) {
94238
+ const cores = map$8(cpus, (cpu, index) => ({
94239
+ id: `cpu${index}`,
94240
+ idle: cpu.times.idle,
94241
+ total: sumAll(values(cpu.times))
93876
94242
  }));
93877
- const disks = pipe(disk, trim, split$2("\n"), drop$1(1), filter$3(isNonEmpty$1), map$8((line) => {
94243
+ return {
94244
+ cores,
94245
+ cpuIdle: sumAll(map$8(cores, (core) => core.idle)),
94246
+ cpuTotal: sumAll(map$8(cores, (core) => core.total)),
94247
+ time,
94248
+ uptime
94249
+ };
94250
+ }
94251
+ function vmStatMemory(text, total) {
94252
+ const pages = fromEntries(getSomes(map$8(split$2(text, "\n"), (line) => map$11(match$3(/^"?([^":]+)"?:\s+([0-9]+)\.$/u)(trim(line)), (match) => [match[1] ?? "", match[2] ?? ""]))));
94253
+ const page = decodeSync(FiniteFromString)(getOrElse$1(map$11(match$3(/page size of ([0-9]+) bytes/u)(text), (match) => match[1] ?? ""), () => ""));
94254
+ function count(name) {
94255
+ return decodeSync(FiniteFromString)(pages[name] ?? "");
94256
+ }
94257
+ return {
94258
+ total,
94259
+ used: clamp((count("Anonymous pages") - count("Pages purgeable") + count("Pages wired down") + count("Pages occupied by compressor")) * page, {
94260
+ maximum: total,
94261
+ minimum: 0
94262
+ })
94263
+ };
94264
+ }
94265
+ function rootVolume(text) {
94266
+ return map$8(filter$3(drop$1(split$2(trim(text), "\n"), 1), isNonEmpty$1), (line) => {
93878
94267
  const fields = split$2(trim(line), /\s+/u);
94268
+ const size = decodeSync(FiniteFromString)(fields[1] ?? "") * 1024;
93879
94269
  return {
93880
- mount: fields[0],
93881
- total: decodeSync(FiniteFromString)(fields[1] ?? ""),
93882
- used: decodeSync(FiniteFromString)(fields[2] ?? "")
94270
+ mount: "/",
94271
+ total: size,
94272
+ used: size - decodeSync(FiniteFromString)(fields[3] ?? "") * 1024
93883
94273
  };
93884
- }));
94274
+ });
94275
+ }
94276
+ function reading(current, memory, disks, load, previous) {
93885
94277
  const used = reduce(disks, 0, (sum, entry) => sum + entry.used);
93886
94278
  const seconds = (current.time - (previous?.time ?? current.time)) / 1e3;
93887
94279
  const baseline = filter$5(fromUndefinedOr(previous), (old) => old.uptime < current.uptime);
93888
- const reading = {
94280
+ const value = {
93889
94281
  cores: coreUsages(current, seconds, getOrUndefined$1(baseline)),
93890
94282
  ...getSomes$1({ cpu: cpuUsage({
93891
94283
  idle: current.cpuIdle,
93892
94284
  total: current.cpuTotal
93893
- }, seconds, getOrUndefined$1(map$11(baseline, (value) => ({
93894
- idle: value.cpuIdle,
93895
- total: value.cpuTotal
94285
+ }, seconds, getOrUndefined$1(map$11(baseline, (old) => ({
94286
+ idle: old.cpuIdle,
94287
+ total: old.cpuTotal
93896
94288
  })))) }),
93897
94289
  disks,
93898
- load: decodeSync(ArraySchema(FiniteFromString))(take$3(filter$3(split$2(trim(load ?? ""), /\s+/u), isNonEmpty$1), 3)),
93899
- memoryTotal: values["MemTotal:"] ?? 0,
93900
- memoryUsed: (values["MemTotal:"] ?? 0) - (values["MemAvailable:"] ?? 0),
94290
+ load,
94291
+ memoryTotal: memory.total,
94292
+ memoryUsed: memory.used,
93901
94293
  time: current.time,
93902
94294
  uptime: current.uptime
93903
94295
  };
93904
94296
  return match$6(disks, {
93905
- onEmpty: () => reading,
94297
+ onEmpty: () => value,
93906
94298
  onNonEmpty: () => ({
93907
- ...reading,
94299
+ ...value,
93908
94300
  storageUsed: used
93909
94301
  })
93910
94302
  });
93911
94303
  }
94304
+ function sample(current, memory, disk, previous, load) {
94305
+ const values = fromEntries(map$8(split$2(trim(memory), "\n"), (line) => {
94306
+ const fields = split$2(line, /\s+/u);
94307
+ return [fields[0], decodeSync(FiniteFromString)(fields[1] ?? "") * 1024];
94308
+ }));
94309
+ return reading(current, {
94310
+ total: values["MemTotal:"] ?? 0,
94311
+ used: (values["MemTotal:"] ?? 0) - (values["MemAvailable:"] ?? 0)
94312
+ }, pipe(disk, trim, split$2("\n"), drop$1(1), filter$3(isNonEmpty$1), map$8((line) => {
94313
+ const fields = split$2(trim(line), /\s+/u);
94314
+ return {
94315
+ mount: fields[0],
94316
+ total: decodeSync(FiniteFromString)(fields[1] ?? ""),
94317
+ used: decodeSync(FiniteFromString)(fields[2] ?? "")
94318
+ };
94319
+ })), decodeSync(ArraySchema(FiniteFromString))(take$3(filter$3(split$2(trim(load ?? ""), /\s+/u), isNonEmpty$1), 3)), previous);
94320
+ }
93912
94321
  function resolution(minutes) {
93913
94322
  return minutes * 1e3;
93914
94323
  }
@@ -93945,7 +94354,7 @@ function merge(bucket) {
93945
94354
  onSome: (app) => app.cpu
93946
94355
  })) }),
93947
94356
  id,
93948
- memory: round(getOrElse(mean(reported, (_point, index) => match$8(appAt(index, id), {
94357
+ memory: round(getOrElse$1(mean(reported, (_point, index) => match$8(appAt(index, id), {
93949
94358
  onNone: () => 0,
93950
94359
  onSome: (app) => app.memory
93951
94360
  })), () => 0), 0)
@@ -93956,19 +94365,19 @@ function merge(bucket) {
93956
94365
  ...getSomes$1({ usage: mean(bucket, (point) => getOrUndefined$1(findFirst(point.cores ?? [], (entry) => entry.id === core.id))?.usage) })
93957
94366
  })),
93958
94367
  ...getSomes$1({ cpu: mean(bucket, (point) => point.cpu) }),
93959
- memoryUsed: getOrElse(mean(bucket, (point) => point.memoryUsed), () => last.memoryUsed),
94368
+ memoryUsed: getOrElse$1(mean(bucket, (point) => point.memoryUsed), () => last.memoryUsed),
93960
94369
  ...getSomes$1({ storageUsed: mean(bucket, (point) => point.storageUsed) }),
93961
94370
  since: bucket[0].since ?? bucket[0].time
93962
94371
  };
93963
94372
  }
93964
94373
  function compact(samples, now) {
93965
94374
  return pipe(samples, filter$3((value) => value.time >= now - 6048e5), groupBy((value) => {
93966
- const tier = getOrElse(findLast(TIERS, (candidate, index) => now - (Math.floor(value.time / candidate.every) + 1) * candidate.every >= (TIERS[index - 1]?.keep ?? 0)), () => TIERS[0]);
94375
+ const tier = getOrElse$1(findLast(TIERS, (candidate, index) => now - (Math.floor(value.time / candidate.every) + 1) * candidate.every >= (TIERS[index - 1]?.keep ?? 0)), () => TIERS[0]);
93967
94376
  return `${tier.every}:${Math.floor(value.time / tier.every)}`;
93968
94377
  }), values, map$8(merge), sort(mapInput(Number$6, (value) => value.time)));
93969
94378
  }
93970
94379
  function usedStorage(point) {
93971
- return getOrElse(fromUndefinedOr(point.storageUsed), () => reduce(point.disks, 0, (sum, disk) => sum + disk.used));
94380
+ return getOrElse$1(fromUndefinedOr(point.storageUsed), () => reduce(point.disks, 0, (sum, disk) => sum + disk.used));
93972
94381
  }
93973
94382
  function history(samples, minutes, now) {
93974
94383
  const window = chartWindow(minutes, now);
@@ -93989,10 +94398,10 @@ function history(samples, minutes, now) {
93989
94398
  function bandName(id, labels) {
93990
94399
  if (id === "other") return "Low impact";
93991
94400
  if (id === "system") return "System";
93992
- return getOrElse(get$11(labels, id), () => replaceAll(/^service:[a-z]+:(?:deslop-)?|\.service$/gu, "")(replace(/^container:/u, "container ")(id)));
94401
+ return getOrElse$1(get$11(labels, id), () => replaceAll(/^service:[a-z]+:(?:deslop-)?|\.service$/gu, "")(replace(/^container:/u, "container ")(id)));
93993
94402
  }
93994
94403
  function appCgroup(path, siblings) {
93995
- const name = getOrElse(last(split$2(path, "/")), () => "");
94404
+ const name = getOrElse$1(last(split$2(path, "/")), () => "");
93996
94405
  if (isSome(match$3(/^docker-[a-f0-9]{12,64}\.scope$/u)(name))) return true;
93997
94406
  if (endsWith(".service")(name)) return isNone(match$3(/^user@[0-9]+\.service$/u)(name));
93998
94407
  return exists(match$3(/\/user@[0-9]+\.service\/app\.slice\/app-([^/]+)\.slice$/u)(path), (match) => contains(siblings, `${match[1]}.service`));
@@ -94034,11 +94443,29 @@ function appShares(current, previous) {
94034
94443
  // src/services/metrics/service.ts
94035
94444
  const CGROUP = "/sys/fs/cgroup";
94036
94445
  const HOURLY_FILE_PREFIX = "metrics-";
94446
+ function counted(read) {
94447
+ return pipe(try_({
94448
+ catch: (cause) => DeployError.make({
94449
+ cause,
94450
+ message: "The machine counters are unreadable."
94451
+ }),
94452
+ try: read
94453
+ }), flatMap$2(decodeEffect(Counters)));
94454
+ }
94455
+ function sampled(read) {
94456
+ return pipe(try_({
94457
+ catch: (cause) => DeployError.make({
94458
+ cause,
94459
+ message: "The machine sample is unreadable."
94460
+ }),
94461
+ try: read
94462
+ }), flatMap$2(decodeEffect(Sample)));
94463
+ }
94037
94464
  var Metrics = class Metrics extends Service$1()("@deslop/deploy/services/metrics/service/Metrics") {
94038
94465
  static layer = effect(Metrics, gen(function* () {
94039
94466
  const fs = yield* FileSystem;
94040
- const worker = trim(yield* fs.readFileString("/proc/sys/kernel/hostname"));
94041
- const cpuModel = pipe(yield* fs.readFileString("/proc/cpuinfo"), match$3(/model name\s*:\s*([^\n]+)/u), map$11((match) => trim(match[1] ?? "")), getOrElse(() => ""));
94467
+ const worker = hostname();
94468
+ const cpuModel = getOrElse$1(map$11(head(cpus()), (cpu) => trim(cpu.model)), () => "");
94042
94469
  const base = yield* KeyValueStore;
94043
94470
  const store = toSchemaStore(base, ArraySchema(Sample));
94044
94471
  const now = yield* currentTimeMillis;
@@ -94080,64 +94507,73 @@ var Metrics = class Metrics extends Service$1()("@deslop/deploy/services/metrics
94080
94507
  })), { concurrency: 8 });
94081
94508
  return fromEntries(getSomes(readings));
94082
94509
  });
94083
- const refreshStorage = pipe(scoped(execute("df", [
94084
- "-B1",
94085
- "--output=target,size,used",
94086
- "-x",
94087
- "tmpfs",
94088
- "-x",
94089
- "devtmpfs",
94090
- "-x",
94091
- "overlay",
94092
- "-x",
94093
- "squashfs",
94094
- "-x",
94095
- "efivarfs"
94096
- ])), flatMap$2((text) => set$1(storage, text)), ignore$1({
94510
+ const refreshStorage = pipe(scoped(match$1(platform === "darwin", {
94511
+ onFalse: () => execute("df", [
94512
+ "-B1",
94513
+ "--output=target,size,used",
94514
+ "-x",
94515
+ "tmpfs",
94516
+ "-x",
94517
+ "devtmpfs",
94518
+ "-x",
94519
+ "overlay",
94520
+ "-x",
94521
+ "squashfs",
94522
+ "-x",
94523
+ "efivarfs"
94524
+ ]),
94525
+ onTrue: () => execute("df", ["-k", "/"])
94526
+ })), flatMap$2((text) => set$1(storage, text)), ignore$1({
94097
94527
  log: "Warn",
94098
94528
  message: "The disk sizes were not read"
94099
94529
  }));
94100
- const collect = pipe(gen(function* () {
94101
- const time = yield* currentTimeMillis;
94530
+ const linux = fnUntraced(function* (time, disks, old) {
94102
94531
  const files = yield* all$1({
94103
94532
  load: fs.readFileString("/proc/loadavg"),
94104
94533
  memory: fs.readFileString("/proc/meminfo"),
94105
94534
  stat: fs.readFileString("/proc/stat"),
94106
94535
  uptime: fs.readFileString("/proc/uptime")
94107
94536
  }, { concurrency: "unbounded" });
94108
- const current = yield* pipe(try_({
94109
- catch: (cause) => DeployError.make({
94110
- cause,
94111
- message: "The machine counters are unreadable."
94112
- }),
94113
- try: () => counters(files.stat, files.uptime, time)
94114
- }), flatMap$2(decodeEffect(Counters)));
94115
- const old = getOrUndefined$1(yield* get$1(previous));
94537
+ const current = yield* counted(() => counters(files.stat, files.uptime, time));
94116
94538
  const shares = yield* pipe(apps, timeout$1("1 second"), flatMap$2((usage) => modify$1(lastApps, (last) => {
94117
- const reading = {
94539
+ const cgroups = {
94118
94540
  cgroups: usage,
94119
94541
  time,
94120
94542
  total: current.cpuTotal
94121
94543
  };
94122
- return [appShares(reading, getOrUndefined$1(last)), some$1(reading)];
94544
+ return [appShares(cgroups, getOrUndefined$1(last)), some$1(cgroups)];
94123
94545
  })), asSome, catchTag("TimeoutError", () => succeedNone));
94124
- const disks = yield* get$1(storage);
94125
- const value = yield* pipe(try_({
94126
- catch: (cause) => DeployError.make({
94127
- cause,
94128
- message: "The machine sample is unreadable."
94129
- }),
94130
- try: () => ({
94546
+ return {
94547
+ current,
94548
+ value: yield* sampled(() => ({
94131
94549
  ...sample(current, files.memory, disks, old, files.load),
94132
94550
  ...match$8(shares, {
94133
94551
  onNone: () => ({}),
94134
94552
  onSome: (usage) => ({ apps: usage })
94135
94553
  })
94136
- })
94137
- }), flatMap$2(decodeEffect(Sample)));
94138
- yield* set$1(previous, some$1(current));
94554
+ }))
94555
+ };
94556
+ });
94557
+ const darwin = fnUntraced(function* (time, disks, old) {
94558
+ const memory = yield* scoped(execute("vm_stat", []));
94559
+ const uptime = toSeconds(nanos(yield* monotonicTimeNanos));
94560
+ const current = yield* counted(() => cpuCounters(cpus(), uptime, time));
94561
+ return {
94562
+ current,
94563
+ value: yield* sampled(() => reading(current, vmStatMemory(memory, totalmem()), rootVolume(disks), loadavg(), old))
94564
+ };
94565
+ });
94566
+ const collect = pipe(gen(function* () {
94567
+ const time = yield* currentTimeMillis;
94568
+ const old = getOrUndefined$1(yield* get$1(previous));
94569
+ const disks = yield* get$1(storage);
94570
+ const measured = yield* match$1(platform === "darwin", {
94571
+ onFalse: () => linux(time, disks, old),
94572
+ onTrue: () => darwin(time, disks, old)
94573
+ });
94574
+ yield* set$1(previous, some$1(measured.current));
94139
94575
  const before = yield* get$1(state);
94140
- const samples = compact([...before, value], time);
94576
+ const samples = compact([...before, measured.value], time);
94141
94577
  yield* set$1(state, samples);
94142
94578
  const retained = fromIterable$3(map$8(samples, (entry) => entry.time));
94143
94579
  const hour = Math.floor(time / 36e5);
@@ -94175,7 +94611,7 @@ var Metrics = class Metrics extends Service$1()("@deslop/deploy/services/metrics
94175
94611
  cpuModel,
94176
94612
  error: join$2(filter$3([yield* get$1(collectError), yield* get$1(persistError)], isNonEmpty$1), "\n"),
94177
94613
  samples: history(samples, query.minutes, time),
94178
- stale: time - getOrElse(map$11(last(samples), (value) => value.time), () => 0) > 9e4,
94614
+ stale: time - getOrElse$1(map$11(last(samples), (value) => value.time), () => 0) > 9e4,
94179
94615
  time,
94180
94616
  worker
94181
94617
  });
@@ -94388,7 +94824,7 @@ const Tools = make$37(make$38("list_apps", {
94388
94824
  parameters: HistoryToolInput,
94389
94825
  success: ResourceHistory
94390
94826
  }).annotate(Readonly, true), make$38("expose_port", {
94391
- description: "Use to give a local port an HTTPS URL on the tailnet or the public internet; publicAccess=true is required for public, and target names another configured worker. Returns {url}; it adds no authentication and starts no application.",
94827
+ description: "Use to give a local port an HTTPS URL on the tailnet or, from a Linux worker, the public internet; publicAccess=true is required for public, and target names another configured worker. Returns {url}; it adds no authentication and starts no application.",
94392
94828
  failure: DeployError,
94393
94829
  parameters: ExposeRequest,
94394
94830
  success: Struct({ url: String$6 })
@@ -94397,7 +94833,7 @@ const Tools = make$37(make$38("list_apps", {
94397
94833
  failure: DeployError,
94398
94834
  parameters: HideRequest
94399
94835
  }).annotate(Destructive, true), make$38("run_job", {
94400
- description: "Use to run a scheduled job now, by the name list_apps shows. Pass worker when both machines run the same job; returns {started: true}.",
94836
+ description: "Use to run a scheduled job now, by the name list_apps shows. Pass worker when several machines run the same job; returns {started: true}.",
94401
94837
  failure: DeployError,
94402
94838
  parameters: RunJobInput,
94403
94839
  success: Struct({ started: Literal(true) })
@@ -94411,7 +94847,7 @@ function workerNames(snapshot) {
94411
94847
  return dedupe([...snapshot.workers ?? [], ...map$8(snapshot.items, (item) => item.worker)]);
94412
94848
  }
94413
94849
  function sourceWorker(source, workers, local) {
94414
- return getOrElse(findFirst(workers, (worker) => sourceBelongsToWorker(source, worker)), () => local);
94850
+ return getOrElse$1(findFirst(workers, (worker) => sourceBelongsToWorker(source, worker)), () => local);
94415
94851
  }
94416
94852
  function errorsOf(sources, workers, worker) {
94417
94853
  const local = match$8(head(workers), {