@deslop/deploy 0.1.1376 → 0.1.1465

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,8 +1,8 @@
1
1
  #!/usr/bin/env -S node --max-old-space-size=512 --report-on-fatalerror
2
2
  import { createRequire } from "node:module";
3
- import { arch, cwd, execArgv, execPath, pid, platform } from "node:process";
3
+ import { cwd, execArgv, execPath, platform } from "node:process";
4
4
  import * as OS from "node:os";
5
- import { cpus, hostname, loadavg, totalmem, userInfo } from "node:os";
5
+ import { userInfo } from "node:os";
6
6
  import * as NodeChildProcess from "node:child_process";
7
7
  import { Duplex, PassThrough, Readable, Transform, finished, pipeline } from "node:stream";
8
8
  import { Buffer as Buffer$1 } from "node:buffer";
@@ -657,7 +657,7 @@ function assignProperties(self, source) {
657
657
  * @category guards
658
658
  * @since 2.0.0
659
659
  */
660
- function isString$2(input) {
660
+ function isString$1(input) {
661
661
  return typeof input === "string";
662
662
  }
663
663
  /**
@@ -823,7 +823,7 @@ function isSymbol(input) {
823
823
  * @since 4.0.0
824
824
  */
825
825
  function isPropertyKey(u) {
826
- return isString$2(u) || isNumber(u) || isSymbol(u);
826
+ return isString$1(u) || isNumber(u) || isSymbol(u);
827
827
  }
828
828
  /**
829
829
  * Checks whether a value is a `function`.
@@ -1297,7 +1297,7 @@ function isError(input) {
1297
1297
  * @since 2.0.0
1298
1298
  */
1299
1299
  function isIterable(input) {
1300
- return hasProperty(input, Symbol.iterator) || isString$2(input);
1300
+ return hasProperty(input, Symbol.iterator) || isString$1(input);
1301
1301
  }
1302
1302
  /**
1303
1303
  * Creates a predicate that returns `true` if either predicate is `true`.
@@ -3411,7 +3411,7 @@ const String$11 = isStrictEquivalent;
3411
3411
  * @category combinators
3412
3412
  * @since 4.0.0
3413
3413
  */
3414
- function Tuple$1(elements) {
3414
+ function Tuple$2(elements) {
3415
3415
  return make$91((self, that) => {
3416
3416
  if (self.length !== that.length) return false;
3417
3417
  for (let i = 0; i < self.length; i++) if (!elements[i](self[i], that[i])) return false;
@@ -3840,6 +3840,46 @@ const combine$3 = /*#__PURE__*/ dual(2, (self, that) => make$90((a1, a2) => {
3840
3840
  */
3841
3841
  const mapInput = /*#__PURE__*/ dual(2, (self, f) => make$90((b1, b2) => self(f(b1), f(b2))));
3842
3842
  /**
3843
+ * Creates an `Order` for a tuple type based on orders for each element.
3844
+ *
3845
+ * **When to use**
3846
+ *
3847
+ * Use when you need fixed-length tuple ordering with per-position orders.
3848
+ *
3849
+ * **Details**
3850
+ *
3851
+ * Compares tuples element-by-element using the corresponding order and stops at
3852
+ * the first non-zero comparison result. Tuples must have the same length as the
3853
+ * order collection, and the result is `0` only if all elements are equal.
3854
+ *
3855
+ * **Example** (Ordering tuples)
3856
+ *
3857
+ * ```ts import.meta.vitest
3858
+ * import { Order } from "effect"
3859
+ *
3860
+ * const tupleOrder = Order.Tuple([Order.Number, Order.String])
3861
+ *
3862
+ * tupleOrder([1, "a"], [2, "b"]) // => -1
3863
+ * tupleOrder([1, "b"], [1, "a"]) // => 1
3864
+ * tupleOrder([1, "a"], [1, "a"]) // => 0
3865
+ * ```
3866
+ *
3867
+ * @see {@link Array} to compare arrays with length consideration
3868
+ * @stability stable
3869
+ * @category combinators
3870
+ * @since 4.0.0
3871
+ */
3872
+ function Tuple$1(elements) {
3873
+ return make$90((self, that) => {
3874
+ const len = elements.length;
3875
+ for (let i = 0; i < len; i++) {
3876
+ const o = elements[i](self[i], that[i]);
3877
+ if (o !== 0) return o;
3878
+ }
3879
+ return 0;
3880
+ });
3881
+ }
3882
+ /**
3843
3883
  * Checks whether one value is strictly less than another according to the given order.
3844
3884
  *
3845
3885
  * **When to use**
@@ -4062,7 +4102,7 @@ const max$3 = (O) => dual(2, (self, that) => self === that || O(self, that) > -1
4062
4102
  * @category comparisons
4063
4103
  * @since 2.0.0
4064
4104
  */
4065
- const clamp$2 = (O) => dual(2, (self, options) => min$4(O)(options.maximum, max$3(O)(options.minimum, self)));
4105
+ const clamp$1 = (O) => dual(2, (self, options) => min$4(O)(options.maximum, max$3(O)(options.minimum, self)));
4066
4106
  // ../../node_modules/.pnpm/effect@4.1.5/node_modules/effect/dist/Option.js
4067
4107
  /**
4068
4108
  * Creates an `Option` representing the absence of a value.
@@ -6041,40 +6081,6 @@ const map$12 = /*#__PURE__*/ dual(2, (self, f) => isSuccess$1(self) ? succeed$10
6041
6081
  */
6042
6082
  const match$7 = /*#__PURE__*/ dual(2, (self, { onFailure, onSuccess }) => isFailure$1(self) ? onFailure(self.failure) : onSuccess(self.success));
6043
6083
  /**
6044
- * Extracts the success value, or computes a fallback from the error.
6045
- *
6046
- * **When to use**
6047
- *
6048
- * Use when you need the success value from a `Result`, with a fallback computed
6049
- * from the failure value.
6050
- *
6051
- * **Details**
6052
- *
6053
- * - `Success<A>` returns the inner value
6054
- * - `Failure<E>` applies `onFailure` to the error and returns the result
6055
- * - The return type is `A | A2` (union of both branches)
6056
- *
6057
- * **Example** (Providing a fallback)
6058
- *
6059
- * ```ts import.meta.vitest
6060
- * import { Result } from "effect"
6061
- *
6062
- * Result.getOrElse(Result.succeed(1), () => 0) // => 1
6063
- *
6064
- * Result.getOrElse(Result.fail("err"), () => 0) // => 0
6065
- * ```
6066
- *
6067
- * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks
6068
- * @see {@link getOrThrow} to throw on failure
6069
- * @see {@link match} to map both branches
6070
- * @see {@link orElse} to recover with another Result instead of unwrapping
6071
- *
6072
- * @stability stable
6073
- * @category getters
6074
- * @since 2.0.0
6075
- */
6076
- const getOrElse = /*#__PURE__*/ dual(2, (self, onFailure) => isFailure$1(self) ? onFailure(self.failure) : self.success);
6077
- /**
6078
6084
  * Extracts the success value, or returns `undefined` on failure.
6079
6085
  *
6080
6086
  * **When to use**
@@ -6104,7 +6110,7 @@ const getOrElse = /*#__PURE__*/ dual(2, (self, onFailure) => isFailure$1(self) ?
6104
6110
  * @category getters
6105
6111
  * @since 2.0.0
6106
6112
  */
6107
- const getOrUndefined = /*#__PURE__*/ getOrElse(constUndefined);
6113
+ const getOrUndefined = /*#__PURE__*/ (/* @__PURE__ */ dual(2, (self, onFailure) => isFailure$1(self) ? onFailure(self.failure) : self.success))(constUndefined);
6108
6114
  /**
6109
6115
  * Extracts the success value or throws the raw failure value `E`.
6110
6116
  *
@@ -6293,7 +6299,7 @@ const make$88 = (...elements) => elements;
6293
6299
  * @category instances
6294
6300
  * @since 4.0.0
6295
6301
  */
6296
- const makeEquivalence$4 = Tuple$1;
6302
+ const makeEquivalence$4 = Tuple$2;
6297
6303
  // ../../node_modules/.pnpm/effect@4.1.5/node_modules/effect/dist/Iterable.js
6298
6304
  /**
6299
6305
  * Gets the first element of an `Iterable` without returning an `Option`.
@@ -6873,7 +6879,7 @@ const makeEquivalence$3 = (equivalence) => {
6873
6879
  * @category constructors
6874
6880
  * @since 4.0.0
6875
6881
  */
6876
- const Array$2 = globalThis.Array;
6882
+ const Array$1 = globalThis.Array;
6877
6883
  /**
6878
6884
  * Creates a `NonEmptyArray` of length `n` where element `i` is computed by `f(i)`.
6879
6885
  *
@@ -6904,7 +6910,7 @@ const Array$2 = globalThis.Array;
6904
6910
  */
6905
6911
  const makeBy = /*#__PURE__*/ dual(2, (n, f) => {
6906
6912
  const max = normalizeNonEmpty(n);
6907
- const out = new Array$2(max);
6913
+ const out = new Array$1(max);
6908
6914
  for (let i = 0; i < max; i++) out[i] = f(i);
6909
6915
  return out;
6910
6916
  });
@@ -6936,7 +6942,7 @@ const makeBy = /*#__PURE__*/ dual(2, (n, f) => {
6936
6942
  * @category constructors
6937
6943
  * @since 2.0.0
6938
6944
  */
6939
- const fromIterable$8 = (collection) => Array$2.isArray(collection) ? collection : Array$2.from(collection);
6945
+ const fromIterable$8 = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection);
6940
6946
  /**
6941
6947
  * Normalizes a value that is either a single element or an array into an array.
6942
6948
  *
@@ -6967,7 +6973,7 @@ const fromIterable$8 = (collection) => Array$2.isArray(collection) ? collection
6967
6973
  * @category constructors
6968
6974
  * @since 3.3.0
6969
6975
  */
6970
- const ensure = (self) => Array$2.isArray(self) ? self : [self];
6976
+ const ensure = (self) => Array$1.isArray(self) ? self : [self];
6971
6977
  /**
6972
6978
  * Pattern-matches on an array, handling empty and non-empty cases separately.
6973
6979
  *
@@ -7117,7 +7123,7 @@ const scan$1 = /*#__PURE__*/ dual(3, (self, b, f) => {
7117
7123
  }
7118
7124
  return out;
7119
7125
  });
7120
- Array$2.isArray;
7126
+ Array$1.isArray;
7121
7127
  /**
7122
7128
  * Checks whether a mutable `Array` is empty, narrowing the type to `[]`.
7123
7129
  *
@@ -7666,7 +7672,7 @@ const findLast = /*#__PURE__*/ dual(2, (self, f) => {
7666
7672
  * @category transforming
7667
7673
  * @since 2.0.0
7668
7674
  */
7669
- const reverse = (self) => Array$2.from(self).reverse();
7675
+ const reverse = (self) => Array$1.from(self).reverse();
7670
7676
  /**
7671
7677
  * Sorts an array by the given `Order`, returning a new array.
7672
7678
  *
@@ -7695,7 +7701,7 @@ const reverse = (self) => Array$2.from(self).reverse();
7695
7701
  * @since 2.0.0
7696
7702
  */
7697
7703
  const sort = /*#__PURE__*/ dual(2, (self, O) => {
7698
- const out = Array$2.from(self);
7704
+ const out = Array$1.from(self);
7699
7705
  out.sort(O);
7700
7706
  return out;
7701
7707
  });
@@ -7727,7 +7733,7 @@ const sort = /*#__PURE__*/ dual(2, (self, O) => {
7727
7733
  * @category sorting
7728
7734
  * @since 2.0.0
7729
7735
  */
7730
- const sortWith = /*#__PURE__*/ dual(3, (self, f, order) => Array$2.from(self).map((a) => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _));
7736
+ const sortWith = /*#__PURE__*/ dual(3, (self, f, order) => Array$1.from(self).map((a) => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _));
7731
7737
  /**
7732
7738
  * Combines elements from two iterables pairwise using a function. If the
7733
7739
  * iterables differ in length, extra elements are discarded.
@@ -9339,25 +9345,6 @@ const min$2 = /*#__PURE__*/ min$4(Order$7);
9339
9345
  */
9340
9346
  const max$1 = /*#__PURE__*/ max$3(Order$7);
9341
9347
  /**
9342
- * Returns a `Duration` constrained between a minimum and maximum value.
9343
- *
9344
- * **Example** (Clamping durations to a range)
9345
- *
9346
- * ```ts import.meta.vitest
9347
- * import { Duration } from "effect"
9348
- *
9349
- * Duration.clamp(Duration.seconds(10), {
9350
- * minimum: Duration.seconds(2),
9351
- * maximum: Duration.seconds(5)
9352
- * }) // => Duration.seconds(5)
9353
- * ```
9354
- *
9355
- * @stability stable
9356
- * @category ordering
9357
- * @since 2.0.0
9358
- */
9359
- const clamp$1 = /*#__PURE__*/ clamp$2(Order$7);
9360
- /**
9361
9348
  * Divides a `Duration` by a number using fallback rules instead of returning
9362
9349
  * an `Option`.
9363
9350
  *
@@ -11954,7 +11941,7 @@ const catchTags$1 = /*#__PURE__*/ dual((args) => isEffect$1(args[0]), (self, cas
11954
11941
  let keys;
11955
11942
  return catchFilter$1(self, (e) => {
11956
11943
  keys ??= Object.keys(cases);
11957
- return hasProperty(e, "_tag") && isString$2(e["_tag"]) && keys.includes(e["_tag"]) ? succeed$10(e) : fail$12(e);
11944
+ return hasProperty(e, "_tag") && isString$1(e["_tag"]) && keys.includes(e["_tag"]) ? succeed$10(e) : fail$12(e);
11958
11945
  }, (e) => cases[e["_tag"]](e), orElse);
11959
11946
  });
11960
11947
  /** @internal */
@@ -11973,8 +11960,6 @@ const mapBoth = /*#__PURE__*/ dual(2, (self, options) => matchCauseEffect$1(self
11973
11960
  /** @internal */
11974
11961
  const orDie$3 = (self) => catch_$3(self, die$5);
11975
11962
  /** @internal */
11976
- const eventually$1 = (self) => catch_$3(self, (_) => flatMap$5(yieldNow$1, () => eventually$1(self)));
11977
- /** @internal */
11978
11963
  const ignoreCauseLogger = (log) => log === "Unhandled" ? (...message) => withFiber$1((fiber) => {
11979
11964
  const level = fiber.getRef(UnhandledLogLevel);
11980
11965
  return level === void 0 ? void_$4 : logWithLevel(level)(...message);
@@ -17138,8 +17123,6 @@ const mapEpochMillis$1 = /*#__PURE__*/ dual(2, (self, f) => {
17138
17123
  return self._tag === "Utc" ? makeUtc(millis) : makeZonedProto(millis, self.zone);
17139
17124
  });
17140
17125
  /** @internal */
17141
- const addDuration$1 = /*#__PURE__*/ dual(2, (self, duration) => mapEpochMillis$1(self, (millis) => millis + toMillis(fromInputUnsafe$1(duration))));
17142
- /** @internal */
17143
17126
  const subtractDuration$1 = /*#__PURE__*/ dual(2, (self, duration) => mapEpochMillis$1(self, (millis) => millis - toMillis(fromInputUnsafe$1(duration))));
17144
17127
  /** @internal */
17145
17128
  const formatIso$1 = (self) => toDateUtc$1(self).toISOString();
@@ -17258,7 +17241,7 @@ const isGreaterThanOrEqualTo$2 = /*#__PURE__*/ isGreaterThanOrEqualTo$4(Order$5)
17258
17241
  * @category math
17259
17242
  * @since 2.0.0
17260
17243
  */
17261
- const clamp = /*#__PURE__*/ clamp$2(Order$5);
17244
+ const clamp = /*#__PURE__*/ clamp$1(Order$5);
17262
17245
  /**
17263
17246
  * Returns the minimum between two `number`s.
17264
17247
  *
@@ -17446,23 +17429,6 @@ const round = /*#__PURE__*/ dual(2, (self, precision) => {
17446
17429
  */
17447
17430
  const String$9 = globalThis.String;
17448
17431
  /**
17449
- * Checks whether a value is a `string`.
17450
- *
17451
- * **Example** (Checking for strings)
17452
- *
17453
- * ```ts import.meta.vitest
17454
- * import { String } from "effect"
17455
- *
17456
- * String.isString("a") // => true
17457
- * String.isString(1) // => false
17458
- * ```
17459
- *
17460
- * @stability stable
17461
- * @category guards
17462
- * @since 2.0.0
17463
- */
17464
- const isString$1 = isString$2;
17465
- /**
17466
17432
  * Provides an `Order` instance for comparing strings using lexicographic
17467
17433
  * ordering.
17468
17434
  *
@@ -17686,7 +17652,7 @@ const length = (self) => self.length;
17686
17652
  * @category transforming
17687
17653
  * @since 2.0.0
17688
17654
  */
17689
- const split$1 = /*#__PURE__*/ dual(2, (self, separator) => {
17655
+ const split = /*#__PURE__*/ dual(2, (self, separator) => {
17690
17656
  const out = self.split(separator);
17691
17657
  return isArrayNonEmpty$1(out) ? out : [self];
17692
17658
  });
@@ -21148,41 +21114,6 @@ const tapError$3 = tapError$4;
21148
21114
  */
21149
21115
  const tapCause = tapCause$1;
21150
21116
  /**
21151
- * Retries an effect until it succeeds, discarding failures.
21152
- *
21153
- * **Details**
21154
- *
21155
- * Yields between attempts so other fibers can run.
21156
- *
21157
- * **Example** (Retrying until success)
21158
- *
21159
- * ```ts import.meta.vitest
21160
- * import { Effect } from "effect"
21161
- * const output: Array<unknown> = []
21162
- *
21163
- * let attempts = 0
21164
- *
21165
- * const flaky = Effect.gen(function*() {
21166
- * attempts++
21167
- * yield* Effect.sync(() => { output.push(`Attempt ${attempts}`) })
21168
- * if (attempts < 3) {
21169
- * return yield* Effect.fail("Not ready")
21170
- * }
21171
- * return "Ready"
21172
- * })
21173
- *
21174
- * const program = Effect.eventually(flaky)
21175
- *
21176
- * void output.push(await Effect.runPromise(program))
21177
- * output // => ["Attempt 1", "Attempt 2", "Attempt 3", "Ready"]
21178
- * ```
21179
- *
21180
- * @stability stable
21181
- * @category repetition
21182
- * @since 2.0.0
21183
- */
21184
- const eventually = eventually$1;
21185
- /**
21186
21117
  * Retries typed failures from an effect according to a retry policy.
21187
21118
  *
21188
21119
  * **When to use**
@@ -31982,44 +31913,6 @@ const toEpochSeconds = toEpochSeconds$1;
31982
31913
  */
31983
31914
  const mapEpochMillis = mapEpochMillis$1;
31984
31915
  /**
31985
- * Adds the given `Duration` to a `DateTime`.
31986
- *
31987
- * **When to use**
31988
- *
31989
- * Use to move a `DateTime` by an elapsed duration such as minutes, seconds, or
31990
- * milliseconds.
31991
- *
31992
- * **Details**
31993
- *
31994
- * The duration is converted to milliseconds and added to the epoch
31995
- * milliseconds. Zoned values keep their original time zone.
31996
- *
31997
- * **Gotchas**
31998
- *
31999
- * This is elapsed-time arithmetic, not calendar-aware local date arithmetic.
32000
- * Use `add` when adding days, weeks, months, or years should account for the
32001
- * date/time zone rules.
32002
- *
32003
- * **Example** (Adding durations)
32004
- *
32005
- * ```ts import.meta.vitest
32006
- * import { DateTime } from "effect"
32007
- *
32008
- * // add 5 minutes
32009
- * DateTime.makeUnsafe(0).pipe(
32010
- * DateTime.addDuration("5 minutes")
32011
- * ) // => DateTime.makeUnsafe(300000)
32012
- * ```
32013
- *
32014
- * @see {@link add} for calendar-aware date/time part arithmetic
32015
- * @see {@link subtractDuration} for subtracting an elapsed duration
32016
- *
32017
- * @stability stable
32018
- * @category math
32019
- * @since 3.6.0
32020
- */
32021
- const addDuration = addDuration$1;
32022
- /**
32023
31916
  * Subtracts the given `Duration` from a `DateTime`.
32024
31917
  *
32025
31918
  * **Example** (Subtracting durations)
@@ -33429,7 +33322,7 @@ const Proto$19 = {
33429
33322
  return this.toString();
33430
33323
  },
33431
33324
  toString() {
33432
- return `<redacted${isString$2(this.label) ? ":" + this.label : ""}>`;
33325
+ return `<redacted${isString$1(this.label) ? ":" + this.label : ""}>`;
33433
33326
  },
33434
33327
  [symbol$3]() {
33435
33328
  return hash(redactedRegistry.get(this));
@@ -35477,39 +35370,6 @@ function joinKeyValue(options) {
35477
35370
  const keyValueSeparator = options?.keyValueSeparator ?? "=";
35478
35371
  return transform$2((input) => Object.entries(input).map(([key, value]) => `${key}${keyValueSeparator}${value}`).join(separator));
35479
35372
  }
35480
- /**
35481
- * Splits a string into an array of strings by a separator.
35482
- *
35483
- * **When to use**
35484
- *
35485
- * Use when you need a schema getter to split a present encoded string
35486
- * containing a delimited list, such as CSV values.
35487
- *
35488
- * **Details**
35489
- *
35490
- * The getter is pure and never fails. It splits by `separator` (default `,`).
35491
- * An empty string produces an empty array, not `[""]`.
35492
- *
35493
- * **Example** (Splitting a comma-separated string)
35494
- *
35495
- * ```ts import.meta.vitest
35496
- * import { Effect, Option, SchemaGetter } from "effect"
35497
- *
35498
- * const splitComma = SchemaGetter.split<string>()
35499
- * const result = Effect.runSync(SchemaGetter.run(splitComma, Option.some("a,b,c"), {}))
35500
- * result // => Option.some(["a", "b", "c"])
35501
- * ```
35502
- *
35503
- * @see {@link splitKeyValue} when values are key-value pairs
35504
- *
35505
- * @stability stable
35506
- * @category splitting
35507
- * @since 4.0.0
35508
- */
35509
- function split(options) {
35510
- const separator = options?.separator ?? ",";
35511
- return transform$2((input) => input === "" ? [] : input.split(separator));
35512
- }
35513
35373
  function encodeWithWellFormedString(encode) {
35514
35374
  return transformEffect$1((input, options) => typeof input === "string" && !isWellFormed(input) ? fail$7(new InvalidValue$1({ expected: "a well-formed Unicode string" }, input, options)) : succeed$5(encode(input)));
35515
35375
  }
@@ -36136,52 +35996,6 @@ function optionFromOptionalKey() {
36136
35996
  });
36137
35997
  }
36138
35998
  /**
36139
- * Decodes optional values into `Option<T>` and encodes `Option.none()` back to
36140
- * an omitted optional value.
36141
- *
36142
- * **When to use**
36143
- *
36144
- * Use when you need a schema transformation to convert optional (possibly
36145
- * `undefined`) values to `Option`.
36146
- *
36147
- * **Details**
36148
- *
36149
- * Decoding maps an absent or `undefined` value to `Some(None)` and a present
36150
- * value to `Some(Some(v))`. Encoding maps `Some(None)` to `None` to omit the
36151
- * value, and maps `Some(Some(v))` to `Some(v)`. This uses
36152
- * `transformOptional` under the hood and filters out `undefined` on decode.
36153
- *
36154
- * **Example** (Converting an optional value to an Option)
36155
- *
36156
- * ```ts import.meta.vitest
36157
- * import { Option, Schema, SchemaTransformation } from "effect"
36158
- *
36159
- * const schema = Schema.Struct({
36160
- * age: Schema.optional(Schema.Number).pipe(
36161
- * Schema.decodeTo(
36162
- * Schema.Option(Schema.Number),
36163
- * SchemaTransformation.optionFromOptional()
36164
- * )
36165
- * )
36166
- * })
36167
- * Schema.decodeSync(schema)({ age: undefined }).age // => Option.none()
36168
- * ```
36169
- *
36170
- * @see {@link optionFromOptionalKey}
36171
- * @see {@link optionFromUndefinedOr}
36172
- * @see {@link transformOptional}
36173
- *
36174
- * @stability stable
36175
- * @category transforming
36176
- * @since 4.0.0
36177
- */
36178
- function optionFromOptional() {
36179
- return transformOptional({
36180
- decode: (ot) => ot.pipe(filter$5(isNotUndefined), some$1),
36181
- encode: flatten$6
36182
- });
36183
- }
36184
- /**
36185
35999
  * Decodes a Base64-encoded `string` into a `Uint8Array` and encodes a
36186
36000
  * `Uint8Array` back to a Base64 string.
36187
36001
  *
@@ -36822,7 +36636,7 @@ const String$7 = class extends ASTNodeImpl {
36822
36636
  _tag = "String";
36823
36637
  /** @internal */
36824
36638
  getParser() {
36825
- return fromRefinement(this, isString$2);
36639
+ return fromRefinement(this, isString$1);
36826
36640
  }
36827
36641
  /** @internal */
36828
36642
  matchPart(s, options) {
@@ -44422,23 +44236,6 @@ function OptionFromOptionalKey(schema) {
44422
44236
  return optionalKey(schema).pipe(decodeTo(Option(toType(schema)), optionFromOptionalKey()));
44423
44237
  }
44424
44238
  /**
44425
- * Decodes an optional or `undefined` value `A` to a required `Option<A>`
44426
- * value.
44427
- *
44428
- * **Details**
44429
- *
44430
- * Decoding maps a missing key or a present `undefined` value to `None`, and
44431
- * maps all other values to `Some`. Encoding maps `None` to a missing key and
44432
- * maps `Some` to its value.
44433
- *
44434
- * @stability stable
44435
- * @category schemas
44436
- * @since 4.0.0
44437
- */
44438
- function OptionFromOptional(schema) {
44439
- return optional$8(schema).pipe(decodeTo(Option(toType(schema)), optionFromOptional()));
44440
- }
44441
- /**
44442
44239
  * Schema for `Redacted` values, which hide their contents from inspection.
44443
44240
  *
44444
44241
  * **Details**
@@ -55914,7 +55711,7 @@ const PortSchema = /*#__PURE__*/ Int$1.check(/*#__PURE__*/ isBetween({
55914
55711
  minimum: 1,
55915
55712
  maximum: 65535
55916
55713
  }));
55917
- const isPath = (u) => isString$2(u) || globalThis.Array.isArray(u);
55714
+ const isPath = (u) => isString$1(u) || globalThis.Array.isArray(u);
55918
55715
  /**
55919
55716
  * Creates a config that always succeeds with the given value, ignoring the
55920
55717
  * provider entirely.
@@ -55975,16 +55772,6 @@ function succeed$1(value) {
55975
55772
  function String$5(name) {
55976
55773
  return schema$1(String$6, name);
55977
55774
  }
55978
- function Array$1(value, pathOrOptions, options) {
55979
- const hasPath = isPath(pathOrOptions);
55980
- const resolvedOptions = hasPath ? options : pathOrOptions;
55981
- const array = ArraySchema(value);
55982
- const separator = resolvedOptions?.separator ?? ",";
55983
- return schema$1(Union$2([String$6.pipe(decodeTo(toCodecStringTree(array), {
55984
- decode: split(resolvedOptions),
55985
- encode: compose(passthrough$1({ strict: false }), transform$2((input) => input.join(separator)))
55986
- })), array]), hasPath ? pathOrOptions : void 0);
55987
- }
55988
55775
  function Record(key, value, pathOrOptions, options) {
55989
55776
  const hasPath = isPath(pathOrOptions);
55990
55777
  const record = Record$1(key, value);
@@ -57159,7 +56946,7 @@ const is = is$1;
57159
56946
  * @category guards
57160
56947
  * @since 4.0.0
57161
56948
  */
57162
- const string = isString$2;
56949
+ const string = isString$1;
57163
56950
  /**
57164
56951
  * Matches values of type `number`.
57165
56952
  *
@@ -57979,19 +57766,6 @@ var PendingInvalidation = class extends (/*#__PURE__*/ Service$1()("effect/react
57979
57766
  */
57980
57767
  const stream$3 = /*#__PURE__*/ dual(2, (effect, keys) => Reactivity.use((r) => r.query(keys, effect)).pipe(map$7(fromQueue), unwrap$4));
57981
57768
  /**
57982
- * Invalidates the supplied keys through the `Reactivity` service.
57983
- *
57984
- * **Details**
57985
- *
57986
- * Registered queries for matching keys are rerun immediately, or collected until
57987
- * the enclosing reactivity batch completes.
57988
- *
57989
- * @stability unstable
57990
- * @category accessors
57991
- * @since 4.0.0
57992
- */
57993
- const invalidate = (keys) => Reactivity.use((r) => r.invalidate(keys));
57994
- /**
57995
57769
  * The default layer that provides an in-memory `Reactivity` service.
57996
57770
  *
57997
57771
  * @stability unstable
@@ -73780,7 +73554,7 @@ function decodeJsonRpcRaw(decoded, batches, controlMessages) {
73780
73554
  function decodeJsonRpcMessage(decoded, controlMessages) {
73781
73555
  if (Object.hasOwn(decoded, "method")) {
73782
73556
  const request = decoded;
73783
- if (controlMessages && isNullish(request.id) && isString$2(request.method) && request.method.startsWith("@effect/rpc/")) {
73557
+ if (controlMessages && isNullish(request.id) && isString$1(request.method) && request.method.startsWith("@effect/rpc/")) {
73784
73558
  const tag = request.method.slice(12);
73785
73559
  const requestId = request.params?.requestId;
73786
73560
  return requestId !== void 0 ? {
@@ -77194,19 +76968,19 @@ var ProtocolError = class ProtocolError extends (/*#__PURE__*/ TaggedError$1("Pr
77194
76968
  }
77195
76969
  static fromFeature(error) {
77196
76970
  if (hasProperty(error, "_tag")) {
77197
- if (error._tag === "PromptNotFound" && hasProperty(error, "name") && isString$2(error.name)) return new ProtocolError({
76971
+ if (error._tag === "PromptNotFound" && hasProperty(error, "name") && isString$1(error.name)) return new ProtocolError({
77198
76972
  code: INVALID_PARAMS_ERROR_CODE,
77199
76973
  message: `Prompt '${error.name}' not found`
77200
76974
  });
77201
- if (error._tag === "SkillNotFound" && hasProperty(error, "uri") && isString$2(error.uri)) return new ProtocolError({
76975
+ if (error._tag === "SkillNotFound" && hasProperty(error, "uri") && isString$1(error.uri)) return new ProtocolError({
77202
76976
  code: INVALID_PARAMS_ERROR_CODE,
77203
76977
  message: `Skill '${error.uri}' not found`
77204
76978
  });
77205
- if (error._tag === "DirectoryNotFound" && hasProperty(error, "uri") && isString$2(error.uri)) return new ProtocolError({
76979
+ if (error._tag === "DirectoryNotFound" && hasProperty(error, "uri") && isString$1(error.uri)) return new ProtocolError({
77206
76980
  code: INVALID_PARAMS_ERROR_CODE,
77207
76981
  message: `Directory '${error.uri}' not found`
77208
76982
  });
77209
- if (error._tag === "ResourceNotFound" && hasProperty(error, "uri") && isString$2(error.uri)) return new ProtocolError({
76983
+ if (error._tag === "ResourceNotFound" && hasProperty(error, "uri") && isString$1(error.uri)) return new ProtocolError({
77210
76984
  code: LEGACY_RESOURCE_NOT_FOUND_ERROR_CODE,
77211
76985
  message: `Resource '${error.uri}' not found`
77212
76986
  });
@@ -80045,7 +79819,7 @@ const AdapterRpcs$1 = /*#__PURE__*/ ClientRpcs$1.omit("ping");
80045
79819
  const isToolOutputSchema$1 = (schema) => {
80046
79820
  if (schema?.type !== "object") return false;
80047
79821
  const isPropertiesSupported = schema.properties === void 0 || isReadonlyObject(schema.properties) && Object.values(schema.properties).every(isReadonlyObject);
80048
- const isRequiredDefined = schema.required === void 0 || Array.isArray(schema.required) && schema.required.every(isString$2);
79822
+ const isRequiredDefined = schema.required === void 0 || Array.isArray(schema.required) && schema.required.every(isString$1);
80049
79823
  return isPropertiesSupported && isRequiredDefined;
80050
79824
  };
80051
79825
  const profileFromInitialize = (initialize) => ({
@@ -80270,7 +80044,7 @@ const AdapterRpcs = /*#__PURE__*/ ClientRpcs.omit("ping");
80270
80044
  const isToolOutputSchema = (schema) => {
80271
80045
  if (schema?.type !== "object") return false;
80272
80046
  const isPropertiesSupported = schema.properties === void 0 || isReadonlyObject(schema.properties) && Object.values(schema.properties).every(isReadonlyObject);
80273
- const isRequiredDefined = schema.required === void 0 || Array.isArray(schema.required) && schema.required.every(isString$2);
80047
+ const isRequiredDefined = schema.required === void 0 || Array.isArray(schema.required) && schema.required.every(isString$1);
80274
80048
  return isPropertiesSupported && isRequiredDefined;
80275
80049
  };
80276
80050
  const unsupported$1 = (operation, reason) => new McpReverseOperationUnsupported({
@@ -99477,7 +99251,7 @@ function recheckUser(current, found) {
99477
99251
  var CurrentUser = class extends Service$1()("@deslop/runtime/shared/auth/CurrentUser") {};
99478
99252
  var RpcAuth = class extends Service()("@deslop/runtime/shared/auth/RpcAuth", { error: AuthError }) {};
99479
99253
  const Origin = String$6.check(makeFilter((value) => exists(getSuccess(fromString(value)), (url) => contains$1(["http:", "https:"], url.protocol) && url.username === "" && url.password === "" && url.hash === ""), { expected: "an HTTP(S) URL without credentials or a fragment" })).check(makeFilter((value) => exists(getSuccess(fromString(value)), (url) => url.pathname === "/" && url.search === ""), { expected: "an HTTP(S) origin without a path or query" }));
99480
- const SecureOrigin = Origin.check(makeFilter((value) => exists(getSuccess(fromString(value)), (url) => url.protocol === "https:" || contains$1([
99254
+ Origin.check(makeFilter((value) => exists(getSuccess(fromString(value)), (url) => url.protocol === "https:" || contains$1([
99481
99255
  "localhost",
99482
99256
  "127.0.0.1",
99483
99257
  "[::1]"
@@ -99705,12 +99479,7 @@ const publicAccess = [
99705
99479
  callers: ["member"],
99706
99480
  surface: `tool ${name}`
99707
99481
  })),
99708
- ...map$10([
99709
- "metrics.watch",
99710
- "metrics.history",
99711
- "inventory.watch",
99712
- "inventory.snapshot"
99713
- ], (name) => ({
99482
+ ...map$10(["metrics.watch", "inventory.watch"], (name) => ({
99714
99483
  app: "deploy",
99715
99484
  callers: ["member"],
99716
99485
  surface: `rpc ${name}`
@@ -99720,11 +99489,6 @@ const publicAccess = [
99720
99489
  callers: ["member"],
99721
99490
  surface: `tool ${name}`
99722
99491
  })),
99723
- {
99724
- app: "deploy",
99725
- callers: ["admin"],
99726
- surface: "rpc exposures.remove"
99727
- },
99728
99492
  ...map$10([
99729
99493
  "ai-proxy.key",
99730
99494
  "ai-proxy.setKey",
@@ -99948,7 +99712,7 @@ function mcpRequest(origin, caller, method, params) {
99948
99712
  return pipe(post(`${origin}/mcp`), setHeaders$1({
99949
99713
  accept: "application/json, text/event-stream",
99950
99714
  "mcp-method": method,
99951
- "mcp-name": pipe(params["name"], liftPredicate(isString$2), getOrElse$1(constant$1(""))),
99715
+ "mcp-name": pipe(params["name"], liftPredicate(isString$1), getOrElse$1(constant$1(""))),
99952
99716
  "mcp-protocol-version": "2026-07-28",
99953
99717
  "x-probe-caller": caller
99954
99718
  }), bodyJson({
@@ -100141,7 +99905,7 @@ const layerRpcStream = succeed$6(RpcStream, RpcStream.of((effect, options) => {
100141
99905
  if (!isStreamSchema(options.rpc.successSchema)) return effect;
100142
99906
  return andThen(annotateCurrentSpan("rpc.stream", true), effect);
100143
99907
  }));
100144
- const layerRpcStreamClient = layerClient(RpcStream, (options) => gen(function* () {
99908
+ layerClient(RpcStream, (options) => gen(function* () {
100145
99909
  if (isStreamSchema(options.rpc.successSchema)) yield* annotateCurrentSpan("rpc.stream", true);
100146
99910
  return yield* options.next(options.request);
100147
99911
  }));
@@ -100885,12 +100649,12 @@ const crossSiteGuard = make$32((app) => gen(function* () {
100885
100649
  const canonical = new URL(yield* String$5("APP_URL")).hostname;
100886
100650
  if (!exists(liftThrowable(() => new URL(`http://${host}`))(), (url) => url.hostname === canonical || isSome(match$2(LOOPBACK)(url.hostname)))) return empty({ status: 403 });
100887
100651
  }
100888
- if (exists(origin, (value) => !exists(liftThrowable(() => new URL(value).host)(), (originHost) => originHost === host)) && request.headers["sec-fetch-site"] !== "same-origin" && !contains$1(OTLP, headNonEmpty(split$1(request.url, "?")))) return empty({ status: 403 });
100652
+ if (exists(origin, (value) => !exists(liftThrowable(() => new URL(value).host)(), (originHost) => originHost === host)) && request.headers["sec-fetch-site"] !== "same-origin" && !contains$1(OTLP, headNonEmpty(split(request.url, "?")))) return empty({ status: 403 });
100889
100653
  return yield* app;
100890
100654
  }));
100891
100655
  const serverMiddleware = make$32((app) => clientAddress(crossSiteGuard(app)));
100892
100656
  const layerServerProtocol = mergeAll$2(layerSchemaBinary(), succeed$6(MaxBodySize, mebibytes(10)), effect(TracerDisabledWhen$1, map$7(TracerDisabledWhen$1, (previous) => (request) => {
100893
- const path = headNonEmpty(split$1(request.url, "?"));
100657
+ const path = headNonEmpty(split(request.url, "?"));
100894
100658
  return previous(request) || path === "/api/rpc" && toLowerCase(request.headers["upgrade"] ?? "") === "websocket" || startsWith("/assets/")(path) || contains$1([
100895
100659
  "/icon",
100896
100660
  "/favicon.ico",
@@ -101449,7 +101213,7 @@ const installAgent = fnUntraced(function* (name, command) {
101449
101213
  const installUpdateAgent = fnUntraced(function* (name, command) {
101450
101214
  const label = `deslop-${name}-update`;
101451
101215
  const target = `${domain()}/${label}`;
101452
- const file = yield* writeAgent(label, name, command, "<key>StartInterval</key><integer>900</integer>");
101216
+ const file = yield* writeAgent(label, name, command, "<key>StartInterval</key><integer>600</integer>");
101453
101217
  if (yield* loaded(target)) yield* bootout(file);
101454
101218
  yield* executeProcess("launchctl", [
101455
101219
  "bootstrap",
@@ -101469,7 +101233,7 @@ const uninstallAgents = fnUntraced(function* (name) {
101469
101233
  return `deslop-${name}.plist removed; application data preserved\n`;
101470
101234
  });
101471
101235
  function agentStatus(name) {
101472
- return map$7(executeProcess("launchctl", ["print", `${domain()}/deslop-${name}`]), (output) => `${pipe(output, split$1("\n"), filter$3((line) => isSome(match$2(/^\s*(?:path|state|pid|last exit code|last terminating signal) =/u)(line))), map$10(trim), join$3("\n"))}\n`);
101236
+ return map$7(executeProcess("launchctl", ["print", `${domain()}/deslop-${name}`]), (output) => `${pipe(output, split("\n"), filter$3((line) => isSome(match$2(/^\s*(?:path|state|pid|last exit code|last terminating signal) =/u)(line))), map$10(trim), join$3("\n"))}\n`);
101473
101237
  }
101474
101238
  function restartAgent(name) {
101475
101239
  return timeout(executeProcess("launchctl", [
@@ -101479,6 +101243,7 @@ function restartAgent(name) {
101479
101243
  ]), "30 seconds");
101480
101244
  }
101481
101245
  // ../../packages/runtime/src/server/services.ts
101246
+ const SLICE = "deslop.slice";
101482
101247
  function systemdArgument(value) {
101483
101248
  return `"${pipe(value, replaceAll("\\", "\\\\"), replaceAll("\"", "\\\""), replaceAll("%", "%%"), replaceAll("$", "$$$$"), replaceAll("\n", "\\n"), replaceAll("\r", "\\r"))}"`;
101484
101249
  }
@@ -101496,7 +101261,8 @@ const installService = fnUntraced(function* (name, command, options) {
101496
101261
  const directory = yield* unitDirectory;
101497
101262
  const unit = `deslop-${name}.service`;
101498
101263
  yield* fs.makeDirectory(directory, { recursive: true });
101499
- yield* fs.writeFileString(path.join(directory, unit), `[Unit]\nDescription=Deslop ${name}\nAfter=network-online.target\n\n[Service]\nType=simple\nEnvironment=NODE_ENV=production\nEnvironment=${systemdArgument(`PATH=${home}/.vite-plus/bin:/usr/local/bin:/usr/bin:/bin`)}\nEnvironmentFile=-${replaceAll("%", "%%")(`${home}/.deslop/${name}.env`)}\nExecStart=${pipe(command, map$10(systemdArgument), join$3(" "))}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`, { mode: 384 });
101264
+ yield* fs.writeFileString(path.join(directory, SLICE), "[Unit]\nDescription=Deslop apps\n\n[Slice]\nCPUWeight=1000\nMemoryLow=1G\n", { mode: 384 });
101265
+ yield* fs.writeFileString(path.join(directory, unit), `[Unit]\nDescription=Deslop ${name}\nAfter=network-online.target\n\n[Service]\nType=simple\nSlice=${SLICE}\nEnvironment=NODE_ENV=production\nEnvironment=${systemdArgument(`PATH=${home}/.vite-plus/bin:/usr/local/bin:/usr/bin:/bin`)}\nEnvironmentFile=-${replaceAll("%", "%%")(`${home}/.deslop/${name}.env`)}\nExecStart=${pipe(command, map$10(systemdArgument), join$3(" "))}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`, { mode: 384 });
101500
101266
  yield* systemctl("daemon-reload");
101501
101267
  yield* systemctl("enable", unit);
101502
101268
  yield* systemctl(match(options?.restart === false, {
@@ -101512,7 +101278,7 @@ const installUpdateService = fnUntraced(function* (name, command) {
101512
101278
  const directory = yield* unitDirectory;
101513
101279
  const unit = `deslop-${name}-update`;
101514
101280
  yield* fs.writeFileString(path.join(directory, `${unit}.service`), `[Unit]\nDescription=Update Deslop ${name}\n\n[Service]\nType=oneshot\nExecStart=${pipe(command, map$10(systemdArgument), join$3(" "))}\nUMask=0077\n`, { mode: 384 });
101515
- yield* fs.writeFileString(path.join(directory, `${unit}.timer`), `[Unit]\nDescription=Update Deslop ${name}\n\n[Timer]\nOnBootSec=5min\nOnUnitInactiveSec=15min\nRandomizedDelaySec=1min\n\n[Install]\nWantedBy=timers.target\n`, { mode: 384 });
101281
+ yield* fs.writeFileString(path.join(directory, `${unit}.timer`), `[Unit]\nDescription=Update Deslop ${name}\n\n[Timer]\nOnBootSec=5min\nOnUnitInactiveSec=10min\nRandomizedDelaySec=1min\n\n[Install]\nWantedBy=timers.target\n`, { mode: 384 });
101516
101282
  yield* systemctl("daemon-reload");
101517
101283
  yield* systemctl("enable", "--now", `${unit}.timer`);
101518
101284
  });
@@ -101722,7 +101488,7 @@ const updateRelease = fnUntraced(function* (name, url) {
101722
101488
  message: "An npm staging directory was left behind"
101723
101489
  }));
101724
101490
  yield* uninterruptible(promoteRelease(name, url, path.join(directory, "node_modules", "@deslop", name), some$1(linked)));
101725
- const kept = pipe([linked, ...yield* forEach$1(["current", "serving"], (link) => fs.readLink(path.join(root, link)), { concurrency: 1 })], map$10((target) => headNonEmpty(split$1(path.relative(releases, target), path.sep))), append$1(latest));
101491
+ const kept = pipe([linked, ...yield* forEach$1(["current", "serving"], (link) => fs.readLink(path.join(root, link)), { concurrency: 1 })], map$10((target) => headNonEmpty(split(path.relative(releases, target), path.sep))), append$1(latest));
101726
101492
  yield* pipe(yield* fs.readDirectory(releases), difference(kept), forEach$1((entry) => fs.remove(path.join(releases, entry), { recursive: true }), { concurrency: 1 }));
101727
101493
  return `Updated ${name} from ${running} to ${latest}\n`;
101728
101494
  });
@@ -101760,7 +101526,7 @@ const configProvider = fnUntraced(function* (given, defaultPort) {
101760
101526
  ...urls,
101761
101527
  PORT: port
101762
101528
  }), make$53((path) => {
101763
- if (some(path, (key) => isString$2(key) && contains$1([
101529
+ if (some(path, (key) => isString$1(key) && contains$1([
101764
101530
  "APP_URL",
101765
101531
  "AUTH_URL",
101766
101532
  "GATEWAY_URL",
@@ -102104,7 +101870,6 @@ const DurationFromSeconds = pipe(Finite, decodeTo(Duration, {
102104
101870
  encode: transform$2(toSeconds)
102105
101871
  }));
102106
101872
  // src/services/inventory/schema.ts
102107
- const WorkerId = brand("DeployWorkerId")(String$6);
102108
101873
  const ItemId = brand("DeployItemId")(String$6);
102109
101874
  const AppId = brand("DeployAppId")(String$6);
102110
101875
  const UnitId = brand("DeployUnitId")(String$6);
@@ -102118,11 +101883,6 @@ const ResidentMemoryFromKiB = pipe(FiniteFromString, decodeTo(Finite, {
102118
101883
  decode: transform$2((value) => value * 1024),
102119
101884
  encode: transform$2((value) => value / 1024)
102120
101885
  }));
102121
- const CpuTime = Struct$2({
102122
- 1: OptionFromOptional(FiniteFromString),
102123
- 2: FiniteFromString,
102124
- 3: FiniteFromString
102125
- });
102126
101886
  const TextFromEmpty = pipe(String$6, decodeTo(Option(String$6), {
102127
101887
  decode: transform$2((value) => liftPredicate(value, isNonEmpty$1)),
102128
101888
  encode: transform$2((value) => getOrElse$1(value, constant$1("")))
@@ -102192,8 +101952,7 @@ const InventoryFields = Struct$2({
102192
101952
  state: String$6,
102193
101953
  ui: pipe(OptionFromOptionalKey(Boolean$5), withConstructorDefault(succeedNone)),
102194
101954
  unit: pipe(OptionalTextFromEmpty, decodeTo(Option(UnitId)), withConstructorDefault(succeedNone)),
102195
- url: TextFromEmpty,
102196
- worker: WorkerId
101955
+ url: TextFromEmpty
102197
101956
  });
102198
101957
  const NonPortItem = Union$2([
102199
101958
  InventoryFields.mapFields((fields) => ({
@@ -102242,21 +102001,15 @@ const Snapshot = Struct$2({
102242
102001
  error: TextFromEmpty,
102243
102002
  name: String$6
102244
102003
  })),
102245
- time: DateTimeUtcFromFiniteMillis,
102246
- workers: ArraySchema(WorkerId)
102004
+ time: DateTimeUtcFromFiniteMillis
102247
102005
  });
102248
- const WorkerList = String$6.check(isPattern(/^[a-z\d](?:[a-z\d-]*[a-z\d])?(?:,[a-z\d](?:[a-z\d-]*[a-z\d])?)*$/u));
102249
- const Peer = Struct$2({
102006
+ const TailnetStatus = Struct$2({ Self: OptionFromOptionalKey(Struct$2({
102250
102007
  DNSName: String$6,
102251
102008
  HostName: String$6,
102252
102009
  OS: String$6,
102253
102010
  Online: Boolean$5,
102254
102011
  TailscaleIPs: ArraySchema(String$6)
102255
- });
102256
- const TailnetStatus = Struct$2({
102257
- Peer: OptionFromOptionalKey(Record$1(String$6, Peer)),
102258
- Self: OptionFromOptionalKey(Peer)
102259
- });
102012
+ })) });
102260
102013
  const Serve = Struct$2({
102261
102014
  AllowFunnel: OptionFromOptionalKey(Record$1(String$6, Boolean$5)),
102262
102015
  TCP: OptionFromOptionalKey(Record$1(String$6, Json)),
@@ -102264,26 +102017,17 @@ const Serve = Struct$2({
102264
102017
  });
102265
102018
  const RunRequest = Struct$2({
102266
102019
  name: UnitId,
102267
- scope: Literals(["system", "user"]),
102268
- worker: WorkerId
102020
+ scope: Literals(["system", "user"])
102269
102021
  });
102270
- const RunJobInput = Struct$2({
102271
- job: JobName.annotate({ description: "A scheduled job name as list_apps shows it." }),
102272
- worker: OptionFromOptionalKey(WorkerId.annotate({ description: "The worker running the job, when several do." }))
102273
- });
102274
- const InventoryCursor = fromJsonString(Tuple([
102275
- WorkerId,
102276
- Literals([
102277
- "apps",
102278
- "exposures",
102279
- "jobs"
102280
- ]),
102281
- ItemId
102282
- ]));
102022
+ const RunJobInput = Struct$2({ id: ItemId.annotate({ description: "A scheduled job’s id as list_apps shows it." }) });
102023
+ const InventoryCursor = fromJsonString(Tuple([Literals([
102024
+ "apps",
102025
+ "exposures",
102026
+ "jobs"
102027
+ ]), ItemId]));
102283
102028
  const InventoryQuery = Struct$2({
102284
102029
  app: OptionFromOptionalKey(String$6.annotate({ description: "A substring of an app or unit name; returns that app's process tree." })),
102285
- failing: OptionFromOptionalKey(Boolean$5.annotate({ description: "Only failed or warning items." })),
102286
- worker: OptionFromOptionalKey(WorkerId.annotate({ description: "A configured worker name." }))
102030
+ failing: OptionFromOptionalKey(Boolean$5.annotate({ description: "Only failed or warning items." }))
102287
102031
  });
102288
102032
  const ProcessSummary = Struct$2({
102289
102033
  children: OptionFromOptionalKey(ArraySchema(suspend$2(() => ProcessSummary))),
@@ -102318,14 +102062,12 @@ const HttpsExposure = Struct$2({
102318
102062
  port: OptionFromOptionalKey(Int$1),
102319
102063
  url: String$6
102320
102064
  });
102321
- const WorkerInventory = Struct$2({
102065
+ const AppList = Struct$2({
102322
102066
  apps: ArraySchema(ManagedApp),
102323
102067
  errors: OptionFromOptionalKey(ArraySchema(String$6)),
102324
102068
  exposures: OptionFromOptionalKey(ArraySchema(HttpsExposure)),
102325
- jobs: OptionFromOptionalKey(ArraySchema(Job)),
102326
- worker: WorkerId
102069
+ jobs: OptionFromOptionalKey(ArraySchema(Job))
102327
102070
  });
102328
- ArraySchema(WorkerInventory);
102329
102071
  const Timer = Struct$2({
102330
102072
  activates: OptionFromNullOr(UnitId),
102331
102073
  next: OptionFromNullOr(pipe(Finite, decodeTo(DateTimeUtc, {
@@ -102370,22 +102112,8 @@ const ExposeInput = Struct$2({
102370
102112
  ]),
102371
102113
  publicAccess: Boolean$5
102372
102114
  });
102373
- const ExposeRequest = Struct$2({
102374
- ...ExposeInput.fields,
102375
- worker: WorkerId
102376
- });
102377
- const HideRequest = Struct$2({
102378
- name: ExposureName,
102379
- worker: WorkerId
102380
- });
102115
+ const HideRequest = Struct$2({ name: ExposureName });
102381
102116
  Union$2([AppId, Literals(["other", "system"])]);
102382
- Literals([
102383
- "idle",
102384
- "irq",
102385
- "nice",
102386
- "sys",
102387
- "user"
102388
- ]);
102389
102117
  const CpuCounters = TupleWithRest(Tuple([
102390
102118
  FiniteFromString,
102391
102119
  FiniteFromString,
@@ -102406,14 +102134,6 @@ const HistoryQuery = Struct$2({ minutes: pipe(HistoryMinutes, decodeTo(Duration,
102406
102134
  decode: transform$2(minutes),
102407
102135
  encode: transformEffect$1((range) => pipe(range, toMinutes, decodeUnknownEffect$1(HistoryMinutes)))
102408
102136
  })) });
102409
- const HistoryToolInput = Struct$2({
102410
- ...HistoryQuery.fields,
102411
- worker: OptionFromOptionalKey(WorkerId.annotate({ description: "A configured worker name." }))
102412
- });
102413
- const MetricsWatch = Struct$2({
102414
- ...HistoryQuery.fields,
102415
- worker: OptionFromOptionalKey(WorkerId)
102416
- });
102417
102137
  const MetricSeries = ArraySchema(OptionFromNullOr(Finite));
102418
102138
  const AppUsage = Struct$2({
102419
102139
  cpu: OptionFromOptionalKey(Finite),
@@ -102428,7 +102148,7 @@ const MachineNow = Struct$2({
102428
102148
  memoryGiB: Finite,
102429
102149
  memoryTotalGiB: Finite
102430
102150
  });
102431
- const WorkerHistory = Struct$2({
102151
+ const ResourceHistory = Struct$2({
102432
102152
  apps: ArraySchema(AppUsage),
102433
102153
  cpuPct: MetricSeries,
102434
102154
  diskPct: MetricSeries,
@@ -102437,10 +102157,8 @@ const WorkerHistory = Struct$2({
102437
102157
  memoryPct: MetricSeries,
102438
102158
  now: OptionFromOptionalKey(MachineNow),
102439
102159
  stale: OptionFromOptionalKey(Literal(true)),
102440
- stepSeconds: DurationFromSeconds,
102441
- worker: WorkerId
102160
+ stepSeconds: DurationFromSeconds
102442
102161
  });
102443
- ArraySchema(WorkerHistory);
102444
102162
  const Counters = Struct$2({
102445
102163
  cpuIdle: DurationFromFiniteMillis,
102446
102164
  cpuTotal: DurationFromFiniteMillis,
@@ -102493,21 +102211,17 @@ Struct$2({
102493
102211
  ]),
102494
102212
  apps: Option(ArraySchema(AppMeasurement))
102495
102213
  });
102496
- const Disk = Struct$2({
102497
- mount: String$6,
102498
- total: Finite,
102499
- used: Finite
102500
- });
102501
- const Platform = Literals(["linux", "darwin"]);
102502
102214
  const MachineHistory = Struct$2({
102503
- disks: ArraySchema(Disk),
102215
+ disks: ArraySchema(Struct$2({
102216
+ mount: String$6,
102217
+ total: Finite,
102218
+ used: Finite
102219
+ })),
102504
102220
  error: TextFromEmpty,
102505
102221
  load: ArraySchema(Finite),
102506
- platform: OptionFromOptionalKey(Platform),
102507
102222
  samples: ArraySchema(Sample.json),
102508
102223
  stale: Boolean$5,
102509
- time: DateTimeUtcFromFiniteMillis,
102510
- worker: WorkerId
102224
+ time: DateTimeUtcFromFiniteMillis
102511
102225
  });
102512
102226
  Literals([
102513
102227
  "apps",
@@ -102515,32 +102229,19 @@ Literals([
102515
102229
  "sample",
102516
102230
  "save"
102517
102231
  ]);
102518
- const VmStatPages = Struct$2({
102519
- "Anonymous pages": FiniteFromString,
102520
- "Pages occupied by compressor": FiniteFromString,
102521
- "Pages purgeable": FiniteFromString,
102522
- "Pages wired down": FiniteFromString
102523
- });
102524
102232
  // src/rpcs/contracts.ts
102525
102233
  var RpcContracts = class extends make$22(make$24("metrics.watch", {
102526
- error: Union$2([AuthError, DeployError]),
102527
- payload: MetricsWatch,
102528
- stream: true,
102529
- success: ArraySchema(MachineHistory)
102530
- }), make$24("metrics.history", {
102531
102234
  error: Union$2([AuthError, DeployError]),
102532
102235
  payload: HistoryQuery,
102236
+ stream: true,
102533
102237
  success: MachineHistory
102534
102238
  }), make$24("inventory.watch", {
102535
102239
  error: Union$2([AuthError, DeployError]),
102536
102240
  stream: true,
102537
102241
  success: Snapshot
102538
- }), make$24("inventory.snapshot", {
102539
- error: Union$2([AuthError, DeployError]),
102540
- success: Snapshot
102541
102242
  }), make$24("exposures.expose", {
102542
102243
  error: Union$2([AuthError, DeployError]),
102543
- payload: ExposeRequest,
102244
+ payload: ExposeInput,
102544
102245
  success: String$6
102545
102246
  }).middleware(RpcAdmin), make$24("exposures.hide", {
102546
102247
  error: Union$2([AuthError, DeployError]),
@@ -102548,703 +102249,42 @@ var RpcContracts = class extends make$22(make$24("metrics.watch", {
102548
102249
  }).middleware(RpcAdmin), make$24("inventory.run", {
102549
102250
  error: Union$2([AuthError, DeployError]),
102550
102251
  payload: RunRequest
102551
- }).middleware(RpcAdmin), make$24("exposures.apply", {
102552
- error: DeployError,
102553
- payload: ExposeInput,
102554
- success: String$6
102555
- }).middleware(RpcAdmin), make$24("exposures.remove", {
102556
- error: DeployError,
102557
- payload: Struct$2({ name: ExposureName })
102558
- }).middleware(RpcAdmin), make$24("inventory.start", {
102559
- error: DeployError,
102560
- payload: RunRequest.mapFields((fields) => omit(fields, ["worker"]))
102561
102252
  }).middleware(RpcAdmin)).middleware(RpcAuth) {};
102562
- // src/services/proxies/service.ts
102563
- const CADDY_ADMIN_PORT = 20219;
102564
- function caddyConfig(rows, storage) {
102565
- return `{\n\tadmin 127.0.0.1:${CADDY_ADMIN_PORT}\n\tgrace_period 10s\n\tpersist_config off\n\tstorage file_system {\n\t\troot ${encodeSync(fromJsonString(String$6))(storage)}\n\t}\n}\n\n${pipe(rows, filter$3((row) => row.kind === "public"), map$10((row) => `${row.hostname} {\n\tencode\n\treverse_proxy 127.0.0.1:${row.port}\n}\n`), join$3("\n"))}`;
102566
- }
102567
- function asDeployError$3(effect) {
102568
- return mapError$2(effect, (cause) => DeployError.make({
102569
- cause,
102570
- message: "Tailscale Serve could not be read or changed; check permissions and its status"
102571
- }));
102572
- }
102573
- var Proxies = class Proxies extends Service$1()("@deslop/deploy/services/proxies/service/Proxies") {
102574
- static layer = (directory) => effect(this, gen(function* () {
102575
- const fs = yield* FileSystem;
102576
- const spawner = yield* ChildProcessSpawner;
102577
- const path = yield* Path$1;
102578
- const http = yield* HttpClient;
102579
- yield* fs.makeDirectory(directory, {
102580
- mode: 448,
102581
- recursive: true
102582
- });
102583
- yield* flatMap$3(fs.readDirectory(directory), forEach$1((name) => match(startsWith("Caddyfile.")(name), {
102584
- onFalse: () => void_$2,
102585
- onTrue: () => fs.remove(path.join(directory, name), {
102586
- force: true,
102587
- recursive: true
102588
- })
102589
- }), { discard: true }));
102590
- const caddy = pipe((yield* ToolPath)("caddy"), provideService$2(FileSystem, fs), provideService$2(Path$1, path));
102591
- const configFile = path.join(directory, "Caddyfile");
102592
- function run(program, args) {
102593
- return pipe(executeProcess(program, args), provideService$2(ChildProcessSpawner, spawner), timeout(seconds(30)));
102594
- }
102595
- const written = fnUntraced(function* (rows) {
102596
- const binary = yield* caddy;
102597
- yield* fs.makeDirectory(path.join(directory, "caddy"), {
102598
- mode: 448,
102599
- recursive: true
102600
- });
102601
- const staged = yield* fs.makeTempFileScoped({
102602
- directory,
102603
- prefix: "Caddyfile."
102604
- });
102605
- yield* fs.chmod(staged, 384);
102606
- yield* fs.writeFileString(staged, caddyConfig(rows, path.join(directory, "caddy")));
102607
- yield* run(binary, [
102608
- "validate",
102609
- "--config",
102610
- staged,
102611
- "--adapter",
102612
- "caddyfile"
102613
- ]);
102614
- return {
102615
- binary,
102616
- staged
102617
- };
102618
- });
102619
- return Proxies.of({
102620
- apply: fn("Proxies.apply")(function* (rows) {
102621
- const config = yield* written(rows);
102622
- yield* fs.rename(config.staged, configFile);
102623
- const running = yield* pipe(run("systemctl", [
102624
- "--user",
102625
- "show",
102626
- "--property=MainPID",
102627
- "--value",
102628
- "deslop-deploy-caddy.service"
102629
- ]), map$7(trim), flatMap$3((pid) => match(pid === "0", {
102630
- onFalse: () => fs.readLink(`/proc/${pid}/exe`),
102631
- onTrue: () => succeed$5("")
102632
- })), option$1);
102633
- yield* pipe(installService("deploy-caddy", [
102634
- config.binary,
102635
- "run",
102636
- "--config",
102637
- configFile,
102638
- "--adapter",
102639
- "caddyfile"
102640
- ], pipe(running, filter$5((current) => current === config.binary), match$8({
102641
- onNone: constUndefined,
102642
- onSome: () => ({ restart: false })
102643
- }))), provideService$2(ChildProcessSpawner, spawner), provideService$2(FileSystem, fs), provideService$2(Path$1, path));
102644
- yield* retry(run(config.binary, [
102645
- "reload",
102646
- "--address",
102647
- `127.0.0.1:${CADDY_ADMIN_PORT}`,
102648
- "--config",
102649
- configFile,
102650
- "--adapter",
102651
- "caddyfile"
102652
- ]), {
102653
- schedule: spaced(millis(200)),
102654
- times: 10,
102655
- while: is$2(AppError)
102656
- });
102657
- }, scoped, mapError$2((cause) => DeployError.make({
102658
- cause,
102659
- message: "Caddy did not load the owned public exposures"
102660
- }))),
102661
- runtime: fn("Proxies.runtime")(function* (port) {
102662
- return yield* pipe(http.get(`http://127.0.0.1:${port}${RUNTIME_PATH}`), flatMap$3(schemaBodyJson$1(RuntimeConfig)), timeout(seconds(2)), option$1);
102663
- }),
102664
- serve: fn("Proxies.serve")(function* (port) {
102665
- yield* asDeployError$3(run("tailscale", [
102666
- "serve",
102667
- "--bg",
102668
- `--https=${port}`,
102669
- `http://127.0.0.1:${port}`
102670
- ]));
102671
- }),
102672
- serveStatus: pipe(run("tailscale", [
102673
- "serve",
102674
- "status",
102675
- "--json"
102676
- ]), flatMap$3(decodeUnknownEffect(fromJsonString(Serve))), asDeployError$3),
102677
- tailnetName: pipe(run("tailscale", ["status", "--json"]), flatMap$3(decodeEffect(fromJsonString(TailnetStatus))), map$7((status) => map$13(status.Self, (self) => replace(/\.$/u, "")(self.DNSName))), asDeployError$3),
102678
- unserve: fn("Proxies.unserve")(function* (port) {
102679
- yield* asDeployError$3(run("tailscale", [
102680
- "serve",
102681
- `--https=${port}`,
102682
- "off"
102683
- ]));
102684
- }),
102685
- validate: fn("Proxies.validate")(function* (rows) {
102686
- yield* written(rows);
102687
- }, scoped, mapError$2((cause) => DeployError.make({
102688
- cause,
102689
- message: "Caddy refused this public exposure"
102690
- })))
102691
- });
102692
- }));
102253
+ // src/services/inventory/lib/failures.ts
102254
+ const SIGNALS = {
102255
+ 1: "SIGHUP",
102256
+ 2: "SIGINT",
102257
+ 6: "SIGABRT",
102258
+ 9: "SIGKILL",
102259
+ 11: "SIGSEGV",
102260
+ 15: "SIGTERM"
102693
102261
  };
102694
- // src/services/exposures/lib/policy.ts
102695
- function reservedPort(port) {
102696
- return pipe(port, liftPredicate((candidate) => candidate === CADDY_ADMIN_PORT), map$13(constant$1("Caddy’s admin port is never published")));
102697
- }
102698
- function refusal(exposure, listener) {
102699
- const reserved = reservedPort(exposure.port);
102700
- if (isSome(reserved)) return reserved;
102701
- return pipe(listener.runtime, map$13((runtime) => runtime.name), orElse$3(() => pipe(listener.owner, flatMap$8(match$2(/^user:deslop-([a-z0-9-]+?)(?:\.service)?$/u)), flatMap$8((match) => fromUndefinedOr(match[1])))), flatMap$8((name) => match$8(listener.runtime, {
102702
- onNone: () => some$1(`${name} did not say how it runs; publish it once it answers`),
102703
- onSome: (runtime) => match$8(runtime.auth, {
102704
- onNone: () => some$1(`${name} runs without a domain, so Deploy never publishes it`),
102705
- onSome: (auth) => {
102706
- if (exposure.name !== name) return some$1(`Port ${exposure.port} belongs to ${name}; publish it only under the name ${name}`);
102707
- const own = `${name}.${replace(/^https:\/\/auth\./u, "")(auth)}`;
102708
- if (exposure.kind === "public" && exposure.hostname !== own) return some$1(`Publish ${name} only at ${own}`);
102709
- return none();
102710
- }
102711
- })
102712
- })));
102713
- }
102714
- function ownedConflict(owned, exposure) {
102715
- if (some(owned, (row) => row.name === exposure.name)) return some$1("Remove the existing owned exposure, and let its removal finish, before changing it");
102716
- if (some(owned, (row) => row.hostname === exposure.hostname && (row.kind === "public" || row.port === exposure.port))) return some$1("This hostname or port already has an owned exposure");
102717
- return none();
102718
- }
102719
- function restoreRefusal(row, listener) {
102720
- return match$8(listener.owner, {
102721
- onNone: () => some$1(`Nothing listens on 127.0.0.1:${row.port}, so it is not published until its owner does`),
102722
- onSome: (current) => pipe(row.owner, filter$5((saved) => saved !== current), map$13((saved) => `Port ${row.port} now belongs to ${current}, not ${saved}, so Deploy withdraws this site; it returns when ${saved} listens again`), orElse$3(() => refusal(row, listener)))
102723
- });
102262
+ function failureReason(result, status, ran) {
102263
+ if (result === "exit-code" && !ran) return "Failed before starting";
102264
+ const signal = SIGNALS[status] ?? `signal ${status}`;
102265
+ return pipe(value(result), when("exit-code", () => match$8(fromUndefinedOr(SIGNALS[status - 128]), {
102266
+ onNone: () => `Exited with code ${status}`,
102267
+ onSome: (name) => `Exited with code ${status} (${name})`
102268
+ })), when("signal", () => `Killed by ${signal}`), when("core-dump", () => `Crashed with ${signal}`), when("oom-kill", constant$1("Killed for running out of memory")), when("timeout", constant$1("Timed out")), when("watchdog", constant$1("Stopped answering its watchdog")), when("start-limit-hit", constant$1("Restarted too often")), orElse(() => `Failed: ${result}`));
102724
102269
  }
102725
- // src/services/exposures/lib/reconciler.ts
102726
- const makeReconciler = fnUntraced(function* (pass, finished, unchanged) {
102727
- const wake = yield* sliding$1(1);
102728
- const waiting = yield* make$49(none());
102729
- const retry = yield* make$49(none());
102730
- yield* pipe(gen(function* () {
102731
- yield* match$8(yield* get$3(retry), {
102732
- onNone: () => take$1(wake),
102733
- onSome: (state) => raceFirst(take$1(wake), sleep(pipe(seconds(5), times(2 ** state.failed), min$2(minutes(10)))))
102734
- });
102735
- const served = yield* getAndSet(waiting, none());
102736
- const exit$2 = yield* exit(pass);
102737
- yield* forEach$1(toArray(served), (deferred) => done(deferred, exit$2), {
102738
- concurrency: 1,
102739
- discard: true
102740
- });
102741
- yield* update(retry, (state) => {
102742
- if (isSuccess(exit$2) && finished(exit$2.value)) return none();
102743
- const before = flatMap$8(state, (last) => last.outcome);
102744
- const outcome = match$3(exit$2, {
102745
- onFailure: () => before,
102746
- onSuccess: some$1
102747
- });
102748
- return some$1({
102749
- failed: pipe(state, filter$5(() => makeEquivalence$5(unchanged)(before, outcome)), match$8({
102750
- onNone: constant$1(0),
102751
- onSome: (last) => min$1(last.failed + 1, 7)
102752
- })),
102753
- outcome
102754
- });
102755
- });
102756
- }), forever, forkScoped);
102757
- return { request: gen(function* () {
102758
- const fresh = yield* make$85();
102759
- const deferred = yield* modify$1(waiting, (current) => match$8(current, {
102760
- onNone: () => [fresh, some$1(fresh)],
102761
- onSome: (pending) => [pending, current]
102270
+ function unitFailures(text) {
102271
+ return pipe(trim(text), split(/\n\s*\n/u), filter$3(isNonEmpty$1), flatMap$6((block) => {
102272
+ const fields = pipe(block, split("\n"), filter$3(includes("=")), fromIterableWith((line) => {
102273
+ const [key, ...value] = split(line, "=");
102274
+ return [key, join$3(value, "=")];
102762
102275
  }));
102763
- yield* offer(wake, void 0);
102764
- return yield* _await(deferred);
102765
- }) };
102766
- });
102767
- // src/services/exposures/migrations.ts
102768
- const migrations$1 = {
102769
- "0001_exposures": flatMap$3(SqlClient, (sql) => sql`
102770
- CREATE TABLE exposures (
102771
- name TEXT PRIMARY KEY,
102772
- kind TEXT NOT NULL,
102773
- hostname TEXT NOT NULL,
102774
- port INTEGER NOT NULL
102775
- ) STRICT
102776
- `),
102777
- "0002_exposure_state": flatMap$3(SqlClient, (sql) => sql`ALTER TABLE exposures ADD COLUMN state TEXT NOT NULL DEFAULT 'active'`),
102778
- "0003_exposure_owner": flatMap$3(SqlClient, (sql) => sql`ALTER TABLE exposures ADD COLUMN owner TEXT`)
102779
- };
102780
- // src/services/inventory/lib/utils.ts
102781
- function sourceBelongsToWorker(source, worker) {
102782
- return source.name === worker || startsWith(`${worker} · `)(source.name);
102783
- }
102784
- function processOwner(cgroup) {
102785
- const container = pipe(cgroup, match$2(/\/(?:docker-|docker\/)([a-f0-9]{12,64})(?:\.scope)?(?:\/|\n|$)/u), flatMap$8((match) => get$13(match, 1)));
102786
- if (isSome(container)) return map$13(container, (id) => AppId.make(`container:${slice(0, 12)(id)}`));
102787
- const segments = split$1(cgroup, /[/\n]/u);
102788
- const service = findLastIndex(segments, endsWith(".service"));
102789
- const userService = findFirstIndex(segments, (segment) => isSome(match$2(/^user@[0-9]+\.service$/u)(segment)));
102790
- return pipe(userService, filter$5((index) => !exists(service, (last) => last > index)), flatMap$8((index) => pipe(segments, drop$1(index + 1), findFirst((segment) => match$2(/^app-(.+)\.slice$/u)(segment)))), map$13((match) => AppId.make(`service:user:${match[1]}.service`)), orElse$3(() => map$13(service, (index) => AppId.make(`service:${pipe(userService, exists((first) => index > first), match({
102791
- onFalse: constant$1("system"),
102792
- onTrue: constant$1("user")
102793
- }))}:${segments[index]}`))));
102794
- }
102795
- function ipv4Reachable(address) {
102796
- return isSome(match$2(/^(?:127\.0\.0\.1|0\.0\.0\.0|\*):/u)(address));
102797
- }
102798
- function loopbackPort(item) {
102799
- return item.kind === "port" && contains$2(item.protocol, "tcp") && exists(item.port, (port) => port >= 1024) && exists(item.address, ipv4Reachable);
102800
- }
102801
- function appPort(item) {
102802
- return loopbackPort(item) && isSome(item.process) && !exists(item.port, (port) => contains$1([5353, 5355], port)) && !exists(item.process, (process) => isSome(match$2(/^(?:ssh|cloudflared|tailscaled|caddy|ControlCenter)$/u)(process)));
102803
- }
102804
- function important(item) {
102805
- if (item.health === "error") return true;
102806
- if (item.kind === "exposure") return contains$2(item.owned, true) || contains$2(item.publicAccess, true);
102807
- if (item.kind === "container") return item.active;
102808
- if (item.kind === "port") return appPort(item);
102809
- if (item.kind !== "service") return false;
102810
- if (isSome(match$2(/^(?:deslop-|preview-|t3code)/u)(item.name))) return true;
102811
- return contains$2(item.scope, "user") && item.active && isNone(match$2(/^(?:dbus|dirmngr|gpg-|keyboxd|gcr-|gnome-|secret-service|ssh-agent|openvpn3-)/u)(item.name));
102812
- }
102813
- function ports(items) {
102814
- return pipe(items, filter$3((item) => appPort(item) && contains$2(item.http, true)), sort(mapInput(String$10, (item) => `${item.worker}:${getOrUndefined$2(item.port)}:${getOrUndefined$2(item.address)}`)), dedupeWith((a, b) => a.worker === b.worker && makeEquivalence$5((x, y) => x === y)(a.port, b.port)));
102815
- }
102816
- function serviceUnit(item) {
102817
- if (item.kind === "service") return getOrElse$1(item.unit, () => item.name);
102818
- return UnitId.make(item.name);
102819
- }
102820
- function itemOwner(item) {
102821
- if (item.kind === "container") return AppId.make(`container:${slice(0, 12)(getOrElse$1(last(split$1(item.id, ":docker:")), constant$1("")))}`);
102822
- return AppId.make(`service:${getOrElse$1(item.scope, constant$1("system"))}:${serviceUnit(item)}`);
102823
- }
102824
- function portOwner(items, port) {
102825
- const containers = flatMap$6(items, (item) => {
102826
- if (item.kind !== "container") return [];
102827
- return pipe(flatten$4(toArray(item.bindings)), filter$3((binding) => binding.protocol === "tcp" && binding.port === port && ipv4Reachable(binding.address)), map$10(() => `container:${item.name}`));
102828
- });
102829
- return pipe(match$6(containers, {
102830
- onEmpty: () => flatMap$6(items, (item) => {
102831
- if (item.kind !== "port" || !contains$2(item.port, port) || !contains$2(item.protocol, "tcp") || !exists(item.address, ipv4Reachable)) return [];
102832
- return [match$8(item.unit, {
102833
- onNone: () => `process:${getOrElse$1(item.process, constant$1("unknown"))}`,
102834
- onSome: (unit) => `${getOrElse$1(item.scope, constant$1("system"))}:${unit}`
102835
- })];
102836
- }),
102837
- onNonEmpty: identity
102838
- }), dedupe, sort(String$10), match$6({
102839
- onEmpty: none,
102840
- onNonEmpty: (owners) => some$1(join$3(owners, " + "))
102841
- }));
102842
- }
102843
- function fullName(item) {
102844
- if (item.kind === "port") return getOrElse$1(item.process, () => item.name);
102845
- if (item.kind === "container" && startsWith("deslop-")(item.name)) return replace(/-[0-9]+$/u, "")(slice(7)(item.name));
102846
- if (startsWith("preview-")(item.name)) return match$8(match$2(/@deslop\/([a-z0-9-]+)/u)(item.detail), {
102847
- onNone: () => `Preview ${replace(/\.service$/u, "")(slice(8)(item.name))}`,
102848
- onSome: (app) => `${app[1]} preview`
102849
- });
102850
- return replaceAll(/^deslop-|\.service$/gu, "")(item.name);
102851
- }
102852
- function workloadName(item) {
102853
- return pipe(fullName(item), replaceAll(/\b([a-f0-9]{7})[a-f0-9]+\b/giu, "$1"), replaceAll(/\b(?=[a-z0-9]{10,}\b)(?=[a-z0-9]*[0-9])([a-z0-9]{7})[a-z0-9]+\b/giu, "$1"));
102854
- }
102855
- function sameSocket(listener, binding) {
102856
- if (contains$2(listener.address, "container") || binding.address === "container") return false;
102857
- if (!contains$2(listener.port, binding.port) || !contains$2(listener.protocol, binding.protocol)) return false;
102858
- if (contains$2(listener.address, binding.address)) return true;
102859
- return exists(listener.address, ipv4Reachable) && ipv4Reachable(binding.address);
102860
- }
102861
- function socket(worker, binding) {
102862
- const loopback = exists(binding.address, ipv4Reachable);
102863
- return make$88(worker, binding.protocol, binding.port, loopback, match(loopback, {
102864
- onFalse: () => binding.address,
102865
- onTrue: () => some$1("")
102866
- }));
102867
- }
102868
- function unitKey(scope, unit) {
102869
- return `${getOrElse$1(scope, constant$1("system"))}:${unit}`;
102870
- }
102871
- function workloads(items) {
102872
- const listeners = filter$3(items, (item) => item.kind === "port");
102873
- const byUnit = pipe(listeners, groupBy((listener) => listener.worker), map$11((worker) => groupBy(worker, (listener) => match$8(listener.unit, {
102874
- onNone: constant$1("none"),
102875
- onSome: (unit) => `unit:${unitKey(listener.scope, unit)}`
102876
- }))));
102877
- const bySocket = fromIterable$5(map$10(reverse(filter$3(listeners, (listener) => !contains$2(listener.address, "container"))), (listener) => [socket(listener.worker, listener), listener]));
102878
- const grouped = pipe(items, filter$3((item) => item.kind === "service" || item.kind === "container"), map$10((item) => {
102879
- const unit = serviceUnit(item);
102880
- const attached = byUnit[item.worker]?.[`unit:${unitKey(item.scope, unit)}`] ?? [];
102881
- const bindings = pipe(item.bindings, getOrElse$1(empty$14), map$10((binding) => ({
102882
- ...item,
102883
- ...pipe(get$10(bySocket, socket(item.worker, {
102884
- address: some$1(binding.address),
102885
- port: some$1(binding.port),
102886
- protocol: some$1(binding.protocol)
102887
- })), filter$5(() => binding.address !== "container"), getOrElse$1(() => ({}))),
102888
- address: some$1(binding.address),
102889
- bindings: some$1([]),
102890
- id: ItemId.make(`${item.id}:port:${binding.address}`),
102891
- kind: "port",
102892
- port: some$1(binding.port),
102893
- process: some$1(item.name),
102894
- protocol: some$1(binding.protocol),
102895
- unit: pipe(item, liftPredicate((owner) => owner.kind === "service"), map$13(serviceUnit)),
102896
- url: none()
102897
- })));
102898
- return {
102899
- item,
102900
- listeners: [...attached, ...bindings]
102901
- };
102902
- }));
102903
- const services = fromIterable$3(pipe(grouped, filter$3((row) => row.item.kind === "service"), map$10((row) => make$88(row.item.worker, unitKey(row.item.scope, serviceUnit(row.item))))));
102904
- const represented = fromIterable$3(flatMap$6(grouped, (row) => pipe(row.listeners, filter$3((binding) => !contains$2(binding.address, "container")), map$10((binding) => socket(row.item.worker, {
102905
- address: binding.address,
102906
- port: binding.port,
102907
- protocol: binding.protocol
102908
- })))));
102909
- const loose = filter$3(listeners, (listener) => !exists(listener.unit, (unit) => has$1(services, make$88(listener.worker, unitKey(listener.scope, unit)))) && (contains$2(listener.address, "container") || !has$1(represented, socket(listener.worker, listener))));
102910
- const rows = [...grouped, ...map$10(loose, (item) => ({
102911
- item,
102912
- listeners: [item]
102913
- }))];
102914
- const exposures = [...filter$3(items, (item) => item.kind === "exposure" && contains$2(item.owned, true)), ...filter$3(items, (item) => item.kind === "exposure" && !contains$2(item.owned, true))];
102915
- const exposuresBySocket = pipe(exposures, map$10((item, index) => ({
102916
- index,
102917
- item
102918
- })), groupBy((entry) => `${entry.item.worker}:${getOrElse$1(entry.item.port, constant$1(0))}`));
102919
- const visible = pipe(rows, map$10((row) => {
102920
- const reachable = dedupe(pipe(row.listeners, filter$3((listener) => exists(listener.port, (port) => sameSocket(listener, {
102921
- address: `127.0.0.1:${port}`,
102922
- port,
102923
- protocol: "tcp"
102924
- }))), map$10((listener) => listener.port), getSomes));
102925
- const exposed = pipe(flatMap$6(reachable, (port) => exposuresBySocket[`${row.item.worker}:${port}`] ?? []), sortWith((entry) => entry.index, Number$6), map$10((entry) => entry.item));
102926
- return {
102927
- ...row,
102928
- exposures: dedupeWith([...pipe(row.item.links, getOrElse$1(empty$14), map$10((url) => ({
102929
- ...row.item,
102930
- id: ItemId.make(`${row.item.id}:url:${url}`),
102931
- kind: "exposure",
102932
- name: ExposureName.make(row.item.name),
102933
- owned: some$1(false),
102934
- publicAccess: some$1(true),
102935
- url: some$1(url)
102936
- }))), ...exposed], (a, b) => equals$1(a.url, b.url) && equals$1(a.publicAccess, b.publicAccess))
102937
- };
102938
- }), filter$3((row) => important(row.item) && (row.item.kind !== "port" || contains$2(row.item.http, true) && isSome(row.item.process) && !contains$2(row.item.process, "node"))));
102939
- const linkedIds = fromIterable$3(flatMap$6(visible, (row) => map$10(row.exposures, (exposure) => exposure.id)));
102940
- const linkedUrls = fromIterable$3(flatMap$6(visible, (row) => map$10(row.exposures, (exposure) => make$88(exposure.worker, exposure.url))));
102941
- const remaining = pipe(exposures, filter$3((item) => !has$1(linkedIds, item.id) && !has$1(linkedUrls, make$88(item.worker, item.url))), map$10((item) => ({
102942
- exposures: [item],
102943
- item,
102944
- listeners: []
102945
- })), filter$3((row) => important(row.item)));
102946
- return map$10([...visible, ...remaining], (row) => {
102947
- if (row.item.kind === "container") return row;
102948
- const candidates = ports(row.listeners);
102949
- const hasUi = some(candidates, (candidate) => contains$2(candidate.ui, true));
102950
- const exposedPorts = fromIterable$3(getSomes(map$10(row.exposures, (exposure) => exposure.port)));
102951
- return {
102952
- ...row,
102953
- listeners: filter$3(candidates, (listener) => !hasUi || contains$2(listener.ui, true) || exists(listener.port, (port) => has$1(exposedPorts, port)))
102954
- };
102955
- });
102956
- }
102957
- function status(item) {
102958
- if (item.kind === "port") return "listening";
102959
- if (item.kind === "exposure" && contains$2(item.owned, true)) return "configured";
102960
- if (item.kind === "exposure" && contains$2(item.publicAccess, true)) return "public permission";
102961
- return item.state;
102962
- }
102963
- function usage(nodes) {
102964
- return {
102965
- cpu: pipe(nodes, map$10((node) => node.cpu), getSomes, match$6({
102966
- onEmpty: () => none(),
102967
- onNonEmpty: (values) => some$1(sumAll(values))
102968
- })),
102969
- memory: sumAll(map$10(nodes, (node) => node.memory))
102970
- };
102971
- }
102972
- const byUsage = pipe(flip$3(Number$6), mapInput((node) => node.memory), combine$3(mapInput(makeOrder(flip$3(Number$6)), (node) => node.cpu)));
102973
- function settle(children, appMemory) {
102974
- return pipe(children, sort(byUsage), map$10((node) => ({
102975
- ...node,
102976
- small: node.memory < appMemory * .02 && !exists(node.cpu, (cpu) => cpu >= .5)
102977
- })));
102978
- }
102979
- function sameLabel(first, second) {
102980
- return first.name === second.name && first.detail === second.detail;
102981
- }
102982
- function absorb(label, children) {
102983
- const [matching, other] = partition(children, fromPredicate((child) => sameLabel(child.label, label)));
102984
- if (isArrayEmpty(matching)) return children;
102985
- return [...other, ...absorb(label, flatMap$6(matching, (child) => child.children))];
102986
- }
102987
- function fold(node) {
102988
- return {
102989
- ...node,
102990
- children: absorb(node.label, map$10(node.children, fold))
102991
- };
102992
- }
102993
- function processTree(rows) {
102994
- const pids = fromIterable(map$10(rows, (row) => row.pid));
102995
- const children = groupBy(rows, (row) => String$9(row.parent));
102996
- const visited = empty$3();
102997
- function build(row) {
102998
- add$1(visited, row.pid);
102999
- const below = pipe(get$14(children, `${row.pid}`), getOrElse$1(empty$14), filter$3((child) => !has(visited, child.pid)), map$10(build));
103000
- const self = {
103001
- children: [],
103002
- cpu: row.cpu,
103003
- label: row.label,
103004
- memory: row.memory,
103005
- pid: row.pid,
103006
- small: false
103007
- };
103008
- return {
103009
- ...self,
103010
- ...usage([self, ...below]),
103011
- children: below
103012
- };
103013
- }
103014
- const roots = pipe(filter$3(rows, (row) => !has(pids, row.parent)), match$6({
103015
- onEmpty: () => take$3(rows, 1),
103016
- onNonEmpty: identity
103017
- }), map$10((node) => fold(build(node))));
103018
- const appMemory = usage(roots).memory;
103019
- function place(node) {
103020
- return {
103021
- ...node,
103022
- children: settle(map$10(node.children, place), appMemory)
103023
- };
103024
- }
103025
- return settle(map$10(roots, place), appMemory);
103026
- }
103027
- function workerNames(snapshot) {
103028
- return dedupe([...snapshot.workers, ...map$10(snapshot.items, (item) => item.worker)]);
103029
- }
103030
- function errorsOf(sources, workers, worker) {
103031
- const local = head(workers);
103032
- return pipe(sources, filter$3((source) => pipe(workers, findFirst((candidate) => sourceBelongsToWorker(source, candidate)), orElse$3(() => local), contains$2(worker))), filterMap(fromPredicateOption((source) => map$13(source.error, (error) => `${replace(`${worker} · `, "")(source.name)}: ${error}`))));
103033
- }
103034
- function portsOf(row) {
103035
- return pipe([...row.listeners, ...row.exposures], filter$3((item) => !contains$2(item.address, "container")), map$10((item) => item.port), getSomes, dedupe, sort(Number$6));
103036
- }
103037
- function failureOf(item) {
103038
- if (item.health === "quiet") return {
103039
- failure: none(),
103040
- since: none()
103041
- };
103042
- return {
103043
- failure: some$1(match$8(item.failure, {
103044
- onNone: () => status(item),
103045
- onSome: (stop) => stop.reason
103046
- })),
103047
- since: flatMap$8(item.failure, (failure) => failure.at)
103048
- };
103049
- }
103050
- function summaryOf(node) {
103051
- return {
103052
- children: pipe(node.children, liftPredicate(isReadonlyArrayNonEmpty), map$13((children) => map$10(children, summaryOf))),
103053
- cpu: map$13(node.cpu, (cpu) => round(cpu, 1)),
103054
- detail: liftPredicate(node.label.detail, isNonEmpty$1),
103055
- mib: round(node.memory / 1024 ** 2, 0),
103056
- name: node.label.name
103057
- };
103058
- }
103059
- function appOf(row, withProcesses) {
103060
- const reachable = portsOf(row);
103061
- const url = flatMap$8(head(row.exposures), (exposure) => exposure.url);
103062
- return {
103063
- ...failureOf(row.item),
103064
- id: row.item.id,
103065
- name: workloadName(row.item),
103066
- ports: liftPredicate(reachable, isReadonlyArrayNonEmpty),
103067
- processes: pipe(row.item.processes, filter$5((processes) => withProcesses && isReadonlyArrayNonEmpty(processes)), map$13((processes) => map$10(processTree(processes), summaryOf))),
103068
- state: row.item.state,
103069
- url
103070
- };
103071
- }
103072
- function matches(row, app) {
103073
- const needle = toLowerCase(app);
103074
- return some([
103075
- workloadName(row.item),
103076
- row.item.name,
103077
- ...toArray(row.item.unit)
103078
- ], (name) => includes(needle)(toLowerCase(name)));
103079
- }
103080
- function rank(row) {
103081
- if (row.item.health === "error") return 0;
103082
- if (row.item.health === "warning") return 1;
103083
- return 2;
103084
- }
103085
- const rowUsageOrder = mapInput(flip$3(Number$6), (row) => pipe(getOrElse$1(row.item.processes, empty$14), map$10((process) => process.memory), sumAll));
103086
- const appOrder = pipe(Number$6, mapInput(rank), combine$3(rowUsageOrder));
103087
- const jobOrder = pipe(Number$6, mapInput(rank), combine$3(mapInput(makeOrder(Order$2), (row) => row.item.next)));
103088
- function listApps(snapshot, input) {
103089
- const app = filter$5(input.app, isNonEmpty$1);
103090
- const onlyFailing = contains$2(input.failing, true);
103091
- return pipe(workerNames(snapshot), filter$3((worker) => !exists(input.worker, (selected) => selected !== worker)), map$10((worker) => {
103092
- const own = filter$3(workloads(snapshot.items), (row) => row.item.worker === worker);
103093
- const apps = pipe(filter$3(own, (row) => (row.item.kind === "service" || row.item.kind === "container") && !contains$2(row.item.scheduled, true) && !exists(app, (query) => !matches(row, query)) && (!onlyFailing || row.item.health !== "quiet")), sort(appOrder), map$10((row) => appOf(row, isSome(app))));
103094
- const jobs = pipe(filter$3(own, (row) => contains$2(row.item.scheduled, true) && (!onlyFailing || row.item.health !== "quiet")), sort(jobOrder), map$10((row) => ({
103095
- ...failureOf(row.item),
103096
- id: row.item.id,
103097
- name: JobName.make(workloadName(row.item)),
103098
- next: row.item.next,
103099
- running: row.item.running
103100
- })));
103101
- const exposures = pipe(snapshot.items, flatMap$6((item) => {
103102
- if (item.kind !== "exposure" || item.worker !== worker || onlyFailing && item.health === "quiet" || !important(item)) return [];
103103
- return toArray(map$13(item.url, (url) => ({
103104
- access: pipe(item.publicAccess, contains$2(true), match({
103105
- onFalse: constant$1("tailnet"),
103106
- onTrue: constant$1("public")
103107
- })),
103108
- failure: failureOf(item).failure,
103109
- id: item.id,
103110
- name: ExposureName.make(item.name),
103111
- port: item.port,
103112
- url
103113
- })));
103114
- }), sort(mapInput(String$10, (exposure) => exposure.url)));
103115
- return {
103116
- apps,
103117
- errors: liftPredicate(errorsOf(snapshot.sources, workerNames(snapshot), worker), isReadonlyArrayNonEmpty),
103118
- exposures: liftPredicate(exposures, isReadonlyArrayNonEmpty),
103119
- jobs: liftPredicate(jobs, isReadonlyArrayNonEmpty),
103120
- worker
103121
- };
103122
- }));
103123
- }
103124
- function ownerNames(snapshot) {
103125
- const byWorker = groupBy(snapshot.items, (item) => item.worker);
103126
- return fromIterableWith(workerNames(snapshot), (worker) => [worker, pipe(byWorker[worker] ?? empty$14(), filter$3((item) => item.kind === "service" || item.kind === "container"), fromIterableWith((item) => [itemOwner(item), workloadName(item)]))]);
103127
- }
103128
- function requestOf(item) {
103129
- return {
103130
- name: UnitId.make(item.name),
103131
- scope: getOrElse$1(item.scope, constant$1("system")),
103132
- worker: item.worker
103133
- };
103134
- }
103135
- const jobRequest = fnUntraced(function* (snapshot, input) {
103136
- const matching = filter$3(workloads(snapshot.items), (row) => contains$2(row.item.scheduled, true) && !exists(input.worker, (worker) => row.item.worker !== worker) && (workloadName(row.item) === input.job || row.item.name === input.job));
103137
- if (!isArrayNonEmpty(matching)) return yield* DeployError.make({ message: `No scheduled job named ${input.job}; list_apps shows the jobs.` });
103138
- if (matching.length > 1) return yield* DeployError.make({ message: `${input.job} runs on more than one worker; pass its worker.` });
103139
- return requestOf(headNonEmpty(matching).item);
103140
- });
103141
- // src/services/inventory/lib/failures.ts
103142
- const SIGNALS = {
103143
- 1: "SIGHUP",
103144
- 2: "SIGINT",
103145
- 6: "SIGABRT",
103146
- 9: "SIGKILL",
103147
- 11: "SIGSEGV",
103148
- 15: "SIGTERM"
103149
- };
103150
- function failureReason(result, status, ran) {
103151
- if (result === "exit-code" && !ran) return "Failed before starting";
103152
- const signal = SIGNALS[status] ?? `signal ${status}`;
103153
- return pipe(value(result), when("exit-code", () => match$8(fromUndefinedOr(SIGNALS[status - 128]), {
103154
- onNone: () => `Exited with code ${status}`,
103155
- onSome: (name) => `Exited with code ${status} (${name})`
103156
- })), when("signal", () => `Killed by ${signal}`), when("core-dump", () => `Crashed with ${signal}`), when("oom-kill", constant$1("Killed for running out of memory")), when("timeout", constant$1("Timed out")), when("watchdog", constant$1("Stopped answering its watchdog")), when("start-limit-hit", constant$1("Restarted too often")), orElse(() => `Failed: ${result}`));
103157
- }
103158
- function exitFailure(status) {
103159
- if (status < 0) return failureReason("signal", -status, true);
103160
- return failureReason("exit-code", status, true);
103161
- }
103162
- function unitFailures(text) {
103163
- return pipe(trim(text), split$1(/\n\s*\n/u), filter$3(isNonEmpty$1), flatMap$6((block) => {
103164
- const fields = pipe(block, split$1("\n"), filter$3(includes("=")), fromIterableWith((line) => {
103165
- const [key, ...value] = split$1(line, "=");
103166
- return [key, join$3(value, "=")];
103167
- }));
103168
- const id = fields["Id"] ?? "";
103169
- const result = fields["Result"] ?? "";
103170
- const status = parse$2(fields["ExecMainStatus"] ?? "");
103171
- if (!isNonEmpty$1(id) || !isNonEmpty$1(fields["ExecMainCode"] ?? "") || fields["ActiveState"] !== "failed" || !isNonEmpty$1(result) || result === "success") return [];
103172
- return match$8(status, {
103173
- onNone: () => [],
103174
- onSome: (exitStatus) => [[UnitId.make(id), {
103175
- at: map$13(parse$2(replace(/^@/u, "")(fields["StateChangeTimestamp"] ?? "")), (seconds) => mapEpochMillis(makeUnsafe$5(0), () => seconds * 1e3)),
103176
- reason: failureReason(result, exitStatus, fields["ExecMainCode"] !== "0")
103177
- }]]
103178
- });
103179
- }), fromEntries);
103180
- }
103181
- // src/services/inventory/lib/launchd.ts
103182
- function applicationBundle(path) {
103183
- return pipe(match$2(/^(\/[^\n]*?\.app)(?:\/|$)/u)(path), map$13((match) => match[1] ?? ""), filter$5(isNonEmpty$1));
103184
- }
103185
- function launchProgram(text) {
103186
- return pipe(match$2(/^\tprogram = (\/[^\n]+)$/mu)(text), map$13((match) => match[1] ?? ""), filter$5(isNonEmpty$1));
103187
- }
103188
- function systemProgram(path) {
103189
- return isSome(match$2(/^(?:\/System|\/usr|\/bin|\/sbin|\/Library\/Apple)(?:\/|$)/u)(path));
103190
- }
103191
- function launchAgents(text) {
103192
- return getSomes(pipe(text, split$1("\n"), map$10((line) => {
103193
- const [pid, status = "", label = ""] = split$1(trim(line), " ");
103194
- if (!isNonEmpty$1(label) || startsWith("com.apple.")(label) || startsWith("application.")(label) || startsWith("deslop-")(label) && endsWith("-update")(label)) return none();
103195
- const processId = filter$5(decodeOption(ProcessIdFromString)(pid), (value) => value > 0);
103196
- if (isNone(processId) && pid !== "-") return none();
103197
- return some$1({
103198
- bundle: none(),
103199
- detail: "user · launch agent",
103200
- label: UnitId.make(label),
103201
- name: label,
103202
- pid: processId,
103203
- status: parse$2(status)
103204
- });
103205
- })));
103206
- }
103207
- function dockApplications(text, agentBundles = []) {
103208
- return getSomes(pipe(text, split$1(/\n(?=\s*[0-9]+\))/u), map$10((block) => {
103209
- const bundle = flatMap$8(match$2(/^\s+bundle path="([^"\n]+)"\s*$/mu)(block), (match) => applicationBundle(match[1] ?? ""));
103210
- const agentApplication = exists(bundle, (value) => contains$1(agentBundles, value));
103211
- const name = pipe(match$2(/^\s*[0-9]+\) "(.+)" ASN:/u)(block), map$13((match) => match[1] ?? ""), filter$5(isNonEmpty$1));
103212
- const pid = pipe(match$2(/^\s+pid = ([0-9]+) .*\btype="(Foreground|UIElement)"(?:\s|$)/mu)(block), filter$5((match) => match[2] === "Foreground" || agentApplication), flatMap$8((match) => decodeOption(ProcessIdFromString)(match[1] ?? "")), filter$5((value) => value > 0));
103213
- return map$13(all$5({
103214
- name,
103215
- pid
103216
- }), (app) => ({
103217
- bundle,
103218
- detail: "user · application",
103219
- label: UnitId.make(app.name),
103220
- name: app.name,
103221
- pid: app.pid
103222
- }));
103223
- })));
103224
- }
103225
- function macApplications(agents, applications) {
103226
- const running = pipe(agents, map$10((agent) => map$13(agent.pid, (pid) => ({
103227
- ...agent,
103228
- pid
103229
- }))), getSomes);
103230
- return pipe([...applications, ...running], map$10((app) => {
103231
- const dock = findFirst(applications, (candidate) => candidate.pid === app.pid || exists(app.bundle, (bundle) => contains$2(candidate.bundle, bundle)));
103232
- return {
103233
- ...app,
103234
- detail: match$8(dock, {
103235
- onNone: () => app.detail,
103236
- onSome: (candidate) => candidate.detail
103237
- }),
103238
- label: UnitId.make(getOrElse$1(app.bundle, () => pipe(dock, map$13((candidate) => candidate.label), getOrElse$1(() => app.label)))),
103239
- name: pipe(running, findFirst((candidate) => exists(app.bundle, (bundle) => contains$2(candidate.bundle, bundle))), match$8({
103240
- onNone: () => match$8(dock, {
103241
- onNone: () => app.name,
103242
- onSome: (candidate) => candidate.name
103243
- }),
103244
- onSome: (agent) => agent.name
103245
- }))
103246
- };
103247
- }), dedupeWith((left, right) => left.pid === right.pid));
102276
+ const id = fields["Id"] ?? "";
102277
+ const result = fields["Result"] ?? "";
102278
+ const status = parse$2(fields["ExecMainStatus"] ?? "");
102279
+ if (!isNonEmpty$1(id) || !isNonEmpty$1(fields["ExecMainCode"] ?? "") || fields["ActiveState"] !== "failed" || !isNonEmpty$1(result) || result === "success") return [];
102280
+ return match$8(status, {
102281
+ onNone: () => [],
102282
+ onSome: (exitStatus) => [[UnitId.make(id), {
102283
+ at: map$13(parse$2(replace(/^@/u, "")(fields["StateChangeTimestamp"] ?? "")), (seconds) => mapEpochMillis(makeUnsafe$5(0), () => seconds * 1e3)),
102284
+ reason: failureReason(result, exitStatus, fields["ExecMainCode"] !== "0")
102285
+ }]]
102286
+ });
102287
+ }), fromEntries);
103248
102288
  }
103249
102289
  // src/services/inventory/lib/command.ts
103250
102290
  const WRAPPERS = {
@@ -103382,7 +102422,7 @@ const SUBJECT = {
103382
102422
  vp: ["filter"]
103383
102423
  };
103384
102424
  function basename(value) {
103385
- return getOrElse$1(last(pipe(value, split$1("/"), filter$3(isNonEmpty$1))), () => value);
102425
+ return getOrElse$1(last(pipe(value, split("/"), filter$3(isNonEmpty$1))), () => value);
103386
102426
  }
103387
102427
  function isFlag(token) {
103388
102428
  return startsWith("-")(token) && token !== "-" && token !== "--";
@@ -103407,8 +102447,8 @@ function flagParts(token) {
103407
102447
  }
103408
102448
  function maskArguments(args) {
103409
102449
  return map$10(args, (arg, index) => {
103410
- if (isSome(match$2(/^-{0,2}[\w.-]+=/u)(arg)) && SECRET.test(split$1(arg, "=")[0])) return `${split$1(arg, "=")[0]}=…`;
103411
- if (isSome(match$2(/^[\w-]+:\s/u)(arg)) && SECRET.test(split$1(arg, ":")[0])) return `${split$1(arg, ":")[0]}: …`;
102450
+ if (isSome(match$2(/^-{0,2}[\w.-]+=/u)(arg)) && SECRET.test(split(arg, "=")[0])) return `${split(arg, "=")[0]}=…`;
102451
+ if (isSome(match$2(/^[\w-]+:\s/u)(arg)) && SECRET.test(split(arg, ":")[0])) return `${split(arg, ":")[0]}: …`;
103412
102452
  const previous = args[index - 1] ?? "";
103413
102453
  const secretValue = startsWith("-")(previous) && !includes("=")(previous) && SECRET.test(previous) || isSome(match$2(/^[\w-]+:$/u)(previous)) && SECRET.test(previous) || isSome(match$2(/^(?:bearer|basic|digest|token)$/iu)(previous));
103414
102454
  const opaque = !startsWith("/")(arg) && isSome(match$2(/^[\w+/=-]{32,}$/u)(arg));
@@ -103429,7 +102469,7 @@ function shellRest(tokens) {
103429
102469
  onSome: (matches) => matches.length
103430
102470
  });
103431
102471
  if (includes("exec \"$@\"")(script)) return drop$1(tokens, 4 + shifts);
103432
- const segments = pipe(maskArguments(shellWords(script)), join$3(" "), replaceAll(/\d*[<>]+\|?\s*\S+/gu, ""), split$1(/\s*(?:\|\|?|;|&&)\s*/u), map$10((segment) => pipe(replace(/^eval\s+/u, "")(trim(segment)), split$1(/\s+/u), dropWhile(assignment))), filter$3((words) => isNonEmpty$1(words[0] ?? "")));
102472
+ const segments = pipe(maskArguments(shellWords(script)), join$3(" "), replaceAll(/\d*[<>]+\|?\s*\S+/gu, ""), split(/\s*(?:\|\|?|;|&&)\s*/u), map$10((segment) => pipe(replace(/^eval\s+/u, "")(trim(segment)), split(/\s+/u), dropWhile(assignment))), filter$3((words) => isNonEmpty$1(words[0] ?? "")));
103433
102473
  return pipe(findFirst(segments, (words) => words[0] === "exec"), map$13((words) => drop$1(words, 1)), orElse$3(() => findFirst(segments, (words) => !contains$1(SETUP, words[0] ?? ""))), getOrElse$1(() => take$3(tokens, 1)));
103434
102474
  }
103435
102475
  function wrapped(args, wrapper) {
@@ -103462,7 +102502,7 @@ function unwrapTokens(tokens, cwd) {
103462
102502
  function unwrap(argv, cwd) {
103463
102503
  const tokens = match(length$1(argv) === 1, {
103464
102504
  onFalse: () => argv,
103465
- onTrue: () => pipe(head(argv), getOrElse$1(constant$1("")), split$1(/\s+/u), filter$3(isNonEmpty$1), maskArguments)
102505
+ onTrue: () => pipe(head(argv), getOrElse$1(constant$1("")), split(/\s+/u), filter$3(isNonEmpty$1), maskArguments)
103466
102506
  });
103467
102507
  return unwrapTokens([replace(/:$/u, "")(getOrElse$1(head(tokens), constant$1(""))), ...drop$1(tokens, 1)], cwd);
103468
102508
  }
@@ -103494,7 +102534,7 @@ function scan(name, subject, args, words, values) {
103494
102534
  }
103495
102535
  if (name === "ssh") return {
103496
102536
  ssh: some$1({
103497
- host: getOrElse$1(last(split$1(token, "@")), () => token),
102537
+ host: getOrElse$1(last(split(token, "@")), () => token),
103498
102538
  remote: drop$1(args, 1)
103499
102539
  }),
103500
102540
  values,
@@ -103535,35 +102575,380 @@ function commandLabel(argv, cwd) {
103535
102575
  }
103536
102576
  });
103537
102577
  }
102578
+ // src/services/inventory/lib/utils.ts
102579
+ function processOwner(cgroup) {
102580
+ const container = pipe(cgroup, match$2(/\/(?:docker-|docker\/)([a-f0-9]{12,64})(?:\.scope)?(?:\/|\n|$)/u), flatMap$8((match) => get$13(match, 1)));
102581
+ if (isSome(container)) return map$13(container, (id) => AppId.make(`container:${slice(0, 12)(id)}`));
102582
+ const segments = split(cgroup, /[/\n]/u);
102583
+ const service = findLastIndex(segments, endsWith(".service"));
102584
+ const userService = findFirstIndex(segments, (segment) => isSome(match$2(/^user@[0-9]+\.service$/u)(segment)));
102585
+ return pipe(userService, filter$5((index) => !exists(service, (last) => last > index)), flatMap$8((index) => pipe(segments, drop$1(index + 1), findFirst((segment) => match$2(/^app-(.+)\.slice$/u)(segment)))), map$13((match) => AppId.make(`service:user:${match[1]}.service`)), orElse$3(() => map$13(service, (index) => AppId.make(`service:${pipe(userService, exists((first) => index > first), match({
102586
+ onFalse: constant$1("system"),
102587
+ onTrue: constant$1("user")
102588
+ }))}:${segments[index]}`))));
102589
+ }
102590
+ function ipv4Reachable(address) {
102591
+ return isSome(match$2(/^(?:127\.0\.0\.1|0\.0\.0\.0|\*):/u)(address));
102592
+ }
102593
+ function loopbackPort(item) {
102594
+ return item.kind === "port" && contains$2(item.protocol, "tcp") && exists(item.port, (port) => port >= 1024) && exists(item.address, ipv4Reachable);
102595
+ }
102596
+ function appPort(item) {
102597
+ return loopbackPort(item) && isSome(item.process) && !exists(item.port, (port) => contains$1([5353, 5355], port)) && !exists(item.process, (process) => isSome(match$2(/^(?:ssh|cloudflared|tailscaled|caddy)$/u)(process)));
102598
+ }
102599
+ function important(item) {
102600
+ if (item.health === "error") return true;
102601
+ if (item.kind === "exposure") return contains$2(item.owned, true) || contains$2(item.publicAccess, true);
102602
+ if (item.kind === "container") return item.active;
102603
+ if (item.kind === "port") return appPort(item);
102604
+ if (item.kind !== "service") return false;
102605
+ if (isSome(match$2(/^(?:deslop-|preview-|t3code)/u)(item.name))) return true;
102606
+ return contains$2(item.scope, "user") && item.active && isNone(match$2(/^(?:dbus|dirmngr|gpg-|keyboxd|gcr-|gnome-|secret-service|ssh-agent|openvpn3-)/u)(item.name));
102607
+ }
102608
+ function ports(items) {
102609
+ return pipe(items, filter$3((item) => appPort(item) && contains$2(item.http, true)), sort(mapInput(String$10, (item) => `${getOrUndefined$2(item.port)}:${getOrUndefined$2(item.address)}`)), dedupeWith((a, b) => makeEquivalence$5((x, y) => x === y)(a.port, b.port)));
102610
+ }
102611
+ function serviceUnit(item) {
102612
+ if (item.kind === "service") return getOrElse$1(item.unit, () => item.name);
102613
+ return UnitId.make(item.name);
102614
+ }
102615
+ function itemOwner(item) {
102616
+ if (item.kind === "container") return AppId.make(`container:${slice(0, 12)(getOrElse$1(last(split(item.id, "docker:")), constant$1("")))}`);
102617
+ return AppId.make(`service:${getOrElse$1(item.scope, constant$1("system"))}:${serviceUnit(item)}`);
102618
+ }
102619
+ function portOwner(items, port) {
102620
+ const containers = flatMap$6(items, (item) => {
102621
+ if (item.kind !== "container") return [];
102622
+ return pipe(flatten$4(toArray(item.bindings)), filter$3((binding) => binding.protocol === "tcp" && binding.port === port && ipv4Reachable(binding.address)), map$10(() => `container:${item.name}`));
102623
+ });
102624
+ return pipe(match$6(containers, {
102625
+ onEmpty: () => flatMap$6(items, (item) => {
102626
+ if (item.kind !== "port" || !contains$2(item.port, port) || !contains$2(item.protocol, "tcp") || !exists(item.address, ipv4Reachable)) return [];
102627
+ return [match$8(item.unit, {
102628
+ onNone: () => `process:${getOrElse$1(item.process, constant$1("unknown"))}`,
102629
+ onSome: (unit) => `${getOrElse$1(item.scope, constant$1("system"))}:${unit}`
102630
+ })];
102631
+ }),
102632
+ onNonEmpty: identity
102633
+ }), dedupe, sort(String$10), match$6({
102634
+ onEmpty: none,
102635
+ onNonEmpty: (owners) => some$1(join$3(owners, " + "))
102636
+ }));
102637
+ }
102638
+ function fullName(item) {
102639
+ if (item.kind === "port") return getOrElse$1(item.process, () => item.name);
102640
+ if (item.kind === "container" && startsWith("deslop-")(item.name)) return replace(/-[0-9]+$/u, "")(slice(7)(item.name));
102641
+ if (startsWith("preview-")(item.name)) return match$8(match$2(/@deslop\/([a-z0-9-]+)/u)(item.detail), {
102642
+ onNone: () => `Preview ${replace(/\.service$/u, "")(slice(8)(item.name))}`,
102643
+ onSome: (app) => `${app[1]} preview`
102644
+ });
102645
+ return replaceAll(/^deslop-|\.service$/gu, "")(item.name);
102646
+ }
102647
+ function workloadName(item) {
102648
+ return pipe(fullName(item), replaceAll(/\b([a-f0-9]{7})[a-f0-9]+\b/giu, "$1"), replaceAll(/\b(?=[a-z0-9]{10,}\b)(?=[a-z0-9]*[0-9])([a-z0-9]{7})[a-z0-9]+\b/giu, "$1"));
102649
+ }
102650
+ function sameSocket(listener, binding) {
102651
+ if (contains$2(listener.address, "container") || binding.address === "container") return false;
102652
+ if (!contains$2(listener.port, binding.port) || !contains$2(listener.protocol, binding.protocol)) return false;
102653
+ if (contains$2(listener.address, binding.address)) return true;
102654
+ return exists(listener.address, ipv4Reachable) && ipv4Reachable(binding.address);
102655
+ }
102656
+ function socket(binding) {
102657
+ const loopback = exists(binding.address, ipv4Reachable);
102658
+ return make$88(binding.protocol, binding.port, loopback, match(loopback, {
102659
+ onFalse: () => binding.address,
102660
+ onTrue: () => some$1("")
102661
+ }));
102662
+ }
102663
+ function unitKey(scope, unit) {
102664
+ return `${getOrElse$1(scope, constant$1("system"))}:${unit}`;
102665
+ }
102666
+ function workloads(items) {
102667
+ const listeners = filter$3(items, (item) => item.kind === "port");
102668
+ const byUnit = groupBy(listeners, (listener) => match$8(listener.unit, {
102669
+ onNone: constant$1("none"),
102670
+ onSome: (unit) => `unit:${unitKey(listener.scope, unit)}`
102671
+ }));
102672
+ const bySocket = fromIterable$5(map$10(reverse(filter$3(listeners, (listener) => !contains$2(listener.address, "container"))), (listener) => [socket(listener), listener]));
102673
+ const grouped = pipe(items, filter$3((item) => item.kind === "service" || item.kind === "container"), map$10((item) => {
102674
+ const attached = byUnit[`unit:${unitKey(item.scope, serviceUnit(item))}`] ?? [];
102675
+ const bindings = pipe(item.bindings, getOrElse$1(empty$14), map$10((binding) => ({
102676
+ ...item,
102677
+ ...pipe(get$10(bySocket, socket({
102678
+ address: some$1(binding.address),
102679
+ port: some$1(binding.port),
102680
+ protocol: some$1(binding.protocol)
102681
+ })), filter$5(() => binding.address !== "container"), getOrElse$1(() => ({}))),
102682
+ address: some$1(binding.address),
102683
+ bindings: some$1([]),
102684
+ id: ItemId.make(`${item.id}:port:${binding.address}`),
102685
+ kind: "port",
102686
+ port: some$1(binding.port),
102687
+ process: some$1(item.name),
102688
+ protocol: some$1(binding.protocol),
102689
+ unit: pipe(item, liftPredicate((owner) => owner.kind === "service"), map$13(serviceUnit)),
102690
+ url: none()
102691
+ })));
102692
+ return {
102693
+ item,
102694
+ listeners: [...attached, ...bindings]
102695
+ };
102696
+ }));
102697
+ const services = fromIterable$3(pipe(grouped, filter$3((row) => row.item.kind === "service"), map$10((row) => unitKey(row.item.scope, serviceUnit(row.item)))));
102698
+ const represented = fromIterable$3(flatMap$6(grouped, (row) => pipe(row.listeners, filter$3((binding) => !contains$2(binding.address, "container")), map$10((binding) => socket({
102699
+ address: binding.address,
102700
+ port: binding.port,
102701
+ protocol: binding.protocol
102702
+ })))));
102703
+ const loose = filter$3(listeners, (listener) => !exists(listener.unit, (unit) => has$1(services, unitKey(listener.scope, unit))) && (contains$2(listener.address, "container") || !has$1(represented, socket(listener))));
102704
+ const rows = [...grouped, ...map$10(loose, (item) => ({
102705
+ item,
102706
+ listeners: [item]
102707
+ }))];
102708
+ const exposures = [...filter$3(items, (item) => item.kind === "exposure" && contains$2(item.owned, true)), ...filter$3(items, (item) => item.kind === "exposure" && !contains$2(item.owned, true))];
102709
+ const exposuresBySocket = pipe(exposures, map$10((item, index) => ({
102710
+ index,
102711
+ item
102712
+ })), groupBy((entry) => `${getOrElse$1(entry.item.port, constant$1(0))}`));
102713
+ const visible = pipe(rows, map$10((row) => {
102714
+ const reachable = dedupe(pipe(row.listeners, filter$3((listener) => exists(listener.port, (port) => sameSocket(listener, {
102715
+ address: `127.0.0.1:${port}`,
102716
+ port,
102717
+ protocol: "tcp"
102718
+ }))), map$10((listener) => listener.port), getSomes));
102719
+ const exposed = pipe(flatMap$6(reachable, (port) => exposuresBySocket[`${port}`] ?? []), sortWith((entry) => entry.index, Number$6), map$10((entry) => entry.item));
102720
+ return {
102721
+ ...row,
102722
+ exposures: dedupeWith([...pipe(row.item.links, getOrElse$1(empty$14), map$10((url) => ({
102723
+ ...row.item,
102724
+ id: ItemId.make(`${row.item.id}:url:${url}`),
102725
+ kind: "exposure",
102726
+ name: ExposureName.make(row.item.name),
102727
+ owned: some$1(false),
102728
+ publicAccess: some$1(true),
102729
+ url: some$1(url)
102730
+ }))), ...exposed], (a, b) => equals$1(a.url, b.url) && equals$1(a.publicAccess, b.publicAccess))
102731
+ };
102732
+ }), filter$3((row) => important(row.item) && (row.item.kind !== "port" || contains$2(row.item.http, true) && isSome(row.item.process) && !contains$2(row.item.process, "node"))));
102733
+ const linkedIds = fromIterable$3(flatMap$6(visible, (row) => map$10(row.exposures, (exposure) => exposure.id)));
102734
+ const linkedUrls = fromIterable$3(flatMap$6(visible, (row) => map$10(row.exposures, (exposure) => exposure.url)));
102735
+ const remaining = pipe(exposures, filter$3((item) => !has$1(linkedIds, item.id) && !has$1(linkedUrls, item.url)), map$10((item) => ({
102736
+ exposures: [item],
102737
+ item,
102738
+ listeners: []
102739
+ })), filter$3((row) => important(row.item)));
102740
+ return map$10([...visible, ...remaining], (row) => {
102741
+ if (row.item.kind === "container") return row;
102742
+ const candidates = ports(row.listeners);
102743
+ const hasUi = some(candidates, (candidate) => contains$2(candidate.ui, true));
102744
+ const exposedPorts = fromIterable$3(getSomes(map$10(row.exposures, (exposure) => exposure.port)));
102745
+ return {
102746
+ ...row,
102747
+ listeners: filter$3(candidates, (listener) => !hasUi || contains$2(listener.ui, true) || exists(listener.port, (port) => has$1(exposedPorts, port)))
102748
+ };
102749
+ });
102750
+ }
102751
+ function status(item) {
102752
+ if (item.kind === "port") return "listening";
102753
+ if (item.kind === "exposure" && contains$2(item.owned, true)) return "configured";
102754
+ if (item.kind === "exposure" && contains$2(item.publicAccess, true)) return "public permission";
102755
+ return item.state;
102756
+ }
102757
+ function usage(nodes) {
102758
+ return {
102759
+ cpu: pipe(nodes, map$10((node) => node.cpu), getSomes, match$6({
102760
+ onEmpty: () => none(),
102761
+ onNonEmpty: (values) => some$1(sumAll(values))
102762
+ })),
102763
+ memory: sumAll(map$10(nodes, (node) => node.memory))
102764
+ };
102765
+ }
102766
+ const byUsage = pipe(flip$3(Number$6), mapInput((node) => node.memory), combine$3(mapInput(makeOrder(flip$3(Number$6)), (node) => node.cpu)));
102767
+ function settle(children, appMemory) {
102768
+ return pipe(children, sort(byUsage), map$10((node) => ({
102769
+ ...node,
102770
+ small: node.memory < appMemory * .02 && !exists(node.cpu, (cpu) => cpu >= .5)
102771
+ })));
102772
+ }
102773
+ function sameLabel(first, second) {
102774
+ return first.name === second.name && first.detail === second.detail;
102775
+ }
102776
+ function absorb(label, children) {
102777
+ const [matching, other] = partition(children, fromPredicate((child) => sameLabel(child.label, label)));
102778
+ if (isArrayEmpty(matching)) return children;
102779
+ return [...other, ...absorb(label, flatMap$6(matching, (child) => child.children))];
102780
+ }
102781
+ function fold(node) {
102782
+ return {
102783
+ ...node,
102784
+ children: absorb(node.label, map$10(node.children, fold))
102785
+ };
102786
+ }
102787
+ function processTree(rows) {
102788
+ const pids = fromIterable(map$10(rows, (row) => row.pid));
102789
+ const children = groupBy(rows, (row) => String$9(row.parent));
102790
+ const visited = empty$3();
102791
+ function build(row) {
102792
+ add$1(visited, row.pid);
102793
+ const below = pipe(get$14(children, `${row.pid}`), getOrElse$1(empty$14), filter$3((child) => !has(visited, child.pid)), map$10(build));
102794
+ const self = {
102795
+ children: [],
102796
+ cpu: row.cpu,
102797
+ label: row.label,
102798
+ memory: row.memory,
102799
+ pid: row.pid,
102800
+ small: false
102801
+ };
102802
+ return {
102803
+ ...self,
102804
+ ...usage([self, ...below]),
102805
+ children: below
102806
+ };
102807
+ }
102808
+ const roots = pipe(filter$3(rows, (row) => !has(pids, row.parent)), match$6({
102809
+ onEmpty: () => take$3(rows, 1),
102810
+ onNonEmpty: identity
102811
+ }), map$10((node) => fold(build(node))));
102812
+ const appMemory = usage(roots).memory;
102813
+ function place(node) {
102814
+ return {
102815
+ ...node,
102816
+ children: settle(map$10(node.children, place), appMemory)
102817
+ };
102818
+ }
102819
+ return settle(map$10(roots, place), appMemory);
102820
+ }
102821
+ function errorsOf(sources) {
102822
+ return filterMap(sources, fromPredicateOption((source) => map$13(source.error, (error) => `${source.name}: ${error}`)));
102823
+ }
102824
+ function portsOf(row) {
102825
+ return pipe([...row.listeners, ...row.exposures], filter$3((item) => !contains$2(item.address, "container")), map$10((item) => item.port), getSomes, dedupe, sort(Number$6));
102826
+ }
102827
+ function failureOf(item) {
102828
+ if (item.health === "quiet") return {
102829
+ failure: none(),
102830
+ since: none()
102831
+ };
102832
+ return {
102833
+ failure: some$1(match$8(item.failure, {
102834
+ onNone: () => status(item),
102835
+ onSome: (stop) => stop.reason
102836
+ })),
102837
+ since: flatMap$8(item.failure, (failure) => failure.at)
102838
+ };
102839
+ }
102840
+ function summaryOf(node) {
102841
+ return {
102842
+ children: pipe(node.children, liftPredicate(isReadonlyArrayNonEmpty), map$13((children) => map$10(children, summaryOf))),
102843
+ cpu: map$13(node.cpu, (cpu) => round(cpu, 1)),
102844
+ detail: liftPredicate(node.label.detail, isNonEmpty$1),
102845
+ mib: round(node.memory / 1024 ** 2, 0),
102846
+ name: node.label.name
102847
+ };
102848
+ }
102849
+ function appOf(row, withProcesses) {
102850
+ const reachable = portsOf(row);
102851
+ const url = flatMap$8(head(row.exposures), (exposure) => exposure.url);
102852
+ return {
102853
+ ...failureOf(row.item),
102854
+ id: row.item.id,
102855
+ name: workloadName(row.item),
102856
+ ports: liftPredicate(reachable, isReadonlyArrayNonEmpty),
102857
+ processes: pipe(row.item.processes, filter$5((processes) => withProcesses && isReadonlyArrayNonEmpty(processes)), map$13((processes) => map$10(processTree(processes), summaryOf))),
102858
+ state: row.item.state,
102859
+ url
102860
+ };
102861
+ }
102862
+ function matches(row, app) {
102863
+ const needle = toLowerCase(app);
102864
+ return some([
102865
+ workloadName(row.item),
102866
+ row.item.name,
102867
+ ...toArray(row.item.unit)
102868
+ ], (name) => includes(needle)(toLowerCase(name)));
102869
+ }
102870
+ function rank(row) {
102871
+ if (row.item.health === "error") return 0;
102872
+ if (row.item.health === "warning") return 1;
102873
+ return 2;
102874
+ }
102875
+ const rowUsageOrder = mapInput(flip$3(Number$6), (row) => pipe(getOrElse$1(row.item.processes, empty$14), map$10((process) => process.memory), sumAll));
102876
+ const appOrder = pipe(Number$6, mapInput(rank), combine$3(rowUsageOrder));
102877
+ const jobOrder = pipe(Number$6, mapInput(rank), combine$3(mapInput(makeOrder(Order$2), (row) => row.item.next)));
102878
+ function listApps(snapshot, input) {
102879
+ const app = filter$5(input.app, isNonEmpty$1);
102880
+ const onlyFailing = contains$2(input.failing, true);
102881
+ const rows = workloads(snapshot.items);
102882
+ const apps = pipe(filter$3(rows, (row) => (row.item.kind === "service" || row.item.kind === "container") && !contains$2(row.item.scheduled, true) && !exists(app, (query) => !matches(row, query)) && (!onlyFailing || row.item.health !== "quiet")), sort(appOrder), map$10((row) => appOf(row, isSome(app))));
102883
+ const jobs = pipe(filter$3(rows, (row) => contains$2(row.item.scheduled, true) && (!onlyFailing || row.item.health !== "quiet")), sort(jobOrder), map$10((row) => ({
102884
+ ...failureOf(row.item),
102885
+ id: row.item.id,
102886
+ name: JobName.make(workloadName(row.item)),
102887
+ next: row.item.next,
102888
+ running: row.item.running
102889
+ })));
102890
+ const exposures = pipe(snapshot.items, flatMap$6((item) => {
102891
+ if (item.kind !== "exposure" || onlyFailing && item.health === "quiet" || !important(item)) return [];
102892
+ return toArray(map$13(item.url, (url) => ({
102893
+ access: pipe(item.publicAccess, contains$2(true), match({
102894
+ onFalse: constant$1("tailnet"),
102895
+ onTrue: constant$1("public")
102896
+ })),
102897
+ failure: failureOf(item).failure,
102898
+ id: item.id,
102899
+ name: ExposureName.make(item.name),
102900
+ port: item.port,
102901
+ url
102902
+ })));
102903
+ }), sort(mapInput(String$10, (exposure) => exposure.url)));
102904
+ return {
102905
+ apps,
102906
+ errors: liftPredicate(errorsOf(snapshot.sources), isReadonlyArrayNonEmpty),
102907
+ exposures: liftPredicate(exposures, isReadonlyArrayNonEmpty),
102908
+ jobs: liftPredicate(jobs, isReadonlyArrayNonEmpty)
102909
+ };
102910
+ }
102911
+ function ownerNames(snapshot) {
102912
+ return pipe(snapshot.items, filter$3((item) => item.kind === "service" || item.kind === "container"), fromIterableWith((item) => [itemOwner(item), workloadName(item)]));
102913
+ }
102914
+ function requestOf(item) {
102915
+ return {
102916
+ name: UnitId.make(item.name),
102917
+ scope: getOrElse$1(item.scope, constant$1("system"))
102918
+ };
102919
+ }
102920
+ const jobRequest = fnUntraced(function* (snapshot, input) {
102921
+ return yield* pipe(workloads(snapshot.items), findFirst((row) => contains$2(row.item.scheduled, true) && row.item.id === input.id), match$8({
102922
+ onNone: () => fail$7(DeployError.make({ message: `No scheduled job has the id ${input.id}; list_apps shows the jobs.` })),
102923
+ onSome: (row) => succeed$5(requestOf(row.item))
102924
+ }));
102925
+ });
103538
102926
  // src/services/inventory/lib/processes.ts
103539
102927
  const PROCESS_INTERVAL = seconds(2);
103540
102928
  function processStatus(status) {
103541
- const values = pipe(trim(status), split$1("\n"), filterMap(fromPredicateOption((line) => map$13(indexOf(":")(line), (at) => [slice(0, at)(line), trim(slice(at + 1)(line))]))), fromEntries);
102929
+ const values = pipe(trim(status), split("\n"), filterMap(fromPredicateOption((line) => map$13(indexOf(":")(line), (at) => [slice(0, at)(line), trim(slice(at + 1)(line))]))), fromEntries);
103542
102930
  function field(name) {
103543
102931
  return pipe(get$14(values, name), filter$5(isNonEmpty$1), getOrUndefined$2);
103544
102932
  }
103545
102933
  return {
103546
- memory: decodeSync(ResidentMemoryFromKiB)(split$1(values["VmRSS"] ?? "", /\s+/u)[0] || "0"),
102934
+ memory: decodeSync(ResidentMemoryFromKiB)(split(values["VmRSS"] ?? "", /\s+/u)[0] || "0"),
103547
102935
  name: values["Name"] ?? "",
103548
102936
  parent: decodeUnknownSync(ProcessIdFromString)(field("PPid")),
103549
102937
  pid: decodeUnknownSync(ProcessIdFromString)(field("Pid"))
103550
102938
  };
103551
102939
  }
103552
- function commandArgs(cmdline) {
103553
- return maskArguments(pipe(cmdline, split$1("\0"), filter$3(isNonEmpty$1), take$3(40)));
103554
- }
103555
102940
  const processes = gen(function* () {
103556
102941
  const fs = yield* FileSystem;
103557
102942
  const stat = yield* fs.readFileString("/proc/stat");
103558
- const counts = yield* decodeEffect(CpuTicks)(pipe(trim(split$1(stat, "\n")[0]), split$1(/\s+/u), drop$1(1), take$3(8)));
102943
+ const counts = yield* decodeEffect(CpuTicks)(pipe(trim(split(stat, "\n")[0]), split(/\s+/u), drop$1(1), take$3(8)));
103559
102944
  const total = millis(sumAll(counts) * 10);
103560
102945
  return {
103561
102946
  records: yield* pipe(yield* fs.readDirectory("/proc"), filter$3((name) => isSome(match$2(/^[0-9]+$/u)(name))), forEach$1((pid) => option$1(gen(function* () {
103562
102947
  const status = yield* fs.readFileString(`/proc/${pid}/status`);
103563
102948
  const processStat = yield* fs.readFileString(`/proc/${pid}/stat`);
103564
102949
  const cwd = yield* option$1(fs.readLink(`/proc/${pid}/cwd`));
103565
- const command = map$13(yield* option$1(fs.readFileString(`/proc/${pid}/cmdline`)), commandArgs);
103566
- const fields = split$1(slice((yield* fromOption(lastIndexOf(")")(processStat))) + 2)(processStat), /\s+/u);
102950
+ const command = map$13(yield* option$1(fs.readFileString(`/proc/${pid}/cmdline`)), (cmdline) => maskArguments(pipe(cmdline, split("\0"), filter$3(isNonEmpty$1), take$3(40))));
102951
+ const fields = split(slice((yield* fromOption(lastIndexOf(")")(processStat))) + 2)(processStat), /\s+/u);
103567
102952
  const parsed = yield* try_({
103568
102953
  catch: (cause) => DeployError.make({
103569
102954
  cause,
@@ -103621,61 +103006,6 @@ function processReadings(current, previous) {
103621
103006
  readings: processUsage(current, map$13(previous, (cached) => cached.baseline))
103622
103007
  };
103623
103008
  }
103624
- function launchdRows(text) {
103625
- return getSomes(pipe(text, split$1("\n"), map$10((line) => flatMap$8(match$2(/^\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) => map$13(all$5({
103626
- memory: decodeOption(ResidentMemoryFromKiB)(match[3] ?? ""),
103627
- parent: decodeOption(ProcessIdFromString)(match[2] ?? ""),
103628
- pid: decodeOption(ProcessIdFromString)(match[1] ?? "")
103629
- }), (fields) => ({
103630
- ...fields,
103631
- args: match[6] ?? "",
103632
- cpu: match[4] ?? "",
103633
- start: match[5] ?? ""
103634
- }))))));
103635
- }
103636
- function launchdStarts(text) {
103637
- return fromIterable$5(map$10(launchdRows(text), (row) => [row.pid, row.start]));
103638
- }
103639
- function launchdExecutables(text) {
103640
- return fromIterable$5(pipe(text, split$1("\n"), map$10((line) => flatMap$8(match$2(/^\s*([0-9]+)\s+(\/.*\S)\s*$/u)(line), (match) => map$13(decodeOption(ProcessIdFromString)(match[1] ?? ""), (pid) => [pid, match[2] ?? ""]))), getSomes));
103641
- }
103642
- function launchdProcesses(text, agents, executables) {
103643
- const rows = launchdRows(text);
103644
- const parents = fromIterable$5(map$10(rows, (row) => [row.pid, row.parent]));
103645
- function agent(pid, visited = empty$3()) {
103646
- if (has(visited, pid)) return none();
103647
- add$1(visited, pid);
103648
- return pipe(agents, get$10(pid), orElse$3(() => pipe(parents, get$10(pid), flatMap$8((parent) => agent(parent, visited)))));
103649
- }
103650
- return getSomes(map$10(rows, (row) => flatMap$8(agent(row.pid), (unit) => map$13(all$5({
103651
- start: make$74(row.start),
103652
- ticks: pipe(match$2(/^(?:([0-9]+):)?([0-9]+):([0-9]+(?:\.[0-9]+)?)$/u)(row.cpu), flatMap$8((match) => decodeOption(CpuTime)({
103653
- 1: match[1],
103654
- 2: match[2] ?? "",
103655
- 3: match[3] ?? ""
103656
- })), map$13((fields) => pipe(hours(getOrElse$1(fields[1], constant$1(0))), sum(minutes(fields[2])), sum(seconds(fields[3])))), filter$5(isFinite$1))
103657
- }), (times) => {
103658
- const args = trim(row.args);
103659
- const command = commandArgs(pipe(executables, get$10(row.pid), filter$5((path) => startsWith(path)(args)), match$8({
103660
- onNone: () => pipe(args, split$1(/\s+/u), join$3("\0")),
103661
- onSome: (path) => pipe(slice(path.length)(args), trim, split$1(/\s+/u), prepend$1(path), join$3("\0"))
103662
- })));
103663
- return {
103664
- owner: some$1(AppId.make(`service:user:${unit}`)),
103665
- process: Process.make({
103666
- cpu: none(),
103667
- label: commandLabel(command, none()),
103668
- memory: row.memory,
103669
- name: pipe(head(command), flatMap$8((head) => last(split$1(head, "/"))), getOrElse$1(constant$1(""))),
103670
- parent: row.parent,
103671
- pid: row.pid
103672
- }),
103673
- start: times.start,
103674
- ticks: times.ticks,
103675
- unit
103676
- };
103677
- }))));
103678
- }
103679
103009
  function attachProcesses(items, records) {
103680
103010
  const owners = groupBy(getSomes(map$10(records, (record) => map$13(record.owner, (owner) => ({
103681
103011
  owner,
@@ -103690,15 +103020,12 @@ function attachProcesses(items, records) {
103690
103020
  }));
103691
103021
  }
103692
103022
  // src/services/inventory/lib/sockets.ts
103693
- function portOf(address) {
103694
- return parse$2(lastNonEmpty(split$1(address, ":")));
103695
- }
103696
103023
  function socketLine(line) {
103697
- const fields = split$1(trim(line), /\s+/u);
103024
+ const fields = split(trim(line), /\s+/u);
103698
103025
  const address = fields[4] ?? "";
103699
103026
  const state = fields[1] ?? "";
103700
103027
  if (!contains$1(["tcp", "udp"], fields[0]) || !isNonEmpty$1(state) || !isNonEmpty$1(address)) return none();
103701
- return map$13(portOf(address), (port) => ({
103028
+ return map$13(parse$2(lastNonEmpty(split(address, ":"))), (port) => ({
103702
103029
  address,
103703
103030
  port,
103704
103031
  process: flatMap$8(match$2(/users:\(\("(.+?)",pid=([0-9]+)/u)(line), (match) => map$13(decodeOption(ProcessIdFromString)(match[2] ?? ""), (pid) => ({
@@ -103709,95 +103036,6 @@ function socketLine(line) {
103709
103036
  state
103710
103037
  }));
103711
103038
  }
103712
- function lsofSocket(file) {
103713
- if (includes("->")(file.address) || !contains$1(["TCP", "UDP"], file.protocol)) return none();
103714
- const address = replace(/^\*:/u, match(file.type === "IPv4", {
103715
- onFalse: constant$1("*:"),
103716
- onTrue: constant$1("0.0.0.0:")
103717
- }))(file.address);
103718
- return flatMap$8(file.pid, (pid) => map$13(portOf(address), (port) => ({
103719
- address,
103720
- port,
103721
- process: some$1({
103722
- name: file.process,
103723
- pid
103724
- }),
103725
- protocol: toLowerCase(file.protocol),
103726
- state: match(file.protocol === "TCP", {
103727
- onFalse: constant$1("UNCONN"),
103728
- onTrue: () => replace(/^ST=/u, "")(file.state) || "LISTEN"
103729
- })
103730
- })));
103731
- }
103732
- function lsofSockets(text) {
103733
- const empty = {
103734
- address: "",
103735
- pid: none(),
103736
- process: "",
103737
- protocol: "",
103738
- state: "",
103739
- type: ""
103740
- };
103741
- const scanned = pipe(text, split$1("\n"), reduce({
103742
- file: empty,
103743
- sockets: empty$14()
103744
- }, (scan, line) => {
103745
- const value = slice(1)(line);
103746
- const flushed = [...scan.sockets, ...toArray(lsofSocket(scan.file))];
103747
- if (startsWith("p")(line)) return {
103748
- file: {
103749
- ...empty,
103750
- pid: decodeOption(ProcessIdFromString)(value)
103751
- },
103752
- sockets: flushed
103753
- };
103754
- if (startsWith("c")(line)) return {
103755
- ...scan,
103756
- file: {
103757
- ...scan.file,
103758
- process: value
103759
- }
103760
- };
103761
- if (startsWith("f")(line)) return {
103762
- file: {
103763
- ...empty,
103764
- pid: scan.file.pid,
103765
- process: scan.file.process
103766
- },
103767
- sockets: flushed
103768
- };
103769
- if (startsWith("t")(line)) return {
103770
- ...scan,
103771
- file: {
103772
- ...scan.file,
103773
- type: value
103774
- }
103775
- };
103776
- if (startsWith("P")(line)) return {
103777
- ...scan,
103778
- file: {
103779
- ...scan.file,
103780
- protocol: value
103781
- }
103782
- };
103783
- if (startsWith("n")(line)) return {
103784
- ...scan,
103785
- file: {
103786
- ...scan.file,
103787
- address: value
103788
- }
103789
- };
103790
- if (startsWith("TST=")(line)) return {
103791
- ...scan,
103792
- file: {
103793
- ...scan.file,
103794
- state: value
103795
- }
103796
- };
103797
- return scan;
103798
- }));
103799
- return dedupeWith([...scanned.sockets, ...toArray(lsofSocket(scanned.file))], (a, b) => a.protocol === b.protocol && a.address === b.address);
103800
- }
103801
103039
  function socketUnit(cgroup) {
103802
103040
  return map$13(findLast$1(matchAll(/\/([^/]+\.service)(?=\/|\n|$)/gu)(cgroup), constTrue), (match$10) => ({
103803
103041
  scope: match(isSome(match$2(/\/user@[0-9]+\.service\/.*\.service(?:\/|\n|$)/u)(cgroup)), {
@@ -103817,7 +103055,7 @@ function probeSocket(listener, process) {
103817
103055
  return listener.protocol === "tcp" && listener.port >= 1024 && ipv4Reachable(listener.address) && isNone(match$2(/^(?:postgres|redis|ssh|cloudflared|tailscaled|caddy)$/u)(process));
103818
103056
  }
103819
103057
  // src/services/inventory/service.ts
103820
- function portItems(sockets, worker, probe, source) {
103058
+ function portItems(sockets, probe, source) {
103821
103059
  return gen(function* () {
103822
103060
  const metadata = fromIterable$5(yield* pipe(getSomes(map$10(sockets, (socket) => socket.process)), dedupeWith((left, right) => left.pid === right.pid), forEach$1(fnUntraced(function* (process) {
103823
103061
  const start = yield* source.start(process.pid);
@@ -103860,7 +103098,7 @@ function portItems(sockets, worker, probe, source) {
103860
103098
  address: some$1(socket.address),
103861
103099
  detail: `${socket.address} · ${getOrElse$1(process, constant$1("process unavailable"))}`,
103862
103100
  http: some$1(exists(response, (value) => value.http)),
103863
- id: ItemId.make(`${worker}:port:${socket.protocol}:${socket.address}`),
103101
+ id: ItemId.make(`port:${socket.protocol}:${socket.address}`),
103864
103102
  kind: "port",
103865
103103
  name: socket.address,
103866
103104
  port: some$1(socket.port),
@@ -103873,8 +103111,7 @@ function portItems(sockets, worker, probe, source) {
103873
103111
  state: socket.state,
103874
103112
  ui: some$1(exists(response, (value) => value.ui)),
103875
103113
  unit: map$13(owner, (found) => found.unit),
103876
- url: none(),
103877
- worker
103114
+ url: none()
103878
103115
  });
103879
103116
  }), { concurrency: 8 });
103880
103117
  });
@@ -103898,7 +103135,7 @@ function collect(name, effect) {
103898
103135
  }));
103899
103136
  }
103900
103137
  function containerRows(listing) {
103901
- return pipe(listing, split$1("\n"), filter$3(isNonEmpty$1), map$10((line) => decodeOption(fromJsonString(Container))(line)), getSomes);
103138
+ return pipe(listing, split("\n"), filter$3(isNonEmpty$1), map$10((line) => decodeOption(fromJsonString(Container))(line)), getSomes);
103902
103139
  }
103903
103140
  var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/service/Inventory") {
103904
103141
  static layer = effect(this, gen(function* () {
@@ -103910,14 +103147,12 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
103910
103147
  function command(name, args, timeout = "10 seconds") {
103911
103148
  return pipe(executeProcess(name, args, { timeout }), mapError$2((cause) => DeployError.make({
103912
103149
  cause,
103913
- message: `Could not run ${name}; inspect the worker's process logs.`
103150
+ message: `Could not run ${name}; inspect Deploy's process logs.`
103914
103151
  })), provideService$2(ChildProcessSpawner, spawner));
103915
103152
  }
103916
103153
  function systemctlRows(args, row) {
103917
103154
  return pipe(command("systemctl", args), flatMap$3(decodeUnknownEffect(fromJsonString(ArraySchema(Unknown)))), map$7((rows) => getSomes(map$10(rows, (item) => decodeUnknownOption(row)(item)))));
103918
103155
  }
103919
- const worker = yield* decodeEffect(WorkerId)(hostname());
103920
- const selfProcess = yield* decodeEffect(ProcessId)(pid);
103921
103156
  const processState = yield* make$49(none());
103922
103157
  function head(port) {
103923
103158
  return pipe(http.head(`http://127.0.0.1:${port}/`, { headers: toHeaders(new NativeSpan({
@@ -103988,7 +103223,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
103988
103223
  onFalse: constant$1("quiet"),
103989
103224
  onTrue: constant$1("error")
103990
103225
  }),
103991
- id: ItemId.make(`${worker}:${scope}:${row.unit}`),
103226
+ id: ItemId.make(`${scope}:${row.unit}`),
103992
103227
  kind: "service",
103993
103228
  name: row.unit,
103994
103229
  next: flatten$6(get$10(scheduled, row.unit)),
@@ -103999,8 +103234,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
103999
103234
  onFalse: () => `${row.active} · ${row.sub}`,
104000
103235
  onTrue: () => row.sub
104001
103236
  }),
104002
- url: none(),
104003
- worker
103237
+ url: none()
104004
103238
  }));
104005
103239
  });
104006
103240
  const docker = pipe(command("docker", [
@@ -104034,7 +103268,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104034
103268
  }),
104035
103269
  onTrue: constant$1("error")
104036
103270
  }),
104037
- id: ItemId.make(`${worker}:docker:${row.ID}`),
103271
+ id: ItemId.make(`docker:${row.ID}`),
104038
103272
  kind: "container",
104039
103273
  links: some$1(dedupe(map$10(fromIterable$8(matchAll(/Host\(`([^`]+)`\)/gu)(getOrElse$1(row.Labels, constant$1("")))), (match) => `https://${match[1]}`))),
104040
103274
  name: row.Names,
@@ -104042,174 +103276,27 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104042
103276
  onFalse: () => row.State,
104043
103277
  onTrue: constant$1("unhealthy")
104044
103278
  }),
104045
- url: none(),
104046
- worker
103279
+ url: none()
104047
103280
  }))));
104048
- const linux = succeed$5({
104049
- processes: pipe(processes, provideService$2(FileSystem, fs), mapError$2((cause) => DeployError.make({
104050
- cause,
104051
- message: "The worker processes could not be read."
104052
- }))),
104053
- sources: [
104054
- collect("User services", units(false)),
104055
- collect("System services", units(true)),
104056
- collect("Docker", docker),
104057
- collect("Listening ports", flatMap$3(command("ss", ["-H", "-lntup"]), (text) => portItems(getSomes(pipe(trim(text), split$1("\n"), map$10(socketLine))), worker, probe, {
104058
- cwd: (processId) => option$1(fs.readLink(`/proc/${processId}/cwd`)),
104059
- owner: (processId) => map$7(option$1(fs.readFileString(`/proc/${processId}/cgroup`)), (cgroup) => socketUnit(getOrElse$1(cgroup, constant$1("")))),
104060
- start: (processId) => map$7(option$1(fs.readFileString(`/proc/${processId}/stat`)), flatMap$8((stat) => flatMap$8(lastIndexOf(")")(stat), (at) => pipe(slice(at + 2)(stat), split$1(/\s+/u), get$13(19)))))
104061
- })))
104062
- ]
104063
- });
104064
- const bundleNames = yield* make$64({
104065
- capacity: Infinity,
104066
- lookup: fnUntraced(function* (bundle) {
104067
- return yield* pipe(command("/usr/bin/plutil", [
104068
- "-convert",
104069
- "json",
104070
- "-o",
104071
- "-",
104072
- `${bundle}/Contents/Info.plist`
104073
- ], "2 seconds"), flatMap$3(decodeEffect(fromJsonString(Struct$2({
104074
- CFBundleDisplayName: optionalKey(Unknown),
104075
- CFBundleName: optionalKey(Unknown)
104076
- })))), map$7((fields) => pipe([fields.CFBundleDisplayName, fields.CFBundleName], filter$3(isString$1), map$10(trim), findFirst(isNonEmpty$1))), option$1, map$7(flatten$6));
104077
- })
104078
- });
104079
- const darwin = gen(function* () {
104080
- const namedAgents = gen(function* () {
104081
- return getSomes(yield* forEach$1(launchAgents(yield* command("launchctl", ["list"])), fnUntraced(function* (agent) {
104082
- if (startsWith("deslop-")(agent.label)) return some$1(agent);
104083
- const program = flatMap$8(yield* option$1(command("launchctl", ["print", `gui/${userInfo().uid}/${agent.label}`], "2 seconds")), launchProgram);
104084
- if (exists(program, systemProgram)) return none();
104085
- return yield* pipe(program, flatMap$8(applicationBundle), match$8({
104086
- onNone: () => succeedSome(agent),
104087
- onSome: fnUntraced(function* (bundle) {
104088
- const name = yield* get$8(bundleNames, bundle);
104089
- return some$1({
104090
- ...agent,
104091
- bundle: some$1(bundle),
104092
- name: getOrElse$1(name, () => pipe(bundle, split$1("/"), last, getOrElse$1(constant$1("")), slice(0, -4)))
104093
- });
104094
- })
104095
- }));
104096
- }), { concurrency: 8 }));
104097
- });
104098
- const collected = yield* all$2({
104099
- agents: result$1(timeout(namedAgents, "8 seconds")),
104100
- applications: result$1(command("/usr/bin/lsappinfo", ["list"])),
104101
- executables: result$1(command("env", [
104102
- "LC_ALL=C",
104103
- "ps",
104104
- "-axww",
104105
- "-o",
104106
- "pid=,comm="
104107
- ])),
104108
- table: result$1(command("env", [
104109
- "LC_ALL=C",
104110
- "ps",
104111
- "-axww",
104112
- "-o",
104113
- "pid=,ppid=,rss=,time=,lstart=,args="
104114
- ]))
104115
- }, { concurrency: "unbounded" });
104116
- const launchd = {
104117
- ...collected,
104118
- applications: map$12(collected.applications, (text) => dockApplications(text, pipe(getOrElse(collected.agents, () => []), map$10((agent) => agent.bundle), getSomes)))
104119
- };
104120
- const time = yield* now;
104121
- const total = pipe(cpus(), flatMap$6((cpu) => values$2(cpu.times)), sumAll, millis);
104122
- const apps = macApplications(getOrElse(launchd.agents, () => []), getOrElse(launchd.applications, () => []));
104123
- function appItems(found) {
104124
- return pipe(found, dedupeWith((left, right) => left.label === right.label), map$10((app) => InventoryItem.make({
104125
- active: true,
104126
- detail: app.detail,
104127
- id: ItemId.make(`${worker}:user:${app.label}`),
104128
- kind: "service",
104129
- name: UnitId.make(app.name),
104130
- running: true,
104131
- scope: some$1("user"),
104132
- state: "running",
104133
- unit: some$1(app.label),
104134
- url: none(),
104135
- worker
104136
- })));
104137
- }
104138
- const records = map$12(launchd.table, (text) => {
104139
- const agents = fromIterable$5(map$10(apps, (app) => [app.pid, app.label]));
104140
- return filter$3(launchdProcesses(text, agents, pipe(launchd.executables, map$12(launchdExecutables), getOrElse(empty$10))), (record) => record.process.pid === selfProcess || !pipe(agents, get$10(selfProcess), contains$2(record.unit)));
104141
- });
104142
- const owned = getOrElse(records, empty$14);
104143
- const starts = pipe(launchd.table, map$12(launchdStarts), getOrElse(empty$10));
104144
- return {
104145
- processes: map$7(fromResult(records), (found) => ({
104146
- records: found,
104147
- time,
104148
- total
104149
- })),
104150
- sources: [
104151
- collect("Launch agents", map$7(fromResult(launchd.agents), (agents) => [...appItems(filter$3(apps, (app) => app.detail === "user · launch agent")), ...pipe(agents, filter$3((agent) => match$8(agent.pid, {
104152
- onNone: () => exists(agent.status, (status) => status !== 0),
104153
- onSome: constFalse$1
104154
- })), map$10((agent) => InventoryItem.make({
104155
- active: isSome(agent.pid),
104156
- detail: agent.detail,
104157
- failure: pipe(agent.status, filter$5((status) => isNone(agent.pid) && status !== 0), map$13((status) => ({
104158
- at: none(),
104159
- reason: exitFailure(status)
104160
- }))),
104161
- health: match(isNone(agent.pid), {
104162
- onFalse: constant$1("quiet"),
104163
- onTrue: constant$1("error")
104164
- }),
104165
- id: ItemId.make(`${worker}:user:${agent.label}`),
104166
- kind: "service",
104167
- name: UnitId.make(agent.name),
104168
- running: isSome(agent.pid),
104169
- scope: some$1("user"),
104170
- state: match$8(agent.pid, {
104171
- onNone: constant$1("failed · failed"),
104172
- onSome: constant$1("running")
104173
- }),
104174
- url: none(),
104175
- worker
104176
- })))])),
104177
- collect("Applications", map$7(fromResult(launchd.applications), () => appItems(filter$3(apps, (app) => app.detail === "user · application")))),
104178
- collect("Listening ports", flatMap$3(command("lsof", [
104179
- "-nP",
104180
- "+c0",
104181
- "-iTCP",
104182
- "-sTCP:LISTEN",
104183
- "-iUDP",
104184
- "-F",
104185
- "pcftPnT"
104186
- ]), (text) => portItems(lsofSockets(text), worker, probe, {
104187
- cwd: fnUntraced(function* (processId) {
104188
- return pipe(yield* option$1(command("lsof", [
104189
- "-nP",
104190
- "-a",
104191
- "-p",
104192
- `${processId}`,
104193
- "-d",
104194
- "cwd",
104195
- "-Fn"
104196
- ], "2 seconds")), getOrElse$1(constant$1("")), split$1("\n"), findFirst(startsWith("n")), map$13(slice(1)));
104197
- }),
104198
- owner: (processId) => succeed$5(pipe(owned, findFirst((record) => record.process.pid === processId), map$13((record) => ({
104199
- scope: "user",
104200
- unit: record.unit
104201
- })))),
104202
- start: (processId) => succeed$5(get$10(starts, processId))
104203
- })))
104204
- ]
104205
- };
104206
- });
103281
+ const processTable = pipe(processes, provideService$2(FileSystem, fs), mapError$2((cause) => DeployError.make({
103282
+ cause,
103283
+ message: "The processes could not be read."
103284
+ })));
103285
+ const machineSources = [
103286
+ collect("User services", units(false)),
103287
+ collect("System services", units(true)),
103288
+ collect("Docker", docker),
103289
+ collect("Listening ports", flatMap$3(command("ss", ["-H", "-lntup"]), (text) => portItems(getSomes(pipe(trim(text), split("\n"), map$10(socketLine))), probe, {
103290
+ cwd: (processId) => option$1(fs.readLink(`/proc/${processId}/cwd`)),
103291
+ owner: (processId) => map$7(option$1(fs.readFileString(`/proc/${processId}/cgroup`)), (cgroup) => socketUnit(getOrElse$1(cgroup, constant$1("")))),
103292
+ start: (processId) => map$7(option$1(fs.readFileString(`/proc/${processId}/stat`)), flatMap$8((stat) => flatMap$8(lastIndexOf(")")(stat), (at) => pipe(slice(at + 2)(stat), split(/\s+/u), get$13(19)))))
103293
+ })))
103294
+ ];
104207
103295
  const start = fnUntraced(function* (input) {
104208
103296
  yield* annotateCurrentSpan({
104209
103297
  job: input.name,
104210
103298
  scope: input.scope
104211
103299
  });
104212
- if (platform === "darwin") return yield* DeployError.make({ message: `${input.name} is not started by a timer` });
104213
103300
  const timers = yield* flatMap$3(command("systemctl", [
104214
103301
  ...match(input.scope === "system", {
104215
103302
  onFalse: () => ["--user"],
@@ -104244,11 +103331,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104244
103331
  });
104245
103332
  }));
104246
103333
  const collectSnapshot = withSpan(scoped(gen(function* () {
104247
- const machine = yield* match(platform === "darwin", {
104248
- onFalse: () => linux,
104249
- onTrue: () => darwin
104250
- });
104251
- const processing = yield* pipe(machine.processes, flatMap$3((current) => modify$1(processState, (previous) => {
103334
+ const processing = yield* pipe(processTable, flatMap$3((current) => modify$1(processState, (previous) => {
104252
103335
  const next = processReadings(current, previous);
104253
103336
  return [next.readings, some$1(next)];
104254
103337
  })), timeout(seconds(3)), match$1({
@@ -104262,11 +103345,11 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104262
103345
  })
104263
103346
  }), forkScoped);
104264
103347
  const sources = yield* all$2([
104265
- ...machine.sources,
103348
+ ...machineSources,
104266
103349
  collect("Tailnet", pipe(command("tailscale", ["status", "--json"]), flatMap$3(decodeEffect(fromJsonString(TailnetStatus))), map$7((status) => map$10(toArray(status.Self), (peer) => InventoryItem.make({
104267
103350
  detail: `${peer.OS} · ${join$3(peer.TailscaleIPs, ", ")}`,
104268
103351
  hostname: some$1(replace(/\.$/u, "")(peer.DNSName)),
104269
- id: ItemId.make(`${worker}:peer:${peer.DNSName}`),
103352
+ id: ItemId.make(`peer:${peer.DNSName}`),
104270
103353
  kind: "peer",
104271
103354
  name: peer.HostName,
104272
103355
  self: some$1(true),
@@ -104274,8 +103357,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104274
103357
  onFalse: constant$1("offline"),
104275
103358
  onTrue: constant$1("online")
104276
103359
  }),
104277
- url: none(),
104278
- worker
103360
+ url: none()
104279
103361
  }))))),
104280
103362
  collect("Tailscale Serve", pipe(command("tailscale", [
104281
103363
  "serve",
@@ -104290,15 +103372,14 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104290
103372
  onFalse: constant$1("quiet"),
104291
103373
  onTrue: constant$1("warning")
104292
103374
  })),
104293
- id: ItemId.make(`${worker}:tailscale:${site[0]}:${handler[0]}`),
103375
+ id: ItemId.make(`tailscale:${site[0]}:${handler[0]}`),
104294
103376
  kind: "exposure",
104295
103377
  name: ExposureName.make(`${site[0]}${handler[0]}`),
104296
103378
  owned: some$1(false),
104297
103379
  port: pipe(handler[1].Proxy, flatMap$8(match$2(/^http:\/\/(?:127\.0\.0\.1|localhost):([0-9]+)/u)), flatMap$8((match) => parse$2(match[1] ?? ""))),
104298
103380
  publicAccess: some$1(exists(status.AllowFunnel, (permissions) => permissions[site[0]] === true)),
104299
103381
  state: "observed",
104300
- url: some$1(`https://${site[0]}${replace(/^\/$/u, "")(handler[0])}`),
104301
- worker
103382
+ url: some$1(`https://${site[0]}${replace(/^\/$/u, "")(handler[0])}`)
104302
103383
  }))))))
104303
103384
  ], { concurrency: "unbounded" });
104304
103385
  const collected = yield* join$2(processing);
@@ -104308,10 +103389,9 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104308
103389
  error: collected.error,
104309
103390
  name: "Processes"
104310
103391
  }],
104311
- time: yield* now,
104312
- workers: [worker]
103392
+ time: yield* now
104313
103393
  };
104314
- })), "Inventory.snapshot", { attributes: { worker } });
103394
+ })), "Inventory.snapshot");
104315
103395
  const snapshot = yield* make$44(yield* collectSnapshot);
104316
103396
  const [ensureFresh, invalidate] = yield* cachedInvalidateWithTTL(pipe(snapshot, updateEffect(() => collectSnapshot), withSpan("Inventory.refresh")), seconds(5));
104317
103397
  const refresh = andThen(invalidate, ensureFresh);
@@ -104325,6 +103405,224 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
104325
103405
  };
104326
103406
  }));
104327
103407
  };
103408
+ // src/services/proxies/service.ts
103409
+ const CADDY_ADMIN_PORT = 20219;
103410
+ function caddyConfig(rows, storage) {
103411
+ return `{\n\tadmin 127.0.0.1:${CADDY_ADMIN_PORT}\n\tgrace_period 10s\n\tpersist_config off\n\tstorage file_system {\n\t\troot ${encodeSync(fromJsonString(String$6))(storage)}\n\t}\n}\n\n${pipe(rows, filter$3((row) => row.kind === "public"), map$10((row) => `${row.hostname} {\n\tencode\n\treverse_proxy 127.0.0.1:${row.port}\n}\n`), join$3("\n"))}`;
103412
+ }
103413
+ function asDeployError$2(effect) {
103414
+ return mapError$2(effect, (cause) => DeployError.make({
103415
+ cause,
103416
+ message: "Tailscale Serve could not be read or changed; check permissions and its status"
103417
+ }));
103418
+ }
103419
+ var Proxies = class Proxies extends Service$1()("@deslop/deploy/services/proxies/service/Proxies") {
103420
+ static layer = (directory) => effect(this, gen(function* () {
103421
+ const fs = yield* FileSystem;
103422
+ const spawner = yield* ChildProcessSpawner;
103423
+ const path = yield* Path$1;
103424
+ const http = yield* HttpClient;
103425
+ yield* fs.makeDirectory(directory, {
103426
+ mode: 448,
103427
+ recursive: true
103428
+ });
103429
+ yield* flatMap$3(fs.readDirectory(directory), forEach$1((name) => match(startsWith("Caddyfile.")(name), {
103430
+ onFalse: () => void_$2,
103431
+ onTrue: () => fs.remove(path.join(directory, name), {
103432
+ force: true,
103433
+ recursive: true
103434
+ })
103435
+ }), { discard: true }));
103436
+ const caddy = pipe((yield* ToolPath)("caddy"), provideService$2(FileSystem, fs), provideService$2(Path$1, path));
103437
+ const configFile = path.join(directory, "Caddyfile");
103438
+ function run(program, args) {
103439
+ return pipe(executeProcess(program, args), provideService$2(ChildProcessSpawner, spawner), timeout(seconds(30)));
103440
+ }
103441
+ const written = fnUntraced(function* (rows) {
103442
+ const binary = yield* caddy;
103443
+ yield* fs.makeDirectory(path.join(directory, "caddy"), {
103444
+ mode: 448,
103445
+ recursive: true
103446
+ });
103447
+ const staged = yield* fs.makeTempFileScoped({
103448
+ directory,
103449
+ prefix: "Caddyfile."
103450
+ });
103451
+ yield* fs.chmod(staged, 384);
103452
+ yield* fs.writeFileString(staged, caddyConfig(rows, path.join(directory, "caddy")));
103453
+ yield* run(binary, [
103454
+ "validate",
103455
+ "--config",
103456
+ staged,
103457
+ "--adapter",
103458
+ "caddyfile"
103459
+ ]);
103460
+ return {
103461
+ binary,
103462
+ staged
103463
+ };
103464
+ });
103465
+ return Proxies.of({
103466
+ apply: fn("Proxies.apply")(function* (rows) {
103467
+ const config = yield* written(rows);
103468
+ yield* fs.rename(config.staged, configFile);
103469
+ const running = yield* pipe(run("systemctl", [
103470
+ "--user",
103471
+ "show",
103472
+ "--property=MainPID",
103473
+ "--value",
103474
+ "deslop-deploy-caddy.service"
103475
+ ]), map$7(trim), flatMap$3((pid) => match(pid === "0", {
103476
+ onFalse: () => fs.readLink(`/proc/${pid}/exe`),
103477
+ onTrue: () => succeed$5("")
103478
+ })), option$1);
103479
+ yield* pipe(installService("deploy-caddy", [
103480
+ config.binary,
103481
+ "run",
103482
+ "--config",
103483
+ configFile,
103484
+ "--adapter",
103485
+ "caddyfile"
103486
+ ], pipe(running, filter$5((current) => current === config.binary), match$8({
103487
+ onNone: constUndefined,
103488
+ onSome: () => ({ restart: false })
103489
+ }))), provideService$2(ChildProcessSpawner, spawner), provideService$2(FileSystem, fs), provideService$2(Path$1, path));
103490
+ yield* retry(run(config.binary, [
103491
+ "reload",
103492
+ "--address",
103493
+ `127.0.0.1:${CADDY_ADMIN_PORT}`,
103494
+ "--config",
103495
+ configFile,
103496
+ "--adapter",
103497
+ "caddyfile"
103498
+ ]), {
103499
+ schedule: spaced(millis(200)),
103500
+ times: 10,
103501
+ while: is$2(AppError)
103502
+ });
103503
+ }, scoped, mapError$2((cause) => DeployError.make({
103504
+ cause,
103505
+ message: "Caddy did not load the owned public exposures"
103506
+ }))),
103507
+ runtime: fn("Proxies.runtime")(function* (port) {
103508
+ return yield* pipe(http.get(`http://127.0.0.1:${port}${RUNTIME_PATH}`), flatMap$3(schemaBodyJson$1(RuntimeConfig)), timeout(seconds(2)), option$1);
103509
+ }),
103510
+ serve: fn("Proxies.serve")(function* (port) {
103511
+ yield* asDeployError$2(run("tailscale", [
103512
+ "serve",
103513
+ "--bg",
103514
+ `--https=${port}`,
103515
+ `http://127.0.0.1:${port}`
103516
+ ]));
103517
+ }),
103518
+ serveStatus: pipe(run("tailscale", [
103519
+ "serve",
103520
+ "status",
103521
+ "--json"
103522
+ ]), flatMap$3(decodeUnknownEffect(fromJsonString(Serve))), asDeployError$2),
103523
+ tailnetName: pipe(run("tailscale", ["status", "--json"]), flatMap$3(decodeEffect(fromJsonString(TailnetStatus))), map$7((status) => map$13(status.Self, (self) => replace(/\.$/u, "")(self.DNSName))), asDeployError$2),
103524
+ unserve: fn("Proxies.unserve")(function* (port) {
103525
+ yield* asDeployError$2(run("tailscale", [
103526
+ "serve",
103527
+ `--https=${port}`,
103528
+ "off"
103529
+ ]));
103530
+ }),
103531
+ validate: fn("Proxies.validate")(function* (rows) {
103532
+ yield* written(rows);
103533
+ }, scoped, mapError$2((cause) => DeployError.make({
103534
+ cause,
103535
+ message: "Caddy refused this public exposure"
103536
+ })))
103537
+ });
103538
+ }));
103539
+ };
103540
+ // src/services/exposures/lib/policy.ts
103541
+ function reservedPort(port) {
103542
+ return pipe(port, liftPredicate((candidate) => candidate === CADDY_ADMIN_PORT), map$13(constant$1("Caddy’s admin port is never published")));
103543
+ }
103544
+ function refusal(exposure, listener) {
103545
+ const reserved = reservedPort(exposure.port);
103546
+ if (isSome(reserved)) return reserved;
103547
+ return pipe(listener.runtime, map$13((runtime) => runtime.name), orElse$3(() => pipe(listener.owner, flatMap$8(match$2(/^user:deslop-([a-z0-9-]+?)(?:\.service)?$/u)), flatMap$8((match) => fromUndefinedOr(match[1])))), flatMap$8((name) => match$8(listener.runtime, {
103548
+ onNone: () => some$1(`${name} did not say how it runs; publish it once it answers`),
103549
+ onSome: (runtime) => match$8(runtime.auth, {
103550
+ onNone: () => some$1(`${name} runs without a domain, so Deploy never publishes it`),
103551
+ onSome: (auth) => {
103552
+ if (exposure.name !== name) return some$1(`Port ${exposure.port} belongs to ${name}; publish it only under the name ${name}`);
103553
+ const own = `${name}.${replace(/^https:\/\/auth\./u, "")(auth)}`;
103554
+ if (exposure.kind === "public" && exposure.hostname !== own) return some$1(`Publish ${name} only at ${own}`);
103555
+ return none();
103556
+ }
103557
+ })
103558
+ })));
103559
+ }
103560
+ function ownedConflict(owned, exposure) {
103561
+ if (some(owned, (row) => row.name === exposure.name)) return some$1("Remove the existing owned exposure, and let its removal finish, before changing it");
103562
+ if (some(owned, (row) => row.hostname === exposure.hostname && (row.kind === "public" || row.port === exposure.port))) return some$1("This hostname or port already has an owned exposure");
103563
+ return none();
103564
+ }
103565
+ function restoreRefusal(row, listener) {
103566
+ return match$8(listener.owner, {
103567
+ onNone: () => some$1(`Nothing listens on 127.0.0.1:${row.port}, so it is not published until its owner does`),
103568
+ onSome: (current) => pipe(row.owner, filter$5((saved) => saved !== current), map$13((saved) => `Port ${row.port} now belongs to ${current}, not ${saved}, so Deploy withdraws this site; it returns when ${saved} listens again`), orElse$3(() => refusal(row, listener)))
103569
+ });
103570
+ }
103571
+ // src/services/exposures/lib/reconciler.ts
103572
+ const makeReconciler = fnUntraced(function* (pass, finished, unchanged) {
103573
+ const wake = yield* sliding$1(1);
103574
+ const waiting = yield* make$49(none());
103575
+ const retry = yield* make$49(none());
103576
+ yield* pipe(gen(function* () {
103577
+ yield* match$8(yield* get$3(retry), {
103578
+ onNone: () => take$1(wake),
103579
+ onSome: (state) => raceFirst(take$1(wake), sleep(pipe(seconds(5), times(2 ** state.failed), min$2(minutes(10)))))
103580
+ });
103581
+ const served = yield* getAndSet(waiting, none());
103582
+ const exit$2 = yield* exit(pass);
103583
+ yield* forEach$1(toArray(served), (deferred) => done(deferred, exit$2), {
103584
+ concurrency: 1,
103585
+ discard: true
103586
+ });
103587
+ yield* update(retry, (state) => {
103588
+ if (isSuccess(exit$2) && finished(exit$2.value)) return none();
103589
+ const before = flatMap$8(state, (last) => last.outcome);
103590
+ const outcome = match$3(exit$2, {
103591
+ onFailure: () => before,
103592
+ onSuccess: some$1
103593
+ });
103594
+ return some$1({
103595
+ failed: pipe(state, filter$5(() => makeEquivalence$5(unchanged)(before, outcome)), match$8({
103596
+ onNone: constant$1(0),
103597
+ onSome: (last) => min$1(last.failed + 1, 7)
103598
+ })),
103599
+ outcome
103600
+ });
103601
+ });
103602
+ }), forever, forkScoped);
103603
+ return { request: gen(function* () {
103604
+ const fresh = yield* make$85();
103605
+ const deferred = yield* modify$1(waiting, (current) => match$8(current, {
103606
+ onNone: () => [fresh, some$1(fresh)],
103607
+ onSome: (pending) => [pending, current]
103608
+ }));
103609
+ yield* offer(wake, void 0);
103610
+ return yield* _await(deferred);
103611
+ }) };
103612
+ });
103613
+ // src/services/exposures/migrations.ts
103614
+ const migrations$1 = {
103615
+ "0001_exposures": flatMap$3(SqlClient, (sql) => sql`
103616
+ CREATE TABLE exposures (
103617
+ name TEXT PRIMARY KEY,
103618
+ kind TEXT NOT NULL,
103619
+ hostname TEXT NOT NULL,
103620
+ port INTEGER NOT NULL
103621
+ ) STRICT
103622
+ `),
103623
+ "0002_exposure_state": flatMap$3(SqlClient, (sql) => sql`ALTER TABLE exposures ADD COLUMN state TEXT NOT NULL DEFAULT 'active'`),
103624
+ "0003_exposure_owner": flatMap$3(SqlClient, (sql) => sql`ALTER TABLE exposures ADD COLUMN owner TEXT`)
103625
+ };
104328
103626
  // src/services/exposures/service.ts
104329
103627
  function ownsMapping(status, row) {
104330
103628
  return !exists(status.AllowFunnel, (permissions) => permissions[`${row.hostname}:${row.port}`] === true) && pipe(status.Web, flatMap$8(get$14(`${row.hostname}:${row.port}`)), exists((value) => size$4(value.Handlers) === 1 && pipe(value.Handlers, get$14("/"), flatMap$8((handler) => handler.Proxy), exists((proxy) => proxy === `http://127.0.0.1:${row.port}`))));
@@ -104340,7 +103638,7 @@ const asStorageDeployError = mapError$2((cause) => DeployError.make({
104340
103638
  cause,
104341
103639
  message: "The owned exposures could not be read or written."
104342
103640
  }));
104343
- function asDeployError$2(effect) {
103641
+ function asDeployError$1(effect) {
104344
103642
  return mapError$2(effect, (cause) => {
104345
103643
  if (is$2(DeployError)(cause)) return cause;
104346
103644
  return DeployError.make({
@@ -104353,7 +103651,6 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104353
103651
  const sql = yield* SqlClient;
104354
103652
  const proxies = yield* Proxies;
104355
103653
  const inventory = yield* Inventory;
104356
- const worker = yield* decodeEffect(WorkerId)(hostname());
104357
103654
  const listExposures = findAll({
104358
103655
  Request: Void,
104359
103656
  Result: Exposure,
@@ -104465,7 +103762,7 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104465
103762
  yield* set(problems, found);
104466
103763
  if (!isEmptyRecord(found)) yield* logWarning("Owned exposures are not yet as saved; Deploy tries again", found);
104467
103764
  return found;
104468
- }), "Exposures.reconcile", { attributes: { worker } })), isEmptyRecord, makeEquivalence$3(Equivalence$4));
103765
+ }), "Exposures.reconcile")), isEmptyRecord, makeEquivalence$3(Equivalence$4));
104469
103766
  yield* ignore$1(reconciler.request, {
104470
103767
  log: "Warn",
104471
103768
  message: "Could not reconcile owned exposures; inspect the Caddy service and the owned exposure records"
@@ -104481,11 +103778,9 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104481
103778
  yield* annotateCurrentSpan({
104482
103779
  exposure: input.name,
104483
103780
  kind: input.kind,
104484
- port: input.port,
104485
- worker
103781
+ port: input.port
104486
103782
  });
104487
103783
  if (input.kind === "public" && !input.publicAccess) return yield* DeployError.make({ message: "Explicitly confirm public access before publishing a port" });
104488
- if (input.kind === "public" && (platform !== "linux" || arch !== "x64")) return yield* DeployError.make({ message: "Public exposure needs a Linux x64 worker; expose this port to the tailnet" });
104489
103784
  yield* match$8(reservedPort(input.port), {
104490
103785
  onNone: () => void_$2,
104491
103786
  onSome: (message) => DeployError.make({ message })
@@ -104510,17 +103805,14 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104510
103805
  if (exposure.kind === "tailnet") {
104511
103806
  const status = yield* proxies.serveStatus;
104512
103807
  if (servesPort(status, exposure.port) || exists(status.AllowFunnel, (permissions) => permissions[`${exposure.hostname}:${exposure.port}`] === true)) return yield* DeployError.make({ message: "This Tailscale port or Funnel permission already exists and is not owned by Deploy" });
104513
- if (!contains$2(yield* proxies.tailnetName, exposure.hostname)) return yield* DeployError.make({ message: "Use this worker’s Tailscale DNS name; Deploy never publishes another worker’s hostname" });
103808
+ if (!contains$2(yield* proxies.tailnetName, exposure.hostname)) return yield* DeployError.make({ message: "Use this machine’s Tailscale DNS name; Deploy never publishes another machine’s hostname" });
104514
103809
  } else yield* proxies.validate([...filter$3(current, (row) => row.kind === "public" && row.state === "active"), exposure]);
104515
103810
  yield* asStorageDeployError(insertExposure(exposure));
104516
103811
  yield* settle(exposure.name, "The exposure is saved and Deploy keeps applying it");
104517
103812
  return exposureUrl(exposure);
104518
- }, withPermit(lock), asDeployError$2),
103813
+ }, withPermit(lock), asDeployError$1),
104519
103814
  hide: fn("Exposures.hide")(function* (name, _admin) {
104520
- yield* annotateCurrentSpan({
104521
- exposure: name,
104522
- worker
104523
- });
103815
+ yield* annotateCurrentSpan({ exposure: name });
104524
103816
  const exposure = yield* pipe(yield* owned, findFirst((row) => row.name === name), fromOption, mapError$2((cause) => DeployError.make({
104525
103817
  cause,
104526
103818
  message: "Deploy does not own this exposure"
@@ -104530,7 +103822,7 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104530
103822
  }
104531
103823
  yield* withPermit(passLock, asStorageDeployError(markRemoving(name)));
104532
103824
  yield* settle(name, "The removal is saved and Deploy finishes it on its own");
104533
- }, withPermit(lock), asDeployError$2),
103825
+ }, withPermit(lock), asDeployError$1),
104534
103826
  items: pipe(all$2({
104535
103827
  current: owned,
104536
103828
  failing: get$3(problems)
@@ -104546,7 +103838,7 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104546
103838
  onFalse: constant$1("quiet"),
104547
103839
  onTrue: constant$1("warning")
104548
103840
  }),
104549
- id: ItemId.make(`${worker}:exposure:${row.name}`),
103841
+ id: ItemId.make(`exposure:${row.name}`),
104550
103842
  kind: "exposure",
104551
103843
  name: row.name,
104552
103844
  owned: some$1(true),
@@ -104556,10 +103848,9 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104556
103848
  onFalse: constant$1("configured; check backend"),
104557
103849
  onTrue: constant$1("removing")
104558
103850
  }),
104559
- url: some$1(exposureUrl(row)),
104560
- worker
103851
+ url: some$1(exposureUrl(row))
104561
103852
  });
104562
- })), withSpan("Exposures.items", { attributes: { worker } }))
103853
+ })), withSpan("Exposures.items"))
104563
103854
  };
104564
103855
  }) }) {
104565
103856
  static migrations = effectDiscard(make$13({})({
@@ -104568,6 +103859,51 @@ var Exposures = class extends Service$1()("@deslop/deploy/services/exposures/ser
104568
103859
  }));
104569
103860
  static layer = (directory) => pipe(effect(this, this.make), provide$2(Proxies.layer(directory)), provide$2(this.migrations));
104570
103861
  };
103862
+ // src/services/machine/service.ts
103863
+ var Machine = class Machine extends Service$1()("@deslop/deploy/services/machine/service/Machine") {
103864
+ static layer = effect(this, gen(function* () {
103865
+ const inventory = yield* Inventory;
103866
+ const exposures = yield* Exposures;
103867
+ const reactivity = yield* Reactivity;
103868
+ const view = withSpan(gen(function* () {
103869
+ const snapshot = yield* inventory.snapshot;
103870
+ const owned = yield* match$1(exposures.items, {
103871
+ onFailure: (cause) => ({
103872
+ items: [],
103873
+ sources: [{
103874
+ error: some$1(cause.message),
103875
+ name: "Exposures"
103876
+ }]
103877
+ }),
103878
+ onSuccess: (items) => ({
103879
+ items,
103880
+ sources: []
103881
+ })
103882
+ });
103883
+ return {
103884
+ ...snapshot,
103885
+ items: [...snapshot.items, ...owned.items],
103886
+ sources: [...snapshot.sources, ...owned.sources]
103887
+ };
103888
+ }), "Machine.view");
103889
+ function changing(effect) {
103890
+ return pipe(effect, onExit$1(() => inventory.refresh), onExit$1(() => reactivity.invalidate(["deployInventory"])));
103891
+ }
103892
+ return Machine.of({
103893
+ expose: fn("Machine.expose")(function* (input, admin) {
103894
+ yield* annotateCurrentSpan({ exposure: input.name });
103895
+ return yield* changing(exposures.expose(input, admin));
103896
+ }),
103897
+ hide: fn("Machine.hide")(function* (input, admin) {
103898
+ yield* annotateCurrentSpan({ exposure: input.name });
103899
+ return yield* changing(exposures.hide(input.name, admin));
103900
+ }),
103901
+ run: inventory.run,
103902
+ snapshot: andThen(inventory.ensureFresh, view),
103903
+ view
103904
+ });
103905
+ }));
103906
+ };
104571
103907
  // src/services/metrics/lib/utils.ts
104572
103908
  const SERIES = {
104573
103909
  10: seconds(10),
@@ -104580,12 +103916,12 @@ function expired(row, now) {
104580
103916
  return some(HistoryMinutes.literals, (minutes$2) => equals(SERIES[minutes$2], row.step) && toEpochMillis(row.since) < toEpochMillis(now) - toMillis(minutes(minutes$2)) - toMillis(SERIES[minutes$2]));
104581
103917
  }
104582
103918
  function counters(stat, uptime, time) {
104583
- const values = decodeUnknownSync(CpuCounters)(pipe(stat, split$1("\n"), head, getOrElse$1(constant$1("")), trim, split$1(/\s+/u), drop$1(1), take$3(8)));
103919
+ const values = decodeUnknownSync(CpuCounters)(pipe(stat, split("\n"), head, getOrElse$1(constant$1("")), trim, split(/\s+/u), drop$1(1), take$3(8)));
104584
103920
  return {
104585
103921
  cpuIdle: millis((values[3] + values[4]) * 10),
104586
103922
  cpuTotal: millis(sumAll(values) * 10),
104587
103923
  time,
104588
- uptime: seconds(decodeSync(FiniteFromString)(split$1(uptime, " ")[0]))
103924
+ uptime: seconds(decodeSync(FiniteFromString)(split(uptime, " ")[0]))
104589
103925
  };
104590
103926
  }
104591
103927
  function cpuUsage(current, elapsed, previous) {
@@ -104599,42 +103935,8 @@ function cpuUsage(current, elapsed, previous) {
104599
103935
  }));
104600
103936
  });
104601
103937
  }
104602
- function cpuCounters(cpus, uptime, time) {
104603
- return {
104604
- cpuIdle: millis(sumAll(map$10(cpus, (cpu) => cpu.times.idle))),
104605
- cpuTotal: millis(sumAll(map$10(cpus, (cpu) => sumAll(values$2(cpu.times))))),
104606
- time,
104607
- uptime
104608
- };
104609
- }
104610
- function vmStatMemory(text, total) {
104611
- const pages = fromEntries(getSomes(pipe(text, split$1("\n"), map$10((line) => map$13(match$2(/^"?([^":]+)"?:\s+([0-9]+)\.$/u)(trim(line)), (match) => [match[1] ?? "", match[2] ?? ""])))));
104612
- const page = decodeUnknownSync(FiniteFromString)(pipe(match$2(/page size of ([0-9]+) bytes/u)(text), flatMap$8(get$13(1)), getOrUndefined$2));
104613
- const counts = decodeUnknownSync(VmStatPages)(pages);
104614
- return {
104615
- total,
104616
- used: clamp((counts["Anonymous pages"] - counts["Pages purgeable"] + counts["Pages wired down"] + counts["Pages occupied by compressor"]) * page, {
104617
- maximum: total,
104618
- minimum: 0
104619
- })
104620
- };
104621
- }
104622
- function diskRows(output) {
104623
- return pipe(output, trim, split$1("\n"), drop$1(1), filter$3(isNonEmpty$1));
104624
- }
104625
- function rootVolume(text) {
104626
- return map$10(diskRows(text), (line) => {
104627
- const fields = split$1(trim(line), /\s+/u);
104628
- const size = decodeUnknownSync(FiniteFromString)(fields[1]) * 1024;
104629
- return {
104630
- mount: "/",
104631
- total: size,
104632
- used: size - decodeUnknownSync(FiniteFromString)(fields[3]) * 1024
104633
- };
104634
- });
104635
- }
104636
103938
  function linuxDisks(text) {
104637
- return map$10(diskRows(text), (line) => {
103939
+ return map$10(pipe(text, trim, split("\n"), drop$1(1), filter$3(isNonEmpty$1)), (line) => {
104638
103940
  const fields = getOrThrowWith$1(match$2(/^\s*(.+?)\s+([0-9]+)\s+([0-9]+)\s*$/u)(line), () => DeployError.make({ message: `df wrote a row without a size and use: ${line}` }));
104639
103941
  return {
104640
103942
  mount: fields[1] ?? "",
@@ -104649,7 +103951,12 @@ function coverageOf(value) {
104649
103951
  onSome: () => seconds(1)
104650
103952
  });
104651
103953
  }
104652
- function reading(current, memory, disks, load, previous) {
103954
+ function sample(current, memory, disks, previous, load) {
103955
+ const values = pipe(trim(memory), split("\n"), fromIterableWith((line) => {
103956
+ const fields = split(line, /\s+/u);
103957
+ return [fields[0], decodeSync(FiniteFromString)(fields[1] ?? "") * 1024];
103958
+ }));
103959
+ const memoryTotal = decodeUnknownSync(Finite)(values["MemTotal:"]);
104653
103960
  const baseline = filter$5(previous, (old) => isLessThan$1(old.uptime, current.uptime));
104654
103961
  const cpu = cpuUsage({
104655
103962
  idle: current.cpuIdle,
@@ -104665,33 +103972,24 @@ function reading(current, memory, disks, load, previous) {
104665
103972
  onEmpty: () => none(),
104666
103973
  onNonEmpty: () => some$1(sumAll(map$10(disks, (entry) => entry.used)))
104667
103974
  });
103975
+ const point = {
103976
+ apps: none(),
103977
+ appsCoverage: zero$2,
103978
+ cpu,
103979
+ cpuCoverage: coverageOf(cpu),
103980
+ memoryCoverage: seconds(1),
103981
+ memoryTotal,
103982
+ memoryUsed: memoryTotal - decodeUnknownSync(Finite)(values["MemAvailable:"]),
103983
+ storageCoverage: coverageOf(storageUsed),
103984
+ storageUsed,
103985
+ time: current.time
103986
+ };
104668
103987
  return {
104669
103988
  disks,
104670
- load,
104671
- point: {
104672
- apps: none(),
104673
- appsCoverage: zero$2,
104674
- cpu,
104675
- cpuCoverage: coverageOf(cpu),
104676
- memoryCoverage: seconds(1),
104677
- memoryTotal: memory.total,
104678
- memoryUsed: memory.used,
104679
- storageCoverage: coverageOf(storageUsed),
104680
- storageUsed,
104681
- time: current.time
104682
- }
103989
+ load: decodeSync(LoadAverages)(pipe(getOrElse$1(load, constant$1("")), trim, split(/\s+/u), filter$3(isNonEmpty$1), take$3(3))),
103990
+ point
104683
103991
  };
104684
103992
  }
104685
- function sample(current, memory, disks, previous, load) {
104686
- const values = pipe(trim(memory), split$1("\n"), fromIterableWith((line) => {
104687
- const fields = split$1(line, /\s+/u);
104688
- return [fields[0], decodeSync(FiniteFromString)(fields[1] ?? "") * 1024];
104689
- }));
104690
- return reading(current, {
104691
- total: decodeUnknownSync(Finite)(values["MemTotal:"]),
104692
- used: decodeUnknownSync(Finite)(values["MemTotal:"]) - decodeUnknownSync(Finite)(values["MemAvailable:"])
104693
- }, disks, decodeSync(LoadAverages)(pipe(getOrElse$1(load, constant$1("")), trim, split$1(/\s+/u), filter$3(isNonEmpty$1), take$3(3))), previous);
104694
- }
104695
103993
  function resolution(range) {
104696
103994
  return divideUnsafe(range, 60);
104697
103995
  }
@@ -104793,45 +104091,13 @@ function history(samples, minutes, now) {
104793
104091
  minimum: 0
104794
104092
  })}`), values$2, map$10(merge));
104795
104093
  }
104796
- function peerHistory(minutes, now, worker, peer) {
104797
- const saved = flatMap$8(peer, (current) => current.saved);
104798
- const time = match$8(saved, {
104799
- onNone: () => now,
104800
- onSome: (last) => addDuration(last.history.time, distance(last.received, now))
104801
- });
104802
- return {
104803
- disks: match$8(saved, {
104804
- onNone: () => [],
104805
- onSome: (last) => last.history.disks
104806
- }),
104807
- error: match$8(peer, {
104808
- onNone: () => some$1("Waiting for worker"),
104809
- onSome: (current) => orElse$3(current.error, () => flatMap$8(current.saved, (last) => last.history.error))
104810
- }),
104811
- load: match$8(saved, {
104812
- onNone: () => [],
104813
- onSome: (last) => last.history.load
104814
- }),
104815
- platform: flatMap$8(saved, (last) => last.history.platform),
104816
- samples: history(match$8(saved, {
104817
- onNone: () => [],
104818
- onSome: (last) => last.history.samples
104819
- }), minutes, time),
104820
- stale: exists(peer, (current) => isSome(current.error)) || match$8(saved, {
104821
- onNone: constTrue,
104822
- onSome: (last) => last.history.stale || pipe(last.received, distance(now), isGreaterThan$3(seconds(90)))
104823
- }),
104824
- time,
104825
- worker
104826
- };
104827
- }
104828
104094
  function bandName(id, labels) {
104829
104095
  if (id === "other") return "Low impact";
104830
104096
  if (id === "system") return "System";
104831
104097
  return pipe(labels, get$14(id), getOrElse$1(() => replaceAll(/^service:[a-z]+:(?:deslop-)?|\.service$/gu, "")(replace(/^container:/u, "container ")(id))));
104832
104098
  }
104833
104099
  function appCgroup(path, siblings) {
104834
- const name = getOrElse$1(last(split$1(path, "/")), constant$1(""));
104100
+ const name = getOrElse$1(last(split(path, "/")), constant$1(""));
104835
104101
  if (isSome(match$2(/^docker-[a-f0-9]{12,64}\.scope$/u)(name))) return true;
104836
104102
  if (endsWith(".service")(name)) return isNone(match$2(/^user@[0-9]+\.service$/u)(name));
104837
104103
  return exists(match$2(/\/user@[0-9]+\.service\/app\.slice\/app-([^/]+)\.slice$/u)(path), (match) => contains$1(siblings, `${match[1]}.service`));
@@ -104906,7 +104172,7 @@ function appsOf(labels, latest) {
104906
104172
  name: "other"
104907
104173
  }];
104908
104174
  }
104909
- function workerHistory(machine, minutes, labels) {
104175
+ function resourceHistory(machine, minutes, labels) {
104910
104176
  const latest = last(machine.samples);
104911
104177
  const storageTotal = diskTotal(machine);
104912
104178
  return {
@@ -104928,13 +104194,9 @@ function workerHistory(machine, minutes, labels) {
104928
104194
  memoryTotalGiB: round(point.memoryTotal / 1024 ** 3, 1)
104929
104195
  })),
104930
104196
  stale: liftPredicate(true, () => machine.stale),
104931
- stepSeconds: resolution(minutes),
104932
- worker: machine.worker
104197
+ stepSeconds: resolution(minutes)
104933
104198
  };
104934
104199
  }
104935
- function resourceHistory(machines, input, names) {
104936
- return pipe(machines, filter$3((machine) => !exists(input.worker, (worker) => machine.worker !== worker)), map$10((machine) => workerHistory(machine, input.minutes, names[machine.worker] ?? {})));
104937
- }
104938
104200
  // src/services/metrics/migrations.ts
104939
104201
  const migrations = {
104940
104202
  "0001_metrics": flatMap$3(SqlClient, (sql) => sql`
@@ -104993,7 +104255,7 @@ const migrations = {
104993
104255
  };
104994
104256
  // src/services/metrics/service.ts
104995
104257
  const CGROUP = "/sys/fs/cgroup";
104996
- const asDeployError$1 = mapError$2((cause) => DeployError.make({
104258
+ const asDeployError = mapError$2((cause) => DeployError.make({
104997
104259
  cause,
104998
104260
  message: "The resource history could not be read or written."
104999
104261
  }));
@@ -105015,15 +104277,6 @@ function sampled(read) {
105015
104277
  try: read
105016
104278
  });
105017
104279
  }
105018
- function readDisks(read) {
105019
- return try_({
105020
- catch: (cause) => DeployError.make({
105021
- cause,
105022
- message: "The disk sizes are unreadable."
105023
- }),
105024
- try: read
105025
- });
105026
- }
105027
104280
  function sameBucket(row, time) {
105028
104281
  const step = toMillis(row.step);
105029
104282
  return Math.floor(toEpochMillis(row.since) / step) === Math.floor(toEpochMillis(time) / step);
@@ -105031,7 +104284,6 @@ function sameBucket(row, time) {
105031
104284
  var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service/Metrics", { make: gen(function* () {
105032
104285
  const fs = yield* FileSystem;
105033
104286
  const sql = yield* SqlClient;
105034
- const worker = yield* decodeEffect(WorkerId)(hostname());
105035
104287
  const joinedSamples = sql`SELECT s.*,
105036
104288
  CASE WHEN COUNT(a.app) = 0 THEN CASE WHEN s.appsCoverage > 0 THEN '[]' END ELSE
105037
104289
  json_group_array(json_patch('{}', json_object('id', a.app, 'cpu', a.cpu, 'cpuCoverage', CASE WHEN a.cpu IS NULL THEN 0 ELSE s.appsCoverage END, 'memory', a.memory)))
@@ -105134,27 +104386,30 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105134
104386
  }), { concurrency: 8 });
105135
104387
  return fromEntries(getSomes(readings));
105136
104388
  });
105137
- const refreshStorage = pipe(match(platform === "darwin", {
105138
- onFalse: () => flatMap$3(executeProcess("df", [
105139
- "-B1",
105140
- "--output=target,size,used",
105141
- "-x",
105142
- "tmpfs",
105143
- "-x",
105144
- "devtmpfs",
105145
- "-x",
105146
- "overlay",
105147
- "-x",
105148
- "squashfs",
105149
- "-x",
105150
- "efivarfs"
105151
- ], { timeout: "10 seconds" }), (text) => readDisks(() => linuxDisks(text))),
105152
- onTrue: () => flatMap$3(executeProcess("df", ["-k", "/"], { timeout: "10 seconds" }), (text) => readDisks(() => rootVolume(text)))
105153
- }), flatMap$3((disks) => set(storage, disks)), andThen(report("disks", none())), withSpan("Metrics.refreshStorage", { attributes: { worker } }), tapError$3((cause) => report("disks", some$1(cause.message))), ignore$1({
104389
+ const refreshStorage = pipe(executeProcess("df", [
104390
+ "-B1",
104391
+ "--output=target,size,used",
104392
+ "-x",
104393
+ "tmpfs",
104394
+ "-x",
104395
+ "devtmpfs",
104396
+ "-x",
104397
+ "overlay",
104398
+ "-x",
104399
+ "squashfs",
104400
+ "-x",
104401
+ "efivarfs"
104402
+ ], { timeout: "10 seconds" }), flatMap$3((text) => try_({
104403
+ catch: (cause) => DeployError.make({
104404
+ cause,
104405
+ message: "The disk sizes are unreadable."
104406
+ }),
104407
+ try: () => linuxDisks(text)
104408
+ })), flatMap$3((disks) => set(storage, disks)), andThen(report("disks", none())), withSpan("Metrics.refreshStorage"), tapError$3((cause) => report("disks", some$1(cause.message))), ignore$1({
105154
104409
  log: "Warn",
105155
104410
  message: "The disk sizes were not read"
105156
104411
  }));
105157
- const linux = fnUntraced(function* (time, disks, old) {
104412
+ const measure = fnUntraced(function* (time, disks, old) {
105158
104413
  const files = yield* all$2({
105159
104414
  load: fs.readFileString("/proc/loadavg"),
105160
104415
  memory: fs.readFileString("/proc/meminfo"),
@@ -105183,24 +104438,11 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105183
104438
  }
105184
104439
  };
105185
104440
  });
105186
- const darwin = fnUntraced(function* (time, disks, old) {
105187
- const uptime = nanos(yield* monotonicTimeNanos);
105188
- const current = yield* counted(() => cpuCounters(cpus(), uptime, time));
105189
- return {
105190
- current,
105191
- value: yield* flatMap$3(executeProcess("vm_stat", [], { timeout: "2 seconds" }), (memory) => sampled(() => reading(current, vmStatMemory(memory, totalmem()), disks, loadavg(), old)))
105192
- };
105193
- });
105194
- const pending = yield* make$49(yield* asDeployError$1(listBuckets(yield* now)));
104441
+ const pending = yield* make$49(yield* asDeployError(listBuckets(yield* now)));
105195
104442
  const writes = yield* make$78(1);
105196
104443
  const collect = pipe(gen(function* () {
105197
104444
  const time = yield* now;
105198
- const old = yield* get$3(previous);
105199
- const disks = yield* get$3(storage);
105200
- const measurement = yield* match(platform === "darwin", {
105201
- onFalse: () => linux(time, disks, old),
105202
- onTrue: () => darwin(time, disks, old)
105203
- });
104445
+ const measurement = yield* measure(time, yield* get$3(storage), yield* get$3(previous));
105204
104446
  yield* set(previous, some$1(measurement.current));
105205
104447
  yield* writes.withPermits(1)(update(pending, (rows) => {
105206
104448
  const [current, completed] = partition(rows, fromPredicate((row) => sameBucket(row, time)));
@@ -105215,7 +104457,7 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105215
104457
  const flush = pipe(gen(function* () {
105216
104458
  const rows = yield* get$3(pending);
105217
104459
  const saved = yield* exit(gen(function* () {
105218
- if (isReadonlyArrayNonEmpty(rows)) yield* pipe(saveSamples(rows), sql.withTransaction, asDeployError$1);
104460
+ if (isReadonlyArrayNonEmpty(rows)) yield* pipe(saveSamples(rows), sql.withTransaction, asDeployError);
105219
104461
  }));
105220
104462
  const time = yield* now;
105221
104463
  yield* set(pending, filter$3(rows, (row) => match(isSuccess(saved), {
@@ -105223,7 +104465,7 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105223
104465
  onTrue: () => sameBucket(row, time)
105224
104466
  })));
105225
104467
  return yield* saved;
105226
- }), writes.withPermits(1), andThen(report("save", none())), withSpan("Metrics.collect", { attributes: { worker } }), tapError$3((cause) => report("save", some$1(cause.message))), ignore$1({
104468
+ }), writes.withPermits(1), andThen(report("save", none())), withSpan("Metrics.collect"), tapError$3((cause) => report("save", some$1(cause.message))), ignore$1({
105227
104469
  log: "Error",
105228
104470
  message: "Resource history could not be saved"
105229
104471
  }));
@@ -105245,7 +104487,7 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105245
104487
  onTrue: () => current
105246
104488
  }));
105247
104489
  if (current.monotonic - since.monotonic < toMillis(minutes(10))) return yield* logDebug("The wall clock moved recently; history is kept until it holds");
105248
- yield* pipe(now, flatMap$3(deleteExpired), sql.withTransaction, asDeployError$1, withSpan("Metrics.prune", { attributes: { worker } }));
104490
+ yield* pipe(now, flatMap$3(deleteExpired), sql.withTransaction, asDeployError, withSpan("Metrics.prune"));
105249
104491
  });
105250
104492
  yield* collect;
105251
104493
  yield* addFinalizer(() => flush);
@@ -105257,14 +104499,11 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105257
104499
  message: "Expired resource history could not be deleted"
105258
104500
  }), schedule(spaced(minutes(1))), forkScoped);
105259
104501
  return { read: fn("Metrics.read")(function* (query) {
105260
- yield* annotateCurrentSpan({
105261
- minutes: toMinutes(query.minutes),
105262
- worker
105263
- });
104502
+ yield* annotateCurrentSpan({ minutes: toMinutes(query.minutes) });
105264
104503
  const time = yield* now;
105265
- const step = SERIES[yield* asDeployError$1(encodeEffect(HistoryQuery.fields.minutes)(query.minutes))];
104504
+ const step = SERIES[yield* asDeployError(encodeEffect(HistoryQuery.fields.minutes)(query.minutes))];
105266
104505
  const samples = yield* writes.withPermits(1)(gen(function* () {
105267
- const stored = yield* asDeployError$1(listSeries({
104506
+ const stored = yield* asDeployError(listSeries({
105268
104507
  after: subtractDuration(chartWindow(query.minutes, time).start, step),
105269
104508
  step
105270
104509
  }));
@@ -105276,17 +104515,12 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105276
104515
  disks: now$2.disks,
105277
104516
  error: pipe(yield* get$3(problems), toValues, liftPredicate(isReadonlyArrayNonEmpty), map$13(join$3("; "))),
105278
104517
  load: now$2.load,
105279
- platform: some$1(match(platform === "darwin", {
105280
- onFalse: constant$1("linux"),
105281
- onTrue: constant$1("darwin")
105282
- })),
105283
104518
  samples: history(samples, query.minutes, time),
105284
104519
  stale: match$8(last(samples), {
105285
104520
  onNone: constTrue,
105286
104521
  onSome: (value) => pipe(value.time, distance(time), isGreaterThan$3(seconds(90)))
105287
104522
  }),
105288
- time,
105289
- worker
104523
+ time
105290
104524
  };
105291
104525
  }) };
105292
104526
  }) }) {
@@ -105296,257 +104530,33 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
105296
104530
  }));
105297
104531
  static layer = provide$2(effect(this, this.make), this.migrations);
105298
104532
  };
105299
- // src/services/fleet/service.ts
105300
- const makeRemoteClient = make$23(RpcContracts.middleware(RpcStream), { flatten: true });
105301
- function asDeployError(effect) {
105302
- return mapError$2(effect, (cause) => {
105303
- if (is$2(DeployError)(cause)) return cause;
105304
- return DeployError.make({
105305
- cause,
105306
- message: "Worker exposure change failed"
105307
- });
105308
- });
105309
- }
105310
- var Fleet = class Fleet extends Service$1()("@deslop/deploy/services/fleet/service/Fleet") {
105311
- static layer = effect(this, gen(function* () {
105312
- const inventory = yield* Inventory;
105313
- const reactivity = yield* Reactivity;
105314
- const spawner = yield* ChildProcessSpawner;
105315
- const layerScope = yield* scope;
105316
- const localWorker = yield* decodeEffect(WorkerId)(hostname());
105317
- const metrics = yield* Metrics;
105318
- const lastMetrics = yield* make$49(empty$10());
105319
- const exposures = yield* Exposures;
105320
- const names = yield* withDefault$2(Array$1(WorkerId.check(isNonEmpty()), "DEPLOY_WORKERS"), []);
105321
- const suffix = pipe(executeProcess("tailscale", ["status", "--json"], { timeout: "5 seconds" }), flatMap$3(decodeEffect(fromJsonString(Struct$2({ MagicDNSSuffix: NonEmptyString })))), map$7((status) => status.MagicDNSSuffix), provideService$2(ChildProcessSpawner, spawner));
105322
- const port = (yield* packageMetadata).config.port;
105323
- const workers = map$10(names, (name) => ({ name }));
105324
- const clients = yield* forEach$1(workers, (worker) => gen(function* () {
105325
- const connected = yield* make$49(false);
105326
- const url = pipe(suffix, flatMap$3((value) => decodeEffect(SecureOrigin)(`https://${worker.name}.${value}:${port}`)), map$7((origin) => `${replace("https:", "wss:")(origin)}${RPC_PATH}`), tapError$3((error) => andThen(logWarning("Peer address is unavailable; retrying in five seconds", error), sleep("5 seconds"))), eventually);
105327
- const protocol = yield* build(pipe(layerProtocolSocket({ pingTimeout: seconds(15) }), provide$2(succeed$6(ConnectionHooks, {
105328
- onConnect: set(connected, true),
105329
- onDisconnect: set(connected, false)
105330
- })), provide$2(layerWebSocket(url)), provide$2(layerSchemaBinary()), provideMerge(layerRpcStreamClient)));
105331
- return [worker.name, {
105332
- client: yield* provideContext$2(makeRemoteClient, protocol),
105333
- connected
105334
- }];
105335
- }), { concurrency: "unbounded" });
105336
- const peers = fromEntries(clients);
105337
- const peerViews = yield* make$49({});
105338
- const local = withSpan(gen(function* () {
105339
- const snapshot = yield* inventory.snapshot;
105340
- const owned = yield* match$1(exposures.items, {
105341
- onFailure: (cause) => ({
105342
- items: [],
105343
- sources: [{
105344
- error: some$1(cause.message),
105345
- name: "Exposures"
105346
- }]
105347
- }),
105348
- onSuccess: (items) => ({
105349
- items,
105350
- sources: []
105351
- })
105352
- });
105353
- return {
105354
- ...snapshot,
105355
- items: [...snapshot.items, ...owned.items],
105356
- sources: [...snapshot.sources, ...owned.sources],
105357
- workers: dedupe([...snapshot.workers, ...map$10(workers, (worker) => worker.name)])
105358
- };
105359
- }), "Fleet.local");
105360
- const remote = fnUntraced(function* (worker, use) {
105361
- const peer = yield* pipe(peers, get$14(worker.name), match$8({
105362
- onNone: () => DeployError.make({ message: `Worker ${worker.name} is not configured.` }),
105363
- onSome: succeed$5
105364
- }));
105365
- if (!(yield* get$3(peer.connected))) return yield* DeployError.make({ message: "Worker is unreachable" });
105366
- return yield* pipe(use(peer.client), timeout(seconds(15)), withSpan("Fleet.remote", { attributes: { worker: worker.name } }));
105367
- });
105368
- const peerSnapshot = fn("Fleet.peerSnapshot")(function* (name) {
105369
- const worker = { name };
105370
- const read = yield* pipe(remote(worker, (client) => client("inventory.snapshot", void 0)), timeout(seconds(2)), map$7((snapshot) => ({
105371
- items: map$10(snapshot.items, (item) => ({
105372
- ...item,
105373
- id: ItemId.make(`${worker.name}:${item.id}`),
105374
- worker: worker.name
105375
- })),
105376
- sources: map$10(snapshot.sources, (source) => ({
105377
- ...source,
105378
- name: `${worker.name} · ${source.name}`
105379
- }))
105380
- })), result$1);
105381
- yield* update(peerViews, (views) => set$6(views, worker.name, match$7(read, {
105382
- onFailure: (cause) => ({
105383
- items: views[worker.name]?.items ?? [],
105384
- sources: [{
105385
- error: some$1(cause.message),
105386
- name: `${worker.name} · Snapshot`
105387
- }]
105388
- }),
105389
- onSuccess: identity
105390
- })));
105391
- });
105392
- const view = withSpan(gen(function* () {
105393
- const own = yield* local;
105394
- const views = yield* get$3(peerViews);
105395
- const others = getSomes(map$10(workers, (worker) => get$14(views, worker.name)));
105396
- return {
105397
- items: [...own.items, ...flatMap$6(others, (value) => value.items)],
105398
- sources: [...own.sources, ...flatMap$6(others, (value) => value.sources)],
105399
- time: yield* now,
105400
- workers: own.workers
105401
- };
105402
- }), "Fleet.view");
105403
- const peerMetrics = fn("Fleet.peerMetrics")(function* (name, query) {
105404
- const worker = { name };
105405
- const read = yield* pipe(remote(worker, (client) => client("metrics.history", query)), timeout(seconds(2)), tapError$3((cause) => logWarning("A worker history could not be read", cause)), result$1);
105406
- const received = yield* now;
105407
- yield* update(lastMetrics, (all) => set$3(all, [worker.name, query.minutes], match$7(read, {
105408
- onFailure: (cause) => ({
105409
- error: some$1(cause.message),
105410
- saved: pipe(all, get$10([worker.name, query.minutes]), flatMap$8((peer) => peer.saved))
105411
- }),
105412
- onSuccess: (value) => ({
105413
- error: none(),
105414
- saved: some$1({
105415
- history: {
105416
- ...value,
105417
- worker: worker.name
105418
- },
105419
- received
105420
- })
105421
- })
105422
- })));
105423
- });
105424
- function refreshPeer(name) {
105425
- return pipe(peerSnapshot(name), andThen(reactivity.invalidate(["deployInventory"])), forkIn(layerScope), asVoid);
105426
- }
105427
- function onPeer(name, use) {
105428
- return pipe(workers, findFirst((worker) => worker.name === name), fromOption, mapError$2((cause) => DeployError.make({
105429
- cause,
105430
- message: "This worker is not configured on the control plane"
105431
- })), flatMap$3((worker) => onExit$1(remote(worker, use), () => refreshPeer(name))));
105432
- }
105433
- return Fleet.of({
105434
- current: fn("Fleet.current")(function* (query) {
105435
- yield* annotateCurrentSpan({
105436
- minutes: toMinutes(query.minutes),
105437
- workers: workers.length + 1
105438
- });
105439
- const own = yield* metrics.read(query);
105440
- const time = yield* now;
105441
- const cached = yield* get$3(lastMetrics);
105442
- return [own, ...map$10(workers, (worker) => peerHistory(query.minutes, time, worker.name, get$10(cached, [worker.name, query.minutes])))];
105443
- }),
105444
- expose: fn("Fleet.expose")(function* (input, admin) {
105445
- yield* annotateCurrentSpan({
105446
- exposure: input.name,
105447
- worker: input.worker
105448
- });
105449
- if (input.worker === localWorker) return yield* onExit$1(exposures.expose(omit(input, ["worker"]), admin), () => inventory.refresh);
105450
- return yield* onPeer(input.worker, (client) => client("exposures.apply", omit(input, ["worker"])));
105451
- }, onExit$1(() => reactivity.invalidate(["deployInventory"])), asDeployError),
105452
- hide: fn("Fleet.hide")(function* (input, admin) {
105453
- yield* annotateCurrentSpan({
105454
- exposure: input.name,
105455
- worker: input.worker
105456
- });
105457
- if (input.worker === localWorker) return yield* onExit$1(exposures.hide(input.name, admin), () => inventory.refresh);
105458
- return yield* onPeer(input.worker, (client) => client("exposures.remove", { name: input.name }));
105459
- }, onExit$1(() => reactivity.invalidate(["deployInventory"])), asDeployError),
105460
- history: fn("Fleet.history")(function* (query) {
105461
- yield* annotateCurrentSpan("minutes", toMinutes(query.minutes));
105462
- return yield* metrics.read(query);
105463
- }),
105464
- local,
105465
- metrics: fn("Fleet.metrics")(function* (query) {
105466
- yield* annotateCurrentSpan({
105467
- minutes: toMinutes(query.minutes),
105468
- workers: workers.length + 1
105469
- });
105470
- yield* forEach$1(workers, (worker) => peerMetrics(worker.name, query), { concurrency: "unbounded" });
105471
- }),
105472
- peerMetrics,
105473
- peerSnapshot,
105474
- peers: map$10(workers, (worker) => worker.name),
105475
- run: fn("Fleet.run")(function* (input, admin) {
105476
- yield* annotateCurrentSpan({
105477
- job: input.name,
105478
- worker: input.worker
105479
- });
105480
- if (input.worker === localWorker) return yield* inventory.run(omit(input, ["worker"]), admin);
105481
- return yield* onPeer(input.worker, (client) => client("inventory.start", omit(input, ["worker"])));
105482
- }, onExit$1(() => reactivity.invalidate(["deployInventory"])), mapError$2((cause) => {
105483
- if (is$2(DeployError)(cause)) return cause;
105484
- return DeployError.make({
105485
- cause,
105486
- message: "Worker could not start the job"
105487
- });
105488
- })),
105489
- snapshot: pipe(all$2([inventory.ensureFresh, forEach$1(workers, (worker) => peerSnapshot(worker.name), { concurrency: "unbounded" })], { concurrency: "unbounded" }), andThen(view), withSpan("Fleet.snapshot", { attributes: { workers: workers.length + 1 } })),
105490
- view,
105491
- workers: [localWorker, ...map$10(workers, (worker) => worker.name)]
105492
- });
105493
- }));
105494
- };
105495
104533
  // src/rpcs/handlers.ts
105496
104534
  const RpcHandlers = RpcContracts.toLayer(gen(function* () {
105497
- const fleet = yield* Fleet;
105498
- const localInventory = yield* Inventory;
105499
- const exposures = yield* Exposures;
104535
+ const machine = yield* Machine;
104536
+ const inventory = yield* Inventory;
104537
+ const metrics = yield* Metrics;
105500
104538
  const scope$2 = yield* scope;
105501
- const inventory = yield* pipe(fromEffect(fleet.view), concat$1(mergeAll([
105502
- fromEffectSchedule(andThen(localInventory.ensureFresh, fleet.view), spaced(seconds(5))),
105503
- ...map$10(fleet.peers, (worker) => fromEffectSchedule(andThen(fleet.peerSnapshot(worker), fleet.view), spaced(seconds(5)))),
105504
- pipe(stream$3(void_$2, ["deployInventory"]), drop(1), mapEffect$1(() => fleet.view))
105505
- ], { concurrency: "unbounded" })), share({
104539
+ const view = yield* pipe(fromEffect(machine.view), concat$1(mergeAll([fromEffectSchedule(andThen(inventory.ensureFresh, machine.view), spaced(seconds(5))), pipe(stream$3(void_$2, ["deployInventory"]), drop(1), mapEffect$1(() => machine.view))], { concurrency: "unbounded" })), share({
105506
104540
  capacity: 1,
105507
104541
  replay: 1,
105508
104542
  strategy: "sliding"
105509
104543
  }));
105510
- const metrics = yield* make$64({
104544
+ const histories = yield* make$64({
105511
104545
  capacity: size$4(SERIES),
105512
- lookup: (minutes) => {
105513
- const query = { minutes };
105514
- return pipe(mergeAll([fromEffectSchedule(fleet.current(query), spaced(min$2(resolution(minutes), seconds(30)))), ...map$10(fleet.peers, (worker) => fromEffectSchedule(andThen(fleet.peerMetrics(worker, query), fleet.current(query)), spaced(clamp$1(resolution(minutes), {
105515
- maximum: seconds(30),
105516
- minimum: seconds(5)
105517
- }))))], { concurrency: "unbounded" }), share({
104546
+ lookup: fnUntraced(function* (minutes) {
104547
+ return yield* pipe(fromEffectSchedule(metrics.read({ minutes }), spaced(min$2(resolution(minutes), seconds(30)))), share({
105518
104548
  capacity: 1,
105519
104549
  replay: 1,
105520
104550
  strategy: "sliding"
105521
104551
  }), provideService$2(Scope, scope$2));
105522
- }
104552
+ })
105523
104553
  });
105524
104554
  return RpcContracts.of({
105525
- "exposures.apply": fnUntraced(function* (input) {
105526
- return yield* onExit$1(exposures.expose(input, yield* CurrentAdmin), () => localInventory.refresh);
105527
- }, onExit$1(() => invalidate(["deployInventory"]))),
105528
- "exposures.expose": (input) => flatMap$3(CurrentAdmin, (admin) => fleet.expose(input, admin)),
105529
- "exposures.hide": (input) => flatMap$3(CurrentAdmin, (admin) => fleet.hide(input, admin)),
105530
- "exposures.remove": fnUntraced(function* (input) {
105531
- yield* onExit$1(exposures.hide(input.name, yield* CurrentAdmin), () => localInventory.refresh);
105532
- }, onExit$1(() => invalidate(["deployInventory"]))),
105533
- "inventory.run": (input) => flatMap$3(CurrentAdmin, (admin) => fleet.run(input, admin)),
105534
- "inventory.snapshot": () => andThen(localInventory.ensureFresh, fleet.local),
105535
- "inventory.start": fnUntraced(function* (input) {
105536
- yield* localInventory.run(input, yield* CurrentAdmin);
105537
- }, onExit$1(() => invalidate(["deployInventory"]))),
105538
- "inventory.watch": () => inventory,
105539
- "metrics.history": fleet.history,
105540
- "metrics.watch": (query) => map$4(unwrap$4(get$8(metrics, query.minutes)), (histories) => {
105541
- const chosen = orElse$3(query.worker, () => pipe(histories, map$10((machine) => machine.worker), head));
105542
- return map$10(histories, (machine) => pipe(chosen, contains$2(machine.worker), match({
105543
- onFalse: () => ({
105544
- ...machine,
105545
- samples: []
105546
- }),
105547
- onTrue: () => machine
105548
- })));
105549
- })
104555
+ "exposures.expose": (input) => flatMap$3(CurrentAdmin, (admin) => machine.expose(input, admin)),
104556
+ "exposures.hide": (input) => flatMap$3(CurrentAdmin, (admin) => machine.hide(input, admin)),
104557
+ "inventory.run": (input) => flatMap$3(CurrentAdmin, (admin) => machine.run(input, admin)),
104558
+ "inventory.watch": () => view,
104559
+ "metrics.watch": (query) => unwrap$4(get$8(histories, query.minutes))
105550
104560
  });
105551
104561
  }));
105552
104562
  // src/tools/contracts.ts
@@ -105556,18 +104566,23 @@ const MetricSummary = Struct$2({
105556
104566
  min: OptionFromOptionalKey(Finite),
105557
104567
  samples: Int$1
105558
104568
  });
105559
- const WorkerSummary = WorkerHistory.mapFields((fields) => ({
104569
+ const ResourceSummary = ResourceHistory.mapFields((fields) => ({
105560
104570
  ...fields,
105561
104571
  cpuPct: MetricSummary,
105562
104572
  diskPct: MetricSummary,
105563
- memoryPct: MetricSummary
104573
+ memoryPct: MetricSummary,
104574
+ series: OptionFromOptionalKey(Struct$2(pick(fields, [
104575
+ "cpuPct",
104576
+ "diskPct",
104577
+ "memoryPct"
104578
+ ])))
105564
104579
  }));
105565
104580
  const PageLimit = pipe(Int$1.check(isBetween({
105566
104581
  maximum: 100,
105567
104582
  minimum: 1
105568
104583
  })), withDecodingDefaultTypeKey(succeed$5(30)));
105569
104584
  const ToolContracts = make$26(make$27("list_apps", {
105570
- description: "Inspect worker apps, jobs and owned HTTPS exposures; app focuses on matching names and includes process trees. Continue with nextCursor; processOffset pages a focused app’s tree, retaining ancestors of selected nodes.",
104585
+ description: "Inspect the apps, jobs and owned HTTPS exposures on the machine Deploy runs on; app focuses on matching names and includes process trees. Continue with nextCursor; processOffset pages a focused app’s tree, retaining ancestors of selected nodes.",
105571
104586
  failure: DeployError,
105572
104587
  parameters: Struct$2({
105573
104588
  ...InventoryQuery.fields,
@@ -105576,66 +104591,49 @@ const ToolContracts = make$26(make$27("list_apps", {
105576
104591
  processLimit: PageLimit,
105577
104592
  processOffset: pipe(Natural, withDecodingDefaultTypeKey(succeed$5(0)))
105578
104593
  }),
105579
- success: Struct$2({
105580
- nextCursor: OptionFromOptionalKey(InventoryCursor),
105581
- workers: ArraySchema(WorkerInventory.mapFields((fields) => ({
105582
- ...fields,
105583
- apps: ArraySchema(Struct$2({
105584
- ...ManagedApp.fields,
105585
- nextProcessOffset: OptionFromOptionalKey(Natural),
105586
- processesOmitted: OptionFromOptionalKey(Natural)
105587
- }))
105588
- })))
105589
- })
104594
+ success: AppList.mapFields((fields) => ({
104595
+ ...fields,
104596
+ apps: ArraySchema(Struct$2({
104597
+ ...ManagedApp.fields,
104598
+ nextProcessOffset: OptionFromOptionalKey(Natural),
104599
+ processesOmitted: OptionFromOptionalKey(Natural)
104600
+ })),
104601
+ nextCursor: OptionFromOptionalKey(InventoryCursor)
104602
+ }))
105590
104603
  }).annotate(Readonly, true).annotate(Strict, true), make$27("read_resource_history", {
105591
- description: "Inspect current capacity, memory-ranked consumers and min/max/last resource percentages with sample coverage. Set series=true for the aligned 60-point history with null gaps when timing or spikes matter.",
104604
+ description: "Inspect current capacity, memory-ranked consumers and min/max/last resource percentages with sample coverage. Set series=true to add the aligned 60-point history with null gaps when timing or spikes matter.",
105592
104605
  failure: DeployError,
105593
104606
  parameters: Struct$2({
105594
- ...HistoryToolInput.fields,
104607
+ ...HistoryQuery.fields,
105595
104608
  series: pipe(Boolean$5, withDecodingDefaultTypeKey(succeed$5(false)))
105596
104609
  }),
105597
- success: Struct$2({ workers: ArraySchema(Union$2([WorkerSummary, WorkerHistory])) })
104610
+ success: ResourceSummary
105598
104611
  }).annotate(Readonly, true).annotate(Strict, true), make$27("create_exposure", {
105599
104612
  dependencies: [CurrentUser],
105600
- description: "Give a listening local port the requested HTTPS hostname and ownership name on a configured worker; public exposure requires explicit publicAccess=true consent. Caddy’s admin port is refused, and a Deslop app’s port is published only under the app’s own name and only when it runs with a domain. Returns the URL, adds no authentication and starts no application; list_apps shows owned exposures.",
104613
+ description: "Give a listening local port the requested HTTPS hostname and ownership name; public exposure requires explicit publicAccess=true consent. Caddy’s admin port is refused, and a Deslop app’s port is published only under the app’s own name and only when it runs with a domain. Returns the URL, adds no authentication and starts no application; list_apps shows owned exposures.",
105601
104614
  failure: Union$2([AuthError, DeployError]),
105602
- parameters: Struct$2({
105603
- ...ExposeInput.fields,
105604
- worker: OptionFromOptionalKey(WorkerId)
105605
- }),
104615
+ parameters: ExposeInput,
105606
104616
  success: Struct$2({ url: String$6 })
105607
104617
  }).annotate(Destructive, true).annotate(Strict, true), make$27("remove_exposure", {
105608
104618
  dependencies: [CurrentUser],
105609
- description: "Remove an HTTPS exposure Deploy owns by name and optional worker from list_apps, not its backend. Externally changed Tailscale mappings are refused; an accepted removal is saved first, finishes on its own when this call fails and is never undone.",
104619
+ description: "Remove an HTTPS exposure Deploy owns by name from list_apps, not its backend. Externally changed Tailscale mappings are refused; an accepted removal is saved first, finishes on its own when this call fails and is never undone.",
105610
104620
  failure: Union$2([AuthError, DeployError]),
105611
- parameters: Struct$2({
105612
- name: ExposureName.check(isNonEmpty()),
105613
- worker: OptionFromOptionalKey(WorkerId)
105614
- }),
105615
- success: Struct$2({
105616
- name: ExposureName,
105617
- worker: OptionFromOptionalKey(WorkerId)
105618
- })
104621
+ parameters: Struct$2({ name: ExposureName.check(isNonEmpty()) }),
104622
+ success: Struct$2({ name: ExposureName })
105619
104623
  }).annotate(Destructive, true).annotate(Strict, true), make$27("run_job", {
105620
104624
  dependencies: [CurrentUser],
105621
- description: "Start a scheduled job now by name from list_apps; pass worker to disambiguate machines. started means accepted, not completed; inspect list_apps or Scope for the outcome.",
104625
+ description: "Start a scheduled job now by its id from list_apps. started means accepted, not completed; inspect list_apps or Scope for the outcome.",
105622
104626
  failure: Union$2([AuthError, DeployError]),
105623
104627
  parameters: RunJobInput,
105624
104628
  success: Struct$2({ started: Literal(true) })
105625
104629
  }).annotate(Strict, true));
105626
104630
  // src/tools/handlers.ts
105627
- function checkWorker(workers, worker) {
105628
- return pipe(worker, filter$5((selected) => !contains$1(workers, selected)), match$8({
105629
- onNone: () => void_$2,
105630
- onSome: (selected) => fail$7(DeployError.make({ message: `Unknown worker ${selected}; valid workers: ${join$3(workers, ", ")}. Nothing changed.` }))
105631
- }));
105632
- }
105633
104631
  function processPaths(tree, prefix) {
105634
104632
  return flatMap$6(tree, (node, index) => [`${prefix}${index}`, ...processPaths(getOrElse$1(node.children, empty$14), `${prefix}${index}.`)]);
105635
104633
  }
105636
104634
  function processPage(nodes, offset, limit) {
105637
104635
  const all = processPaths(nodes, "");
105638
- const selected = pipe(all, drop$1(offset), take$3(limit), flatMap$6((path) => pipe(path, split$1("."), scan$1("", (prefix, part) => `${prefix}${part}.`), drop$1(1))), fromIterable$3);
104636
+ const selected = pipe(all, drop$1(offset), take$3(limit), flatMap$6((path) => pipe(path, split("."), scan$1("", (prefix, part) => `${prefix}${part}.`), drop$1(1))), fromIterable$3);
105639
104637
  function visit(tree, prefix) {
105640
104638
  return flatMap$6(tree, (node, index) => {
105641
104639
  const path = `${prefix}${index}`;
@@ -105653,76 +104651,50 @@ function processPage(nodes, offset, limit) {
105653
104651
  processesOmitted: liftPredicate(all.length - size(selected), (count) => count > 0)
105654
104652
  };
105655
104653
  }
105656
- const cursorOrder = pipe(mapInput(String$10, (key) => key[0]), combine$3(mapInput(String$10, (key) => key[1])), combine$3(mapInput(String$10, (key) => key[2])));
105657
- function inventoryPage(workers, input) {
105658
- const remaining = pipe(workers, flatMap$6((worker) => [
105659
- ...map$10(worker.apps, (row) => [
105660
- worker.worker,
105661
- "apps",
105662
- row.id
105663
- ]),
105664
- ...pipe(worker.jobs, getOrElse$1(empty$14), map$10((row) => [
105665
- worker.worker,
105666
- "jobs",
105667
- row.id
105668
- ])),
105669
- ...pipe(worker.exposures, getOrElse$1(empty$14), map$10((row) => [
105670
- worker.worker,
105671
- "exposures",
105672
- row.id
105673
- ]))
105674
- ]), sort(cursorOrder), filter$3((key) => !exists(input.cursor, (cursor) => isLessThanOrEqualTo$4(cursorOrder)(key, cursor))));
104654
+ const cursorOrder = Tuple$1([String$10, String$10]);
104655
+ function inventoryPage(list, input) {
104656
+ const remaining = pipe([
104657
+ ...map$10(list.apps, (row) => ["apps", row.id]),
104658
+ ...pipe(list.jobs, getOrElse$1(empty$14), map$10((row) => ["jobs", row.id])),
104659
+ ...pipe(list.exposures, getOrElse$1(empty$14), map$10((row) => ["exposures", row.id]))
104660
+ ], sort(cursorOrder), filter$3((key) => !exists(input.cursor, (cursor) => isLessThanOrEqualTo$4(cursorOrder)(key, cursor))));
105675
104661
  const page = take$3(remaining, input.limit);
105676
104662
  const selected = fromIterable$3(page);
105677
104663
  return {
105678
- nextCursor: pipe(page, last, filter$5(() => remaining.length > input.limit)),
105679
- workers: map$10(workers, (worker) => ({
105680
- ...pick(worker, ["worker", "errors"]),
105681
- apps: pipe(worker.apps, filter$3((row) => has$1(selected, [
105682
- worker.worker,
105683
- "apps",
105684
- row.id
105685
- ])), map$10((row) => match$8(row.processes, {
105686
- onNone: () => ({
104664
+ apps: pipe(list.apps, filter$3((row) => has$1(selected, ["apps", row.id])), map$10((row) => match$8(row.processes, {
104665
+ onNone: () => ({
104666
+ ...row,
104667
+ nextProcessOffset: none(),
104668
+ processesOmitted: none()
104669
+ }),
104670
+ onSome: (processes) => {
104671
+ const result = processPage(processes, input.processOffset, input.processLimit);
104672
+ return {
105687
104673
  ...row,
105688
- nextProcessOffset: none(),
105689
- processesOmitted: none()
105690
- }),
105691
- onSome: (processes) => {
105692
- const result = processPage(processes, input.processOffset, input.processLimit);
105693
- return {
105694
- ...row,
105695
- ...result,
105696
- processes: some$1(result.processes)
105697
- };
105698
- }
105699
- }))),
105700
- exposures: map$13(worker.exposures, (exposures) => filter$3(exposures, (row) => has$1(selected, [
105701
- worker.worker,
105702
- "exposures",
105703
- row.id
105704
- ]))),
105705
- jobs: map$13(worker.jobs, (jobs) => filter$3(jobs, (row) => has$1(selected, [
105706
- worker.worker,
105707
- "jobs",
105708
- row.id
105709
- ])))
105710
- }))
104674
+ ...result,
104675
+ processes: some$1(result.processes)
104676
+ };
104677
+ }
104678
+ }))),
104679
+ errors: list.errors,
104680
+ exposures: map$13(list.exposures, (exposures) => filter$3(exposures, (row) => has$1(selected, ["exposures", row.id]))),
104681
+ jobs: map$13(list.jobs, (jobs) => filter$3(jobs, (row) => has$1(selected, ["jobs", row.id]))),
104682
+ nextCursor: pipe(page, last, filter$5(() => remaining.length > input.limit))
105711
104683
  };
105712
104684
  }
105713
- function focusedInventory(workers, app) {
104685
+ function focusedInventory(list, app) {
105714
104686
  return match$8(app, {
105715
- onNone: () => workers,
104687
+ onNone: () => list,
105716
104688
  onSome: (queryText) => {
105717
104689
  const query = toLowerCase(queryText);
105718
104690
  function matchingName(row) {
105719
104691
  return pipe(row.name, toLowerCase, includes(query));
105720
104692
  }
105721
- return map$10(workers, (worker) => ({
105722
- ...worker,
105723
- exposures: pipe(worker.exposures, map$13((rows) => filter$3(rows, matchingName)), orElseSome(() => [])),
105724
- jobs: pipe(worker.jobs, map$13((rows) => filter$3(rows, matchingName)), orElseSome(() => []))
105725
- }));
104693
+ return {
104694
+ ...list,
104695
+ exposures: pipe(list.exposures, map$13((rows) => filter$3(rows, matchingName)), orElseSome(() => [])),
104696
+ jobs: pipe(list.jobs, map$13((rows) => filter$3(rows, matchingName)), orElseSome(() => []))
104697
+ };
105726
104698
  }
105727
104699
  });
105728
104700
  }
@@ -105741,53 +104713,47 @@ function metricSummary(series) {
105741
104713
  samples: values.length
105742
104714
  };
105743
104715
  }
105744
- const ToolHandlers = ToolContracts.toLayer(map$7(Fleet, (fleet) => ToolContracts.of({
105745
- create_exposure: fnUntraced(function* (input) {
105746
- const admin = yield* requireAdmin(yield* CurrentUser, "Only an admin can create exposures");
105747
- yield* checkWorker(fleet.workers, input.worker);
105748
- return { url: yield* fleet.expose({
105749
- ...input,
105750
- worker: getOrElse$1(input.worker, () => WorkerId.make(hostname()))
105751
- }, admin) };
105752
- }),
105753
- list_apps: fnUntraced(function* (input) {
105754
- yield* checkWorker(fleet.workers, input.worker);
105755
- return inventoryPage(focusedInventory(listApps(yield* fleet.snapshot, input), input.app), input);
105756
- }),
105757
- read_resource_history: fnUntraced(function* (input) {
105758
- yield* checkWorker(fleet.workers, input.worker);
105759
- const value = yield* all$2({
105760
- machines: andThen(fleet.metrics({ minutes: input.minutes }), fleet.current({ minutes: input.minutes })),
105761
- snapshot: fleet.snapshot
105762
- }, { concurrency: "unbounded" });
105763
- return { workers: map$10(resourceHistory(value.machines, input, ownerNames(value.snapshot)), (worker) => match(input.series, {
105764
- onFalse: () => ({
105765
- ...worker,
105766
- cpuPct: metricSummary(worker.cpuPct),
105767
- diskPct: metricSummary(worker.diskPct),
105768
- memoryPct: metricSummary(worker.memoryPct)
105769
- }),
105770
- onTrue: () => worker
105771
- })) };
105772
- }),
105773
- remove_exposure: fnUntraced(function* (input) {
105774
- const admin = yield* requireAdmin(yield* CurrentUser, "Only an admin can remove exposures");
105775
- yield* checkWorker(fleet.workers, input.worker);
105776
- yield* fleet.hide({
105777
- name: input.name,
105778
- worker: getOrElse$1(input.worker, () => WorkerId.make(hostname()))
105779
- }, admin);
105780
- return input;
105781
- }),
105782
- run_job: fnUntraced(function* (input) {
105783
- const admin = yield* requireAdmin(yield* CurrentUser, "Only an admin can run jobs");
105784
- yield* checkWorker(fleet.workers, input.worker);
105785
- yield* fleet.run(yield* jobRequest(yield* fleet.snapshot, input), admin);
105786
- return { started: true };
105787
- })
105788
- })));
104716
+ const ToolHandlers = ToolContracts.toLayer(gen(function* () {
104717
+ const machine = yield* Machine;
104718
+ const metrics = yield* Metrics;
104719
+ return ToolContracts.of({
104720
+ create_exposure: fnUntraced(function* (input) {
104721
+ return { url: yield* machine.expose(input, yield* requireAdmin(yield* CurrentUser, "Only an admin can create exposures")) };
104722
+ }),
104723
+ list_apps: fnUntraced(function* (input) {
104724
+ return inventoryPage(focusedInventory(listApps(yield* machine.snapshot, input), input.app), input);
104725
+ }),
104726
+ read_resource_history: fnUntraced(function* (input) {
104727
+ const value = yield* all$2({
104728
+ history: metrics.read({ minutes: input.minutes }),
104729
+ snapshot: machine.snapshot
104730
+ }, { concurrency: "unbounded" });
104731
+ const history = resourceHistory(value.history, input.minutes, ownerNames(value.snapshot));
104732
+ return {
104733
+ ...history,
104734
+ cpuPct: metricSummary(history.cpuPct),
104735
+ diskPct: metricSummary(history.diskPct),
104736
+ memoryPct: metricSummary(history.memoryPct),
104737
+ series: pipe(history, pick([
104738
+ "cpuPct",
104739
+ "diskPct",
104740
+ "memoryPct"
104741
+ ]), liftPredicate(() => input.series))
104742
+ };
104743
+ }),
104744
+ remove_exposure: fnUntraced(function* (input) {
104745
+ yield* machine.hide(input, yield* requireAdmin(yield* CurrentUser, "Only an admin can remove exposures"));
104746
+ return input;
104747
+ }),
104748
+ run_job: fnUntraced(function* (input) {
104749
+ const admin = yield* requireAdmin(yield* CurrentUser, "Only an admin can run jobs");
104750
+ yield* machine.run(yield* jobRequest(yield* machine.snapshot, input), admin);
104751
+ return { started: true };
104752
+ })
104753
+ });
104754
+ }));
105789
104755
  // src/main.server.ts
105790
- const layerServices = pipe(Fleet.layer, provideMerge(unwrap$8(map$7(dataDirectory, Exposures.layer))), provideMerge(mergeAll$2(Inventory.layer, Metrics.layer)), provide$2(ToolPath.layer));
104756
+ const layerServices = pipe(Machine.layer, provideMerge(unwrap$8(map$7(dataDirectory, Exposures.layer))), provideMerge(mergeAll$2(Inventory.layer, Metrics.layer)), provide$2(ToolPath.layer));
105791
104757
  runApp({
105792
104758
  icon: icon_default,
105793
104759
  routes: provide$2(mergeAll$2(layerRpc({
@@ -105795,13 +104761,8 @@ runApp({
105795
104761
  handlers: RpcHandlers
105796
104762
  }), layerMcp({
105797
104763
  contracts: ToolContracts,
105798
- instructions: "Use list_apps for worker inventory and read_resource_history for resource comparisons. create_exposure and remove_exposure manage owned HTTPS mappings; run_job starts scheduled jobs.",
104764
+ instructions: "Use list_apps for the machine’s inventory and read_resource_history for resource comparisons. create_exposure and remove_exposure manage owned HTTPS mappings; run_job starts scheduled jobs.",
105799
104765
  registrations: provide$2(toolkit(ToolContracts), ToolHandlers)
105800
- })), layerServices),
105801
- settings: { DEPLOY_WORKERS: {
105802
- description: "The other workers' Tailscale machine names, comma-separated",
105803
- flag: "workers",
105804
- schema: WorkerList
105805
- } }
104766
+ })), layerServices)
105806
104767
  });
105807
104768
  export {};