@ghostlytools/cli 1.7.3 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +18 -13
  2. package/SKILL.md +5 -3
  3. package/dist/assets/{api-B42F9ytB.js → api-Chhvpwok.js} +2 -2
  4. package/dist/assets/{api-tf-wAAnB.js → api-D3i2hwy0.js} +142 -84
  5. package/dist/assets/api-D3i2hwy0.js.map +1 -0
  6. package/dist/assets/{apiKit-DJb9hulp.js → apiKit-BtsHrnoo.js} +30 -7
  7. package/dist/assets/apiKit-BtsHrnoo.js.map +1 -0
  8. package/dist/assets/{apps-BfoDISRg.js → apps-BFJTqvAt.js} +1 -1
  9. package/dist/assets/{apps-DIrWmLgL.js → apps-BHl97rHs.js} +10 -8
  10. package/dist/assets/apps-BHl97rHs.js.map +1 -0
  11. package/dist/assets/{arkade-CJAhhgPQ.js → arkade-BFE8KkEE.js} +2 -2
  12. package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-BFE8KkEE.js.map} +1 -1
  13. package/dist/assets/{backup-BkUeeduy.js → backup-Bbsr6nDi.js} +1 -1
  14. package/dist/assets/{backup-Bko-AAm0.js → backup-CxACdtQX.js} +7 -7
  15. package/dist/assets/{backup-Bko-AAm0.js.map → backup-CxACdtQX.js.map} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
  19. package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
  20. package/dist/assets/{buttons-DeA6Yddq.js → buttons-CieBtXEO.js} +4 -4
  21. package/dist/assets/{buttons-DeA6Yddq.js.map → buttons-CieBtXEO.js.map} +1 -1
  22. package/dist/assets/buttons-YtAj3R_E.js +2 -0
  23. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-QmtwDj-N.js} +2 -2
  24. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-QmtwDj-N.js.map} +1 -1
  25. package/dist/assets/{envelope-Cz5fc7BM.js → envelope-DYiGwzq_.js} +2 -2
  26. package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-DYiGwzq_.js.map} +1 -1
  27. package/dist/assets/{errors-mnjSQlbX.js → errors-QUGP-jIF.js} +2 -2
  28. package/dist/assets/errors-QUGP-jIF.js.map +1 -0
  29. package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
  30. package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
  31. package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
  32. package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
  33. package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
  35. package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BlZRBWpt.js → groupFiles-CBJIEvCE.js} +22 -10
  40. package/dist/assets/groupFiles-CBJIEvCE.js.map +1 -0
  41. package/dist/assets/{host-BX0DmKW6.js → host-Va-r_KJz.js} +54 -16
  42. package/dist/assets/host-Va-r_KJz.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-B2uK9tJv.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-B2uK9tJv.js.map} +1 -1
  45. package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
  46. package/dist/assets/idb-BkOJES5_.js.map +1 -0
  47. package/dist/assets/{irohWeb-R3bcd34h.js → irohWeb-DxeEgQ-W.js} +2 -2
  48. package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-DxeEgQ-W.js.map} +1 -1
  49. package/dist/assets/{main-6QOSvQ8b.js → main-BX4oPWCJ.js} +362 -110
  50. package/dist/assets/main-BX4oPWCJ.js.map +1 -0
  51. package/dist/assets/{mainline-BfwezHWi.js → mainline-IfWQOB-J.js} +39 -12
  52. package/dist/assets/mainline-IfWQOB-J.js.map +1 -0
  53. package/dist/assets/{networkReason-Ba9415nn.js → networkReason-N2vAaoth.js} +3 -3
  54. package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-N2vAaoth.js.map} +1 -1
  55. package/dist/assets/{nwc-ovXSN2M2.js → nwc-CzyCtNK2.js} +3 -3
  56. package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-CzyCtNK2.js.map} +1 -1
  57. package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-DjWmEn3j.js} +2 -2
  58. package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-DjWmEn3j.js.map} +1 -1
  59. package/dist/assets/{profiles-C6XWqre5.js → profiles-DcCeOi7J.js} +104 -10
  60. package/dist/assets/profiles-DcCeOi7J.js.map +1 -0
  61. package/dist/assets/{registry-CFtlhWCI.js → registry-BmS02J5h.js} +1 -1
  62. package/dist/assets/{registry-B0Uv9yL6.js → registry-CeW8XEQc.js} +45 -14
  63. package/dist/assets/registry-CeW8XEQc.js.map +1 -0
  64. package/dist/assets/{resolve-BzFG4WDU.js → resolve-BvHkAhDH.js} +66 -29
  65. package/dist/assets/resolve-BvHkAhDH.js.map +1 -0
  66. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-mTTp3XNs.js} +2 -2
  67. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-mTTp3XNs.js.map} +1 -1
  68. package/dist/assets/{server-BGCuHbmQ.js → server-BUcJo4vz.js} +779 -239
  69. package/dist/assets/server-BUcJo4vz.js.map +1 -0
  70. package/dist/assets/{src-DWw2hUE5.js → src-BB5-5P3s.js} +540 -159
  71. package/dist/assets/src-BB5-5P3s.js.map +1 -0
  72. package/dist/assets/{translate-DObb-1tq.js → translate-2WyaRVCr.js} +11 -9
  73. package/dist/assets/translate-2WyaRVCr.js.map +1 -0
  74. package/dist/assets/{usdt-Bkva90Vo.js → usdt-BLazHiaP.js} +3 -3
  75. package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-BLazHiaP.js.map} +1 -1
  76. package/dist/assets/{words-odSAoasK.js → words-BaumxjXe.js} +3 -3
  77. package/dist/assets/words-BaumxjXe.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/package.json +1 -1
  80. package/dist/assets/api-tf-wAAnB.js.map +0 -1
  81. package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
  82. package/dist/assets/apps-DIrWmLgL.js.map +0 -1
  83. package/dist/assets/buttons-Be7u0V5g.js +0 -2
  84. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  85. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  86. package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
  87. package/dist/assets/host-BX0DmKW6.js.map +0 -1
  88. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  89. package/dist/assets/main-6QOSvQ8b.js.map +0 -1
  90. package/dist/assets/mainline-BfwezHWi.js.map +0 -1
  91. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  92. package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
  93. package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
  94. package/dist/assets/server-BGCuHbmQ.js.map +0 -1
  95. package/dist/assets/src-DWw2hUE5.js.map +0 -1
  96. package/dist/assets/translate-DObb-1tq.js.map +0 -1
  97. package/dist/assets/words-odSAoasK.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { Ga as CRON_LINE, Ja as PR_STATES, Ka as ITEM_STATES, Qa as TASK_STATUSES, Wn as GROUP_FILE_LIMITS, Xa as RUN_RESULTS, Ya as ROUTINE_STATES, Za as STATUS_CARD_LIMITS, ao as statusCardBytes, da as VOICE_LIMITS, no as cardUrl, qa as PR_CHECKS, to as cardLine } from "./src-DWw2hUE5.js";
2
- import { a as WALLET_TYPES, d as ENGINE_READS, f as READ_PARAMS, i as TRANSPORT_NAMES, l as ENGINE_METHODS, n as CHAT_METHODS, o as turnRef, p as SECRET_RESULTS, r as PAY_METHODS, t as ADDRESS_TYPES, u as ENGINE_PARAMS } from "./words-odSAoasK.js";
3
- import { i as localFileError, n as EXIT, r as asCliError, t as CliError } from "./errors-mnjSQlbX.js";
4
- import { m as namedByThem, t as CONTACT_KEY } from "./apiKit-DJb9hulp.js";
5
- import { _ as ownSocket, a as checkShownName, c as ghostlyHome, f as profileExists, h as userPath, i as checkProfileName, l as listProfiles, m as selectProfile, o as createProfile, p as profilePaths, s as currentProfile, u as lockOwner } from "./profiles-C6XWqre5.js";
6
- import { _ as isCallRate, a as newNonce, c as provesGreeting, d as CALL_RATES, l as readDaemonSecret, n as daemonOfThisRelease, s as provesDaemon, t as HELLO } from "./daemonProof-Bp9lJDxf.js";
1
+ import { $a as RUN_RESULTS, Gn as GROUP_FILE_LIMITS, Ja as CRON_LINE, Qa as ROUTINE_STATES, Xa as PR_CHECKS, Ya as ITEM_STATES, Za as PR_STATES, ao as cardUrl, co as statusCardBytes, eo as STATUS_CARD_LIMITS, fa as VOICE_LIMITS, io as cardLine, to as TASK_STATUSES } from "./src-BB5-5P3s.js";
2
+ import { a as WALLET_TYPES, d as ENGINE_READS, f as READ_PARAMS, i as TRANSPORT_NAMES, l as ENGINE_METHODS, n as CHAT_METHODS, o as turnRef, p as SECRET_RESULTS, r as PAY_METHODS, t as ADDRESS_TYPES, u as ENGINE_PARAMS } from "./words-BaumxjXe.js";
3
+ import { i as localFileError, n as EXIT, r as asCliError, t as CliError } from "./errors-QUGP-jIF.js";
4
+ import { m as namedByThem, t as CONTACT_KEY } from "./apiKit-BtsHrnoo.js";
5
+ import { _ as userPath, a as checkShownName, c as ghostlyHome, f as profileExists, h as startingDaemon, i as checkProfileName, l as listProfiles, m as selectProfile, o as createProfile, p as profilePaths, s as currentProfile, u as lockOwner, y as ownSocket } from "./profiles-DcCeOi7J.js";
6
+ import { _ as isCallRate, a as newNonce, c as provesGreeting, d as CALL_RATES, l as readDaemonSecret, n as daemonOfThisRelease, s as provesDaemon, t as HELLO } from "./daemonProof-QmtwDj-N.js";
7
7
  import { accessSync, closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { dirname, resolve } from "node:path";
9
9
  import { spawn } from "node:child_process";
@@ -12,7 +12,7 @@ import { createInterface } from "node:readline";
12
12
  import { format } from "node:util";
13
13
  var package_default = {
14
14
  name: "@ghostlytools/cli",
15
- version: "1.7.3",
15
+ version: "1.7.4",
16
16
  type: "module",
17
17
  description: "Ghostly for bots and terminals: the app's own engine, headless on Node, behind a daemon and a `ghostly` command with JSON output.",
18
18
  license: "MIT",
@@ -117,8 +117,10 @@ var GLOBAL_OPTIONS = {
117
117
  * that starts with `-`, is longer than two characters and is no option of the command is the value (`--` starts one
118
118
  * id in 4096; `-x` stays an option). Any other positional that starts with `-` is refused instead of sent: a
119
119
  * mistyped flag must not reach a contact as text. Put `--` before a message that starts with a dash.
120
+ *
121
+ * An unknown option names the command `parsing` gives, the nearest of its options and its help.
120
122
  */
121
- function parseArgs(argv, spec, idSlot = () => false) {
123
+ function parseArgs(argv, spec, idSlot = () => false, parsing) {
122
124
  const all = {
123
125
  ...GLOBAL_OPTIONS,
124
126
  ...spec
@@ -153,7 +155,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
153
155
  inline = eq === -1 ? void 0 : arg.slice(eq + 1);
154
156
  } else {
155
157
  const long = byShort.get(arg.slice(1));
156
- if (!long) throw new CliError("usage", `Unknown option ${arg} (put -- before text that starts with a dash)`);
158
+ if (!long) throw unknownOption(arg, all, parsing);
157
159
  name = long;
158
160
  }
159
161
  if (name.startsWith("no-") && all[name.slice(3)]?.type === "boolean" && inline === void 0) {
@@ -161,7 +163,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
161
163
  continue;
162
164
  }
163
165
  const option = all[name];
164
- if (!option) throw new CliError("usage", `Unknown option --${name}`);
166
+ if (!option) throw unknownOption(`--${name}`, all, parsing);
165
167
  if (option.type === "boolean") {
166
168
  if (inline !== void 0 && !["true", "false"].includes(inline)) throw new CliError("usage", `--${name} takes no value`);
167
169
  setBoolean(name, inline === void 0 || inline === "true");
@@ -187,7 +189,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
187
189
  }
188
190
  continue;
189
191
  }
190
- if (arg.startsWith("-") && arg !== "-") throw new CliError("usage", `Unknown option ${arg} (put -- before text that starts with a dash)`);
192
+ if (arg.startsWith("-") && arg !== "-") throw unknownOption(arg, all, parsing);
191
193
  positionals.push(arg);
192
194
  }
193
195
  return {
@@ -195,6 +197,47 @@ function parseArgs(argv, spec, idSlot = () => false) {
195
197
  options
196
198
  };
197
199
  }
200
+ /**
201
+ * `Unknown option --wiat for ghostly send (did you mean --wait? ghostly help send)`. The `--` hint only where text comes
202
+ * and for a word with one dash, which may be text (`-1`, `-x`): `version -x` has no text to put after `--`.
203
+ */
204
+ function unknownOption(arg, all, parsing) {
205
+ const names = Object.entries(all).flatMap(([name, o]) => o.type === "boolean" ? [name, `no-${name}`] : [name]);
206
+ const near = nearest(arg.replace(/^--?/, ""), names);
207
+ const hints = [
208
+ ...near ? [`did you mean --${near}?`] : [],
209
+ ...parsing?.text && /^-[^-]/.test(arg) ? ["put -- before text that starts with a dash;"] : [],
210
+ ...parsing ? [`ghostly help ${parsing.command}`] : []
211
+ ];
212
+ return new CliError("usage", `Unknown option ${arg}${parsing ? ` for ghostly ${parsing.command}` : ""}${hints.length ? ` (${hints.join(" ")})` : ""}`);
213
+ }
214
+ /**
215
+ * The word of `words` a typo most likely meant: the nearest by Damerau-Levenshtein distance (a letter added, dropped,
216
+ * changed or two swapped), at most 2 and at most a third of the word's length (`wiat` one: `nope` is not `home`; `-x`
217
+ * none), else undefined.
218
+ */
219
+ function nearest(typed, words) {
220
+ const most = Math.min(2, Math.floor(typed.length / 3));
221
+ let best, bestDistance = most + 1;
222
+ for (const word of words) {
223
+ const d = distance(typed, word);
224
+ if (d < bestDistance) {
225
+ best = word;
226
+ bestDistance = d;
227
+ }
228
+ }
229
+ return best;
230
+ }
231
+ /** The optimal string alignment distance: the edits that turn `a` into `b`, a swap of two neighbours one of them. */
232
+ function distance(a, b) {
233
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
234
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
235
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
236
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
237
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
238
+ }
239
+ return d[a.length][b.length];
240
+ }
198
241
  /** Words as a sentence lists them: "a", "a or b", "a, b or c". */
199
242
  var listed$1 = (words) => words.length > 1 ? `${words.slice(0, -1).join(", ")} or ${words.at(-1)}` : words[0];
200
243
  /** The global option a word names (`--profile`, `--profile=bot`, `-p`), else undefined. */
@@ -875,12 +918,21 @@ function quota(card, usage) {
875
918
  if (card.left === void 0 && !used) throw new CliError("usage", `--left is needed (or --used with --limit): ghostly ${usage}`);
876
919
  return card;
877
920
  }
878
- /** A time a command names: milliseconds, or a date the JavaScript Date reads (`2026-09-30T01:00:00Z`). */
921
+ /** How the time flags say the dates they take (`--next`, `--resets`, `--also`'s `@`). */
922
+ var CARD_TIME_FORMS = "2026-09-30 or 2026-09-30 01:00 (no zone: local time; a date alone is its midnight), 2026-09-30T01:00:00Z or 2026-09-30T01:00+02:00";
923
+ /** An ISO date with no time, which `Date.parse` alone reads as UTC midnight: `2026-09-30`, `2026-09`. */
924
+ var ISO_DAY = /^(?:[+-]\d{6}|\d{4})-\d{2}(-\d{2})?$/;
925
+ /**
926
+ * A time a command names: milliseconds, or a date the JavaScript Date reads (`2026-09-30T01:00:00Z`). A date with no
927
+ * zone is local time in every form: `Date.parse` reads `2026-09-30 01:00` and `Sep 30 2026` as local but an ISO date
928
+ * alone as UTC midnight (21:00 the day before in UTC-03, agents#2355), so that one is read as `2026-09-30T00:00`.
929
+ */
879
930
  function cardTime(value, flag) {
880
931
  if (value === void 0) return void 0;
881
932
  const text = String(value).trim();
882
- const ms = /^\d+$/.test(text) ? milliseconds(text, flag) : Date.parse(text);
883
- if (!Number.isSafeInteger(ms) || ms <= 0) throw new CliError("usage", `--${flag} takes a time in milliseconds or a date like 2026-09-30T01:00:00Z, not ${JSON.stringify(value)}`);
933
+ const day = ISO_DAY.exec(text);
934
+ const ms = /^\d+$/.test(text) ? milliseconds(text, flag) : Date.parse(day ? `${text}${day[1] ? "" : "-01"}T00:00` : text);
935
+ if (!Number.isSafeInteger(ms) || ms <= 0) throw new CliError("usage", `--${flag} takes a time in milliseconds or a date: ${CARD_TIME_FORMS}, not ${JSON.stringify(value)}`);
884
936
  return ms;
885
937
  }
886
938
  /** `--run ok`, `--run failed:"CI flaked"`: a run of a routine, recorded as its last. */
@@ -938,7 +990,7 @@ var routineOptions = {
938
990
  },
939
991
  next: {
940
992
  type: "string",
941
- description: "Its next run: milliseconds or a date like 2026-09-30T01:00:00Z"
993
+ description: `Its next run: milliseconds or a date: ${CARD_TIME_FORMS}`
942
994
  },
943
995
  run: {
944
996
  type: "string",
@@ -1083,11 +1135,11 @@ var usageOptions = {
1083
1135
  },
1084
1136
  resets: {
1085
1137
  type: "string",
1086
- description: "When the window starts again: milliseconds or a date like 2026-10-07T18:00:00Z"
1138
+ description: `When the window starts again: milliseconds or a date: ${CARD_TIME_FORMS}`
1087
1139
  },
1088
1140
  also: {
1089
1141
  type: "list",
1090
- description: "Another window, window=percent[@time], like week=80@2026-10-10T00:00:00Z (up to 3; shown in the details)"
1142
+ description: "Another window, window=percent[@time], like week=80@2026-10-10T00:00:00Z or week=80@2026-10-10 (up to 3; shown in the details; a time as --resets takes, no zone: local time)"
1091
1143
  },
1092
1144
  id: {
1093
1145
  type: "string",
@@ -1157,7 +1209,7 @@ var commands$8 = {
1157
1209
  description: "Replace the three files when they are there"
1158
1210
  }
1159
1211
  },
1160
- run: async ({ options }, a) => (await import("./apps-BfoDISRg.js")).initApp(a.dir, {
1212
+ run: async ({ options }, a) => (await import("./apps-BFJTqvAt.js")).initApp(a.dir, {
1161
1213
  name: options.name,
1162
1214
  title: options.title,
1163
1215
  force: options.force === true
@@ -1197,7 +1249,7 @@ var commands$8 = {
1197
1249
  description: "This version's sequence, higher than the bundle at --out's (default: one more than it)"
1198
1250
  }
1199
1251
  },
1200
- run: async ({ options }, a) => (await import("./apps-BfoDISRg.js")).publishApp(a.dir, keyFile(options.key, "app publish <dir> --key <file> [--out <file>] [--sequence n]"), here(options.out), options.sequence)
1252
+ run: async ({ options }, a) => (await import("./apps-BFJTqvAt.js")).publishApp(a.dir, keyFile(options.key, "app publish <dir> --key <file> [--out <file>] [--sequence n]"), here(options.out), options.sequence)
1201
1253
  },
1202
1254
  "app revoke": {
1203
1255
  method: "app.revoke",
@@ -1230,7 +1282,7 @@ var commands$8 = {
1230
1282
  description: "Allow --up-to past the bundle's own sequence (versions published from elsewhere)"
1231
1283
  }
1232
1284
  },
1233
- run: async ({ options }, a) => (await import("./apps-BfoDISRg.js")).revokeApp(a.dir, keyFile(options.key, "app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]"), {
1285
+ run: async ({ options }, a) => (await import("./apps-BFJTqvAt.js")).revokeApp(a.dir, keyFile(options.key, "app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]"), {
1234
1286
  digests: options.digest,
1235
1287
  upTo: options["up-to"],
1236
1288
  reason: options.reason,
@@ -1291,7 +1343,7 @@ var commands$8 = {
1291
1343
  usage: "app verify <bundle|url>",
1292
1344
  summary: "Check a .ghostlyapp as a client would, from a file or an https URL: its manifest and digest, or refused (exit 1) with the reason, revoked when the ghostly-revoke.json beside it revokes this version",
1293
1345
  args: ["bundle"],
1294
- run: async (_, a) => (await import("./apps-BfoDISRg.js")).verifyApp(a.bundle)
1346
+ run: async (_, a) => (await import("./apps-BFJTqvAt.js")).verifyApp(a.bundle)
1295
1347
  },
1296
1348
  "store sign": {
1297
1349
  method: "store.sign",
@@ -1308,7 +1360,7 @@ var commands$8 = {
1308
1360
  description: "The folder to write ghostly-store.json and ghostly-store.sig in (default: the index's)"
1309
1361
  }
1310
1362
  },
1311
- run: async ({ options }, a) => (await import("./apps-BfoDISRg.js")).signStore(a.index, keyFile(options.key, "store sign <index> --key <file> [--out <dir>]"), here(options.out))
1363
+ run: async ({ options }, a) => (await import("./apps-BFJTqvAt.js")).signStore(a.index, keyFile(options.key, "store sign <index> --key <file> [--out <dir>]"), here(options.out))
1312
1364
  }
1313
1365
  };
1314
1366
  //#endregion
@@ -3224,6 +3276,11 @@ function idSlot(command) {
3224
3276
  };
3225
3277
  return (index) => at(index) && (shift === 0 || index + shift >= names.length || at(index + shift));
3226
3278
  }
3279
+ /** Whether a command's last positional takes the rest of the line as words, not ids: a text, a name, a path, emoji. */
3280
+ function takesText(command) {
3281
+ const last = command.args?.at(-1)?.replace(/\?$/, "");
3282
+ return !!last?.endsWith("...") && !ID_ARGS.has(last.slice(0, -3));
3283
+ }
3227
3284
  /**
3228
3285
  * The placeholders a usage line shows for its positionals, in order: `chat pay <chat> <sats> [--memo t]` →
3229
3286
  * ["chat", "sats"]. One that is not a plain `<x>` (`[text... | --text <text>]`) is undefined; the flags end them.
@@ -3428,6 +3485,12 @@ function checkWebhook(url) {
3428
3485
  if (parsed.username || parsed.password) throw new CliError("usage", "The webhook URL takes no user or password: put the bridge's token in its path or query");
3429
3486
  return parsed;
3430
3487
  }
3488
+ /**
3489
+ * The event number a cursor file holds, or undefined when there is no file (a first start: live events). A file that is
3490
+ * there and holds no whole number (empty, half-written, edited by hand) is refused, naming the file and what it holds:
3491
+ * taken as no cursor, the listener started at the journal's end and skipped every event since the last one handled,
3492
+ * without a word, and its next write replaced the file.
3493
+ */
3431
3494
  function readCursor(path) {
3432
3495
  if (!path || !existsSync(path)) return void 0;
3433
3496
  let text;
@@ -3436,8 +3499,11 @@ function readCursor(path) {
3436
3499
  } catch (error) {
3437
3500
  throw localFileError(error, path) ?? error;
3438
3501
  }
3439
- const value = Number(text.trim());
3440
- return Number.isInteger(value) && value >= 0 ? value : void 0;
3502
+ const trimmed = text.trim();
3503
+ const value = trimmed === "" ? NaN : Number(trimmed);
3504
+ if (Number.isSafeInteger(value) && value >= 0 && /^\d+$/.test(trimmed)) return value;
3505
+ const shown = trimmed === "" ? "nothing" : JSON.stringify(trimmed.length > 32 ? `${trimmed.slice(0, 32)}…` : trimmed);
3506
+ throw new CliError("bad_request", `${path} holds no event number (${shown}): fix or remove it, or give --since`);
3441
3507
  }
3442
3508
  /**
3443
3509
  * Whether a cursor can be kept at `path`, asked before anything starts: its folder is there and takes a file. Before, a
@@ -3717,7 +3783,7 @@ var Feed = class {
3717
3783
  pause;
3718
3784
  resume;
3719
3785
  held = false;
3720
- /** `since`: the last event taken, where a new subscription starts. */
3786
+ /** `since`: the last event taken (or, before one, the daemon's last seq when it subscribed), where a new subscription starts. */
3721
3787
  constructor(handle, since, pause, resume) {
3722
3788
  this.handle = handle;
3723
3789
  this.since = since;
@@ -3801,6 +3867,9 @@ function followDaemon(address, client, handle, since, holdMs = PAUSE_HOLD_MS, pr
3801
3867
  if (current !== c) return;
3802
3868
  current = null;
3803
3869
  reconnect(1e3);
3870
+ }).then((answer) => {
3871
+ if (feed.since === void 0 && typeof answer?.lastSeq === "number") feed.since = answer.lastSeq;
3872
+ return answer;
3804
3873
  });
3805
3874
  return {
3806
3875
  subscribed: follow(client),
@@ -3922,6 +3991,37 @@ async function completeWithPipedEvidence(call, params, read, note) {
3922
3991
  evidence
3923
3992
  });
3924
3993
  }
3994
+ /**
3995
+ * `settings set <key> <json-value>`'s value: from stdin when it is `-`, or when none is given and stdin is not a
3996
+ * terminal (a pipe nobody writes: the note, then the usage error, as for a join). A TURN password (`iceServers` with a
3997
+ * `credential`) given on the command line still goes, with the ps/history warning: `settings get` hides it as a secret.
3998
+ */
3999
+ async function settingValue(key, value, read, tty = false, note = () => {}) {
4000
+ const usage = "Missing <json-value>: ghostly settings set <key> <json-value>";
4001
+ if (value !== void 0 && value !== "-") return {
4002
+ value,
4003
+ ...key === "iceServers" && hasCredential(value) && { warning: `A TURN password on the command line shows in ps and the shell's history: give it on stdin instead (… | ghostly settings set ${key} -)` }
4004
+ };
4005
+ if (value === void 0 && tty) throw new CliError("usage", usage);
4006
+ const text = (value === "-" ? await read() : await readUnasked(read, note, {
4007
+ what: "the value",
4008
+ missing: "Missing <json-value>",
4009
+ command: `settings set ${key}`,
4010
+ as: "an argument"
4011
+ })).replace(/\r?\n$/, "");
4012
+ if (!text.trim()) throw new CliError("usage", value === "-" ? `Missing <json-value> on stdin: … | ghostly settings set ${key} -` : usage);
4013
+ return { value: text };
4014
+ }
4015
+ /** Whether an `iceServers` value as typed holds a TURN password: an entry with a `credential` that is not empty. */
4016
+ function hasCredential(value) {
4017
+ let servers;
4018
+ try {
4019
+ servers = JSON.parse(value);
4020
+ } catch {
4021
+ return false;
4022
+ }
4023
+ return Array.isArray(servers) && servers.some((server) => !!server && typeof server === "object" && typeof server.credential === "string" && server.credential !== "");
4024
+ }
3925
4025
  async function readUnasked(read, note, ask) {
3926
4026
  let noteTimer, giveUpTimer;
3927
4027
  const stop = () => {
@@ -3991,15 +4091,15 @@ var VERSION = package_default.version;
3991
4091
  * command a running daemon answers loads none of them, and starts about as fast as Node does. Statically imported, they
3992
4092
  * cost every command ~100 ms before its socket was opened.
3993
4093
  */
3994
- var engineApi = () => import("./api-B42F9ytB.js");
3995
- var engineHost = () => import("./host-BX0DmKW6.js");
4094
+ var engineApi = () => import("./api-Chhvpwok.js");
4095
+ var engineHost = () => import("./host-Va-r_KJz.js");
3996
4096
  /**
3997
4097
  * `--translate <lang>`'s translator, or null (not asked; or the runtime is not there, said on stderr). Loaded only when
3998
4098
  * asked: the app's message parser it reads costs every other command nothing.
3999
4099
  */
4000
4100
  async function translatorFor(value, home) {
4001
4101
  if (value === void 0) return null;
4002
- const { loadDetector, openTranslator, translateTarget } = await import("./translate-DObb-1tq.js");
4102
+ const { loadDetector, openTranslator, translateTarget } = await import("./translate-2WyaRVCr.js");
4003
4103
  return openTranslator({
4004
4104
  home,
4005
4105
  to: translateTarget(value),
@@ -4216,49 +4316,61 @@ function waitsFor(method, params) {
4216
4316
  async function session(g, options) {
4217
4317
  requireProfile(g);
4218
4318
  const client = await connectDaemon(g.paths);
4219
- if (client) {
4220
- const warned = warnVersion(client);
4221
- const call = async (m, p) => {
4222
- const timeoutMs = answerWithin(m, p ?? {});
4223
- if (timeoutMs === void 0 && !await settlesWithin(warned, ANSWER_MS)) {
4224
- client.destroy();
4225
- throw new CliError("timeout", `The daemon did not answer in ${ANSWER_MS / 1e3} s; nothing was done: \`ghostly daemon restart\` starts a fresh one`, { method: m });
4226
- }
4227
- return client.call(m, p, { timeoutMs });
4228
- };
4229
- return {
4230
- mode: "daemon",
4231
- call,
4232
- close: async () => {
4233
- await warned;
4234
- client.close();
4235
- }
4236
- };
4237
- }
4319
+ if (client) return throughDaemon(client);
4238
4320
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
4239
4321
  const host = await openOneShot(g, options);
4322
+ if (host instanceof DaemonClient) return throughDaemon(host);
4240
4323
  return {
4241
4324
  mode: "one-shot",
4242
4325
  call: (m, p) => callApi(host.ctx, m, p ?? {}),
4243
4326
  close: () => host.close()
4244
4327
  };
4245
4328
  }
4329
+ function throughDaemon(client) {
4330
+ const warned = warnVersion(client);
4331
+ const call = async (m, p) => {
4332
+ const timeoutMs = answerWithin(m, p ?? {});
4333
+ if (timeoutMs === void 0 && !await settlesWithin(warned, ANSWER_MS)) {
4334
+ client.destroy();
4335
+ throw new CliError("timeout", `The daemon did not answer in ${ANSWER_MS / 1e3} s; nothing was done: \`ghostly daemon restart\` starts a fresh one`, { method: m });
4336
+ }
4337
+ return client.call(m, p, { timeoutMs });
4338
+ };
4339
+ return {
4340
+ mode: "daemon",
4341
+ call,
4342
+ close: async () => {
4343
+ await warned;
4344
+ client.close();
4345
+ }
4346
+ };
4347
+ }
4246
4348
  /** How long a one-shot waits for another process to let go of the profile: a one-shot leaves in well under a second. */
4247
4349
  var HOLDER_WAIT_MS = 5e3;
4350
+ /** How long it waits for the profile's daemon that is starting (`startingDaemon`): its engine takes seconds on a large profile. */
4351
+ var STARTING_WAIT_MS = 3e4;
4248
4352
  /**
4249
4353
  * Opens the profile in this process for a one-shot command. Another one that holds it (a script's `&`, a second
4250
4354
  * terminal) is waited for: both used to fail at once, and a backgrounded send was lost unless the script checked its
4251
- * exit code. One still holding it after HOLDER_WAIT_MS is answered with the next step.
4355
+ * exit code. One still holding it after HOLDER_WAIT_MS is answered with the next step. A daemon takes the profile before
4356
+ * its socket listens (its engine starts in between, seconds on a large profile): once one answers there, the command
4357
+ * goes through it, its client the answer. Only the lock was looked at again, and a command run while the daemon started
4358
+ * failed busy, told to start the daemon that was running. A daemon that marked its start is waited for up to
4359
+ * STARTING_WAIT_MS, and named as the holder. A `listen` with no daemon opens it the same way, as the daemon (`mode`).
4252
4360
  */
4253
- async function openOneShot(g, options = {}) {
4361
+ async function openOneShot(g, options = {}, mode = "one-shot") {
4254
4362
  const { openHost } = await engineHost();
4255
- const until = Date.now() + HOLDER_WAIT_MS;
4363
+ const from = Date.now();
4256
4364
  for (;;) try {
4257
- return await openHost(g.paths, "one-shot", VERSION, options);
4365
+ return await openHost(g.paths, mode, VERSION, options);
4258
4366
  } catch (error) {
4259
4367
  if (!(error instanceof CliError) || error.code !== "busy") throw error;
4260
- const left = until - Date.now();
4368
+ const starting = startingDaemon(g.paths);
4369
+ const client = await connectDaemon(g.paths);
4370
+ if (client) return client;
4371
+ const left = from + (starting === null ? HOLDER_WAIT_MS : STARTING_WAIT_MS) - Date.now();
4261
4372
  if (left <= 0) {
4373
+ if (starting !== null) throw new CliError("busy", `Profile ${g.profile} is in use by its daemon (process ${starting}), which was still starting after ${STARTING_WAIT_MS / 1e3} s: ghostly daemon status shows when it is up`, { pid: starting });
4262
4374
  const pid = error.details?.pid;
4263
4375
  throw new CliError("busy", `Profile ${g.profile} is in use by ${pid ? `process ${pid}, another ghostly command,` : "another ghostly command"} and was not free after ${HOLDER_WAIT_MS / 1e3} s: run the commands one after another, or start \`ghostly daemon --detach\` so they can run at once`, error.details);
4264
4376
  }
@@ -4407,7 +4519,7 @@ var SPECIAL = [
4407
4519
  "The profile's settings",
4408
4520
  { "show-secret": o("boolean", "Show credentials too") }
4409
4521
  ],
4410
- ["settings set <key> <json-value>", "Change one: relays, irohRelays, hyperdhtRelay, iceServers, publicProfiles, online, shareProfile, sendTyping, autoDownloads, serveFiles, nick"],
4522
+ ["settings set <key> <json-value>", "Change one: relays, irohRelays, hyperdhtRelay, iceServers, publicProfiles, online, shareProfile, sendTyping, autoDownloads, serveFiles, nick. <json-value> - (or none, piped) reads it from stdin: a TURN password stays out of ps"],
4411
4523
  [
4412
4524
  "engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]",
4413
4525
  "Any call of the app's engine, with its own parameters (engine --list --verbose names them)",
@@ -4459,31 +4571,87 @@ function beside(rows, more) {
4459
4571
  }
4460
4572
  return out;
4461
4573
  }
4462
- function help() {
4574
+ /**
4575
+ * The width the help is laid out to: $COLUMNS, else the terminal's when stdout is one (80 when it says nothing), else
4576
+ * none: piped, each row stays one line for grep. At a fixed 58-column usage, 170 of the 195 lines of `ghostly help` passed
4577
+ * 80 columns, and an 80-column terminal broke every summary mid-word into column 0.
4578
+ */
4579
+ function helpColumns() {
4580
+ const given = Number(process.env.COLUMNS);
4581
+ if (Number.isInteger(given) && given > 0) return given;
4582
+ return process.stdout.isTTY ? process.stdout.columns || 80 : void 0;
4583
+ }
4584
+ /** `prefix`, then `text`'s words in lines of at most `columns` (a longer word alone), each after the first `indent` in. */
4585
+ function wrap(prefix, text, columns, indent) {
4586
+ const lines = [];
4587
+ let line = prefix, started = false;
4588
+ for (const word of text.trim().match(/\S+ */g) ?? []) {
4589
+ if (started && (line + word.trimEnd()).length > columns) {
4590
+ lines.push(line.trimEnd());
4591
+ line = " ".repeat(indent);
4592
+ }
4593
+ line += word;
4594
+ started = true;
4595
+ }
4596
+ return [...lines, line.trimEnd()];
4597
+ }
4598
+ /** Lines of text as written, or, laid out to `columns` and one of them wider, as one paragraph wrapped at their indent. */
4599
+ function paragraph(lines, columns) {
4600
+ if (columns === void 0 || lines.every((line) => line.length <= columns)) return lines;
4601
+ const indent = lines[0].length - lines[0].trimStart().length;
4602
+ return wrap(" ".repeat(indent), lines.join(" "), columns, indent);
4603
+ }
4604
+ /**
4605
+ * A help row: `label` (a usage or an option, with its indent), its `text` from column `at`, or under the label when the
4606
+ * label takes that room. Laid out to `columns`, the text wraps at its column; with under 40 columns left for it (an
4607
+ * 80-column terminal beside the 58 of a usage), it goes under its label, 2 further in.
4608
+ */
4609
+ function helpRow(label, text, at, columns) {
4610
+ const long = label.length > at - 2;
4611
+ if (columns === void 0) return [long ? `${label}\n${" ".repeat(at)}${text}` : label.padEnd(at) + text];
4612
+ const indent = label.length - label.trimStart().length;
4613
+ const labelLines = wrap(" ".repeat(indent), label, columns, indent + 4);
4614
+ if (columns - at < 40) return [...labelLines, ...wrap(" ".repeat(indent + 2), text, columns, indent + 2)];
4615
+ if (long) return [...labelLines, ...wrap(" ".repeat(at), text, columns, at)];
4616
+ return wrap(label.padEnd(at), text, columns, at);
4617
+ }
4618
+ /**
4619
+ * What `ghostly` says first in a Ghostly folder with no profile yet: where to start, as the README's "Five minutes"
4620
+ * does, before the whole list. `$ ` keeps the lines apart from the list's commands.
4621
+ */
4622
+ var FIRST_STEPS = [
4623
+ "First steps:",
4624
+ " $ ghostly invite create --label alice make an invite for a contact",
4625
+ " $ ghostly invite join - join one (pasted on stdin)",
4626
+ " $ ghostly daemon --detach keep the profile online",
4627
+ " $ ghostly help <command> one command and its options"
4628
+ ];
4629
+ function help(firstSteps = false) {
4630
+ const columns = helpColumns();
4463
4631
  const rows = [...beside([...SPECIAL.slice(0, 7).map(([usage, summary]) => [usage, summary]), ...Object.values(COMMANDS).filter((c) => c.method !== "events.replay").map((c) => [c.usage, c.summary])], [...Object.values(TEXT_COMMANDS).map((c) => [c.usage, c.summary]), ...SPECIAL.slice(7).map(([usage, summary]) => [usage, summary])]), [COMMANDS.events.usage, COMMANDS.events.summary]];
4464
- const width = 58;
4465
4632
  return [
4466
- `ghostly ${VERSION}: Ghostly for bots and terminals, the app's own engine without a screen.`,
4633
+ ...paragraph([`ghostly ${VERSION}: Ghostly for bots and terminals, the app's own engine without a screen.`], columns),
4467
4634
  "",
4468
- "Usage: ghostly <command> [options] (JSON on stdout; errors as {\"error\":{code,message}} with an exit code)",
4635
+ ...firstSteps ? [...FIRST_STEPS, ""] : [],
4636
+ ...paragraph(["Usage: ghostly <command> [options] (JSON on stdout; errors as {\"error\":{code,message}} with an exit code)"], columns),
4469
4637
  "",
4470
- ...rows.map(([usage, summary]) => ` ${usage.length > width ? usage + "\n " + " ".repeat(width) : usage.padEnd(width)} ${summary}`),
4638
+ ...rows.flatMap(([usage, summary]) => helpRow(` ${usage}`, summary, 62, columns)),
4471
4639
  "",
4472
4640
  "Options for every command:",
4473
- ...Object.entries(GLOBAL_OPTIONS).map(([name, o]) => ` --${name}${o.short ? `, -${o.short}` : ""}`.padEnd(24) + o.description),
4641
+ ...Object.entries(GLOBAL_OPTIONS).flatMap(([name, o]) => helpRow(` --${name}${o.short ? `, -${o.short}` : ""}`, o.description, 24, columns)),
4474
4642
  "",
4475
- "A <chat> is its id, a unique prefix of it, or its name; a <group> the same. Exit codes: 0 done, 1 failed,",
4476
- "2 usage, 3 not found, 4 timed out, 5 needs --force/--yes/--confirm-real.",
4477
- "More: https://ghostly.tools/cli, or the README.md beside this CLI."
4643
+ ...paragraph(["A <chat> is its id, a unique prefix of it, or its name; a <group> the same. Exit codes: 0 done, 1 failed,", "2 usage, 3 not found, 4 timed out, 5 needs --force/--yes/--confirm-real."], columns),
4644
+ ...paragraph(["More: https://ghostly.tools/cli, or the README.md beside this CLI."], columns)
4478
4645
  ].join("\n");
4479
4646
  }
4647
+ var EVERY_COMMAND = "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h";
4480
4648
  /** What `ghostly help help` answers. */
4481
- var HELP_USAGE = [
4649
+ var helpUsage = (columns) => [
4482
4650
  "Usage: ghostly help [<command>...]",
4483
4651
  "",
4484
- " Help for every command, or for one command or a group of them (also ghostly <command> --help)",
4652
+ ...paragraph([" Help for every command, or for one command or a group of them (also ghostly <command> --help)"], columns),
4485
4653
  "",
4486
- "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h"
4654
+ ...paragraph([EVERY_COMMAND], columns)
4487
4655
  ].join("\n");
4488
4656
  /** Every command's help row: usage, summary and, for the table and text commands, their options. */
4489
4657
  function helpRows() {
@@ -4511,7 +4679,8 @@ function commandWords(usage) {
4511
4679
  * options; for a group (`ghostly help file`), the group's commands.
4512
4680
  */
4513
4681
  function commandHelp(words) {
4514
- if (words[0] === "help") return HELP_USAGE;
4682
+ const columns = helpColumns();
4683
+ if (words[0] === "help") return helpUsage(columns);
4515
4684
  const named = (list) => helpRows().filter((row) => {
4516
4685
  const own = commandWords(row.usage);
4517
4686
  return list.every((word, i) => own[i] === word);
@@ -4520,31 +4689,31 @@ function commandHelp(words) {
4520
4689
  let rows = named(words);
4521
4690
  while (!rows.length && words.length > 1) rows = named(words = words.slice(0, -1));
4522
4691
  const asked = words.join(" ");
4523
- if (!rows.length) throw new CliError("usage", `Unknown command: ${asked || "\"\""} (ghostly help)`);
4692
+ if (!rows.length) throw unknownCommand(given[0], given[1], given[2]);
4524
4693
  const exact = rows.filter((row) => commandWords(row.usage).join(" ") === asked);
4525
4694
  if (!exact.length && words.length < given.length) throw unknownCommand(given[0], given[1], given[2]);
4526
4695
  const lines = [];
4527
4696
  for (const row of exact) {
4528
- lines.push(`Usage: ghostly ${row.usage}`, "", ` ${row.summary}`);
4697
+ lines.push(...columns === void 0 ? [`Usage: ghostly ${row.usage}`] : wrap("Usage: ghostly ", row.usage, columns, 4), "", ...paragraph([` ${row.summary}`], columns));
4529
4698
  const options = Object.entries(row.options ?? {}).filter(([, o]) => o.description);
4530
4699
  if (options.length) {
4531
4700
  lines.push("", "Options:");
4532
4701
  const labels = options.map(([name, o]) => ` --${o.negatedOnly ? "no-" : ""}${name}${o.type === "boolean" ? "" : ` <${o.type === "number" ? "n" : "value"}>`}`);
4533
4702
  const width = Math.max(26, ...labels.map((label) => label.length + 2));
4534
- options.forEach(([, o], i) => lines.push(labels[i].padEnd(width) + o.description));
4703
+ options.forEach(([, o], i) => lines.push(...helpRow(labels[i], o.description, width, columns)));
4535
4704
  }
4536
- if (Object.values(TEXT_COMMANDS).includes(row)) lines.push("", " -- ends the options: everything after it is the text, options included (\"-- -1 --wait sent\" sends", " all of it). Put options before --.");
4705
+ if (Object.values(TEXT_COMMANDS).includes(row)) lines.push("", ...paragraph([" -- ends the options: everything after it is the text, options included (\"-- -1 --wait sent\" sends", " all of it). Put options before --."], columns));
4537
4706
  lines.push("");
4538
4707
  }
4539
4708
  const rest = rows.filter((row) => !exact.includes(row));
4540
4709
  if (rest.length) {
4541
4710
  const width = Math.min(58, Math.max(...rest.map((row) => row.usage.length)));
4542
4711
  const count = `${rest.length}${exact.length ? " more" : ""} command${rest.length === 1 ? "" : "s"}`;
4543
- lines.push(`ghostly ${asked}: ${count} (ghostly help ${asked} <command> for one)`, "");
4544
- for (const row of rest) lines.push(` ${row.usage.length > width ? row.usage + "\n " + " ".repeat(width) : row.usage.padEnd(width)} ${row.summary}`);
4712
+ lines.push(...paragraph([`ghostly ${asked}: ${count} (ghostly help ${asked} <command> for one)`], columns), "");
4713
+ for (const row of rest) lines.push(...helpRow(` ${row.usage}`, row.summary, width + 4, columns));
4545
4714
  lines.push("");
4546
4715
  }
4547
- lines.push("Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h");
4716
+ lines.push(...paragraph([EVERY_COMMAND], columns));
4548
4717
  return lines.join("\n");
4549
4718
  }
4550
4719
  async function profileCommand(sub, argv) {
@@ -4598,7 +4767,7 @@ async function profileCommand(sub, argv) {
4598
4767
  eitherWay: true
4599
4768
  }
4600
4769
  }
4601
- }[sub ?? ""] ?? {});
4770
+ }[sub ?? ""] ?? {}, void 0, { command: commandOf("profile", sub) });
4602
4771
  const g = globals(parsed);
4603
4772
  pretty = g.pretty;
4604
4773
  switch (sub) {
@@ -4693,7 +4862,7 @@ async function profileCommand(sub, argv) {
4693
4862
  if (!given || !name) throw new CliError("usage", `Missing <${given ? "new profile" : "file"}>: ghostly profile restore <file> <new profile> [--passphrase-file f] [--use]`);
4694
4863
  noMoreThan(2, parsed.positionals, "profile restore <file> <new profile> [--passphrase-file f] [--use]");
4695
4864
  const file = here(given);
4696
- const { backupFileProtection, restoreProfile } = await import("./backup-BkUeeduy.js");
4865
+ const { backupFileProtection, restoreProfile } = await import("./backup-Bbsr6nDi.js");
4697
4866
  const protection = await backupFileProtection(file);
4698
4867
  const paths = await restoreProfile(g.home, checkProfileName(name), file, protection === "none" ? void 0 : backupPassphrase(parsed.options["passphrase-file"], RESTORE_PASSPHRASE));
4699
4868
  if (parsed.options.use) selectProfile(g.home, name);
@@ -4815,7 +4984,7 @@ async function daemonCommand(argv) {
4815
4984
  type: "number",
4816
4985
  description: ""
4817
4986
  }
4818
- });
4987
+ }, void 0, { command: commandOf("daemon", sub) });
4819
4988
  const g = globals(parsed);
4820
4989
  pretty = g.pretty;
4821
4990
  if (!sub || [
@@ -4827,8 +4996,13 @@ async function daemonCommand(argv) {
4827
4996
  knownProfile(g);
4828
4997
  const client = await connectDaemon(g.paths);
4829
4998
  if (!client) {
4999
+ const starting = startingDaemon(g.paths);
4830
5000
  print({
4831
5001
  running: false,
5002
+ ...starting === null ? {} : {
5003
+ starting: true,
5004
+ pid: starting
5005
+ },
4832
5006
  profile: g.profile,
4833
5007
  socket: g.paths.socket
4834
5008
  });
@@ -4848,19 +5022,24 @@ async function daemonCommand(argv) {
4848
5022
  if (sub === "stop") {
4849
5023
  knownProfile(g);
4850
5024
  const stopFor = seconds(parsed, 20);
4851
- const client = await connectDaemon(g.paths);
5025
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4852
5026
  if (!client) throw new CliError("not_found", `No daemon runs profile ${g.profile}`);
5027
+ const { pid, listen } = await stopDaemon(g, client, stopFor);
5028
+ if (listen) process.stderr.write(listenEnded(pid));
4853
5029
  print({
4854
5030
  stopped: true,
4855
- pid: await stopDaemon(g, client, stopFor)
5031
+ pid,
5032
+ ...listen && { listen: true }
4856
5033
  });
4857
5034
  return;
4858
5035
  }
4859
5036
  if (sub === "restart") {
4860
5037
  const stopFor = seconds(parsed, 20), startFor = seconds(parsed, 60);
4861
- const client = await connectDaemon(g.paths);
5038
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4862
5039
  const probe = client ? client.call("status").catch(() => null) : null;
4863
- const stopped = client ? await stopDaemon(g, client, stopFor) : null;
5040
+ const ended = client ? await stopDaemon(g, client, stopFor) : null;
5041
+ const stopped = ended?.pid ?? null;
5042
+ if (ended?.listen) process.stderr.write(listenEnded(ended.pid));
4864
5043
  const before = (await probe)?.version ?? null;
4865
5044
  let started;
4866
5045
  try {
@@ -4877,6 +5056,7 @@ async function daemonCommand(argv) {
4877
5056
  print({
4878
5057
  restarted: true,
4879
5058
  stopped,
5059
+ ...ended?.listen && { listen: true },
4880
5060
  before,
4881
5061
  version: VERSION,
4882
5062
  ...started
@@ -4891,6 +5071,24 @@ async function daemonCommand(argv) {
4891
5071
  }
4892
5072
  print(await startDetached(g, startFor));
4893
5073
  }
5074
+ /**
5075
+ * The profile's daemon that is starting (`startingDaemon`: it holds the profile, its socket does not listen yet), once
5076
+ * its socket answers, waited for up to `seconds`; null when none is starting. One still starting then is the answer,
5077
+ * `timeout` with its pid. `daemon stop` said no daemon ran, and the daemon came up a moment later; `daemon restart`
5078
+ * failed busy and left the old code running.
5079
+ */
5080
+ async function startedDaemon(g, seconds) {
5081
+ const until = Date.now() + seconds * 1e3;
5082
+ for (;;) {
5083
+ const pid = startingDaemon(g.paths);
5084
+ const client = await connectDaemon(g.paths);
5085
+ if (client) return client;
5086
+ if (pid === null) return null;
5087
+ const left = until - Date.now();
5088
+ if (left <= 0) throw new CliError("timeout", `The daemon (process ${pid}) is still starting after ${seconds} s; ghostly daemon status shows when it is up`, { pid });
5089
+ await new Promise((resolve) => setTimeout(resolve, Math.min(100, left)));
5090
+ }
5091
+ }
4894
5092
  /** `--timeout <s>`, or `fallback` without one: seconds above 0 (0 or less would not wait at all). */
4895
5093
  function seconds(parsed, fallback) {
4896
5094
  const value = parsed.options.timeout;
@@ -4906,9 +5104,9 @@ function seconds(parsed, fallback) {
4906
5104
  * `process.kill` with either name is TerminateProcess: the first signal ends it, there is no second.
4907
5105
  */
4908
5106
  async function stopDaemon(g, client, seconds) {
4909
- let pid, answered = true;
5107
+ let pid, answered = true, listen = false;
4910
5108
  try {
4911
- ({pid} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
5109
+ ({pid, listen = false} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
4912
5110
  } catch (error) {
4913
5111
  const refused = isNotTheDaemon(error);
4914
5112
  if (!(error instanceof CliError && error.code === "timeout") && !refused) throw error;
@@ -4930,14 +5128,24 @@ async function stopDaemon(g, client, seconds) {
4930
5128
  }
4931
5129
  return !running();
4932
5130
  };
4933
- if (await gone()) return pid;
5131
+ if (await gone()) return {
5132
+ pid,
5133
+ listen
5134
+ };
4934
5135
  if (!answered) {
4935
5136
  process.stderr.write(`ghostly: the daemon (process ${pid}) did not stop on SIGTERM in ${seconds} s: killing it\n`);
4936
5137
  signal(pid, "SIGKILL");
4937
- if (await gone()) return pid;
5138
+ if (await gone()) return {
5139
+ pid,
5140
+ listen
5141
+ };
4938
5142
  }
4939
5143
  throw new CliError("timeout", `The daemon (process ${pid}) has not stopped yet`, { pid });
4940
5144
  }
5145
+ /** What `daemon stop` and `restart` say of a daemon that was a `listen` running the profile: that listen is over. */
5146
+ function listenEnded(pid) {
5147
+ return `ghostly: the daemon (process ${pid}) was a ghostly listen running the profile: it ended with it. Start ghostly daemon --detach, then listen through it, so that a restart does not end the listen\n`;
5148
+ }
4941
5149
  /** Throws busy, with its pid, when a process other than `except` holds the profile. */
4942
5150
  function heldBy(g, except) {
4943
5151
  const owner = lockOwner(g.paths);
@@ -5111,7 +5319,7 @@ async function listenCommand(argv) {
5111
5319
  type: "string",
5112
5320
  description: ""
5113
5321
  }
5114
- });
5322
+ }, void 0, { command: "listen" });
5115
5323
  noMoreThan(0, parsed.positionals, SPECIAL.find(([usage]) => usage.startsWith("listen "))[0]);
5116
5324
  const blank = (value) => typeof value === "string" && value.trim() === "";
5117
5325
  if (blank(parsed.options.webhook)) throw new CliError("usage", "--webhook needs a URL");
@@ -5164,9 +5372,10 @@ async function listenCommand(argv) {
5164
5372
  });
5165
5373
  };
5166
5374
  requireProfile(g);
5167
- const client = await connectDaemon(g.paths);
5168
- if (client) await warnVersion(client);
5169
- if (client) {
5375
+ const opened = await connectDaemon(g.paths) ?? await openOneShot(g, {}, "daemon");
5376
+ if (opened instanceof DaemonClient) {
5377
+ const client = opened;
5378
+ await warnVersion(client);
5170
5379
  const handle = await start((m, p) => client.call(m, p), async (chat) => {
5171
5380
  const c = await connectDaemon(g.paths, 1e3);
5172
5381
  if (!c) return null;
@@ -5194,8 +5403,8 @@ async function listenCommand(argv) {
5194
5403
  process.on("SIGTERM", stop);
5195
5404
  return;
5196
5405
  }
5197
- const [{ keepServing, openHost, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5198
- const host = await openHost(g.paths, "daemon", VERSION);
5406
+ const [{ keepServing, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5407
+ const host = opened;
5199
5408
  const call = (m, p) => callApi(host.ctx, m, p);
5200
5409
  const handle = await start(call, async (chat) => (await call("chat.get", { chat })).peer || null).catch(async (error) => {
5201
5410
  await host.close();
@@ -5214,7 +5423,13 @@ async function listenCommand(argv) {
5214
5423
  setTimeout(() => process.exit(code), 2e4).unref();
5215
5424
  served.close().then(() => host.close()).finally(() => process.exit(code));
5216
5425
  };
5217
- host.ctx.stop = stop;
5426
+ host.ctx.listen = true;
5427
+ host.ctx.stop = () => {
5428
+ const message = `This listen ran profile ${g.profile} as its daemon, and was stopped over the socket (ghostly daemon stop or restart, or the profile was cleared)`;
5429
+ process.stderr.write(`ghostly: ${message}. Start ghostly daemon --detach first, then listen through it: a restart then does not end the listen\n`);
5430
+ print({ error: new CliError("unavailable", message).toJSON() });
5431
+ quit(EXIT.unavailable);
5432
+ };
5218
5433
  onStopSignals(stop);
5219
5434
  onReaderGone(stop);
5220
5435
  let off = null, left = [];
@@ -5271,7 +5486,7 @@ async function engineCommand(argv) {
5271
5486
  type: "boolean",
5272
5487
  description: ""
5273
5488
  }
5274
- });
5489
+ }, void 0, { command: "engine" });
5275
5490
  const g = globals(parsed);
5276
5491
  pretty = g.pretty;
5277
5492
  if (parsed.options.list) {
@@ -5316,7 +5531,10 @@ async function settingsCommand(sub, argv) {
5316
5531
  const parsed = parseArgs(argv, { "show-secret": {
5317
5532
  type: "boolean",
5318
5533
  description: ""
5319
- } });
5534
+ } }, void 0, {
5535
+ command: commandOf("settings", sub),
5536
+ text: sub === "set"
5537
+ });
5320
5538
  const g = globals(parsed);
5321
5539
  pretty = g.pretty;
5322
5540
  if (sub === "get") {
@@ -5325,9 +5543,11 @@ async function settingsCommand(sub, argv) {
5325
5543
  return;
5326
5544
  }
5327
5545
  if (sub === "set") {
5328
- const [key, value] = parsed.positionals;
5329
- if (!key || value === void 0) throw new CliError("usage", `Missing <${key ? "json-value" : "key"}>: ghostly settings set <key> <json-value>`);
5546
+ const [key, given] = parsed.positionals;
5547
+ if (!key) throw new CliError("usage", "Missing <key>: ghostly settings set <key> <json-value>");
5330
5548
  noMoreThan(2, parsed.positionals, "settings set <key> <json-value>");
5549
+ const { value, warning } = await settingValue(key, given, readStdin, process.stdin.isTTY === true, (note) => process.stderr.write(`ghostly: ${note}\n`));
5550
+ if (warning) process.stderr.write(`ghostly: ${warning}\n`);
5331
5551
  let parsedValue;
5332
5552
  try {
5333
5553
  parsedValue = JSON.parse(value);
@@ -5342,7 +5562,10 @@ async function settingsCommand(sub, argv) {
5342
5562
  }
5343
5563
  async function textCommand(name, argv) {
5344
5564
  const spec = TEXT_COMMANDS[name];
5345
- const parsed = parseArgs(argv, spec.options, idSlot(spec));
5565
+ const parsed = parseArgs(argv, spec.options, idSlot(spec), {
5566
+ command: name,
5567
+ text: true
5568
+ });
5346
5569
  const g = globals(parsed);
5347
5570
  pretty = g.pretty;
5348
5571
  const [target, ...rest] = parsed.positionals;
@@ -5366,7 +5589,7 @@ async function textCommand(name, argv) {
5366
5589
  };
5367
5590
  if (spec.target === "group") params.mentions = parsed.options.mention ?? [];
5368
5591
  if (parsed.options.reply !== void 0) params.reply = parsed.options.reply;
5369
- if (!spec.message) Object.assign(params, (await import("./buttons-Be7u0V5g.js")).buttonsOf(parsed.options));
5592
+ if (!spec.message) Object.assign(params, (await import("./buttons-YtAj3R_E.js")).buttonsOf(parsed.options));
5370
5593
  print(await withSession(g, (s) => {
5371
5594
  if (spec.target === "chat") {
5372
5595
  params.wait = parsed.options.wait ?? (s.mode === "one-shot" ? spec.message ? "confirmed" : "sent" : "none");
@@ -5405,14 +5628,14 @@ async function identityAddCommand(argv) {
5405
5628
  type: "number",
5406
5629
  description: ""
5407
5630
  }
5408
- });
5631
+ }, void 0, { command: "identity add" });
5409
5632
  const g = globals(parsed);
5410
5633
  pretty = g.pretty;
5411
5634
  const [provider, ...subject] = parsed.positionals;
5412
5635
  if (!provider) throw new CliError("usage", "Missing <provider>: ghostly identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]");
5413
5636
  inRange(parsed.options, "timeout", "a number of seconds", 5, 3600);
5414
5637
  const items = parsed.options.field ?? [];
5415
- const known = parsed.options.days !== void 0 || items.length ? (await import("./registry-CFtlhWCI.js")).IDENTITY_PROVIDERS.find((p) => p.id === provider) : void 0;
5638
+ const known = parsed.options.days !== void 0 || items.length ? (await import("./registry-BmS02J5h.js")).IDENTITY_PROVIDERS.find((p) => p.id === provider) : void 0;
5416
5639
  if (known && parsed.options.days !== void 0) inRange(parsed.options, "days", "a whole number", 1, known.validity.maxDays, true);
5417
5640
  const { fields, warning } = await identityFields(items, parsed.options.stdin === true, identitySecretFields(known, parsed.options.signer), readStdin, process.stdin.isTTY === true);
5418
5641
  if (warning) process.stderr.write(`ghostly: ${warning}\n`);
@@ -5427,9 +5650,7 @@ async function identityAddCommand(argv) {
5427
5650
  const tell = (event) => {
5428
5651
  if (event.type === "identity.approval" || event.type === "identity.progress") process.stderr.write(JSON.stringify(event) + "\n");
5429
5652
  };
5430
- requireProfile(g);
5431
- const client = await connectDaemon(g.paths);
5432
- if (client) {
5653
+ const addThroughDaemon = async (client) => {
5433
5654
  await warnVersion(client);
5434
5655
  const watcher = await connectDaemon(g.paths);
5435
5656
  await watcher?.subscribe(void 0, tell);
@@ -5439,10 +5660,19 @@ async function identityAddCommand(argv) {
5439
5660
  client.close();
5440
5661
  watcher?.close();
5441
5662
  }
5663
+ };
5664
+ requireProfile(g);
5665
+ const client = await connectDaemon(g.paths);
5666
+ if (client) {
5667
+ await addThroughDaemon(client);
5442
5668
  return;
5443
5669
  }
5444
5670
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5445
5671
  const host = await openOneShot(g);
5672
+ if (host instanceof DaemonClient) {
5673
+ await addThroughDaemon(host);
5674
+ return;
5675
+ }
5446
5676
  const off = host.ctx.hub.onEvent(tell);
5447
5677
  try {
5448
5678
  const result = await callApi(host.ctx, "identity.add", params);
@@ -5458,7 +5688,10 @@ async function identityAddCommand(argv) {
5458
5688
  }
5459
5689
  async function tableCommand(name, argv) {
5460
5690
  const command = COMMANDS[name];
5461
- const parsed = parseArgs(argv, command.options ?? {}, idSlot(command));
5691
+ const parsed = parseArgs(argv, command.options ?? {}, idSlot(command), {
5692
+ command: name,
5693
+ text: takesText(command)
5694
+ });
5462
5695
  const g = globals(parsed);
5463
5696
  pretty = g.pretty;
5464
5697
  const args = positionals(command, parsed.positionals);
@@ -5512,7 +5745,7 @@ async function tableCommand(name, argv) {
5512
5745
  });
5513
5746
  if (translator) {
5514
5747
  try {
5515
- printAnswer(await (await import("./translate-DObb-1tq.js")).translateAnswer(result, translator));
5748
+ printAnswer(await (await import("./translate-2WyaRVCr.js")).translateAnswer(result, translator));
5516
5749
  } finally {
5517
5750
  translator.close();
5518
5751
  }
@@ -5525,7 +5758,7 @@ async function tableCommand(name, argv) {
5525
5758
  * contact's, raw PCM); what the command says goes to stderr. It ends when the call does.
5526
5759
  */
5527
5760
  async function callPipeCommand(argv) {
5528
- const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }));
5761
+ const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }), { command: "call pipe" });
5529
5762
  const g = globals(parsed);
5530
5763
  const ref = parsed.positionals.join(" ") || void 0;
5531
5764
  const client = await connectDaemon(g.paths);
@@ -5568,15 +5801,23 @@ function helpAsked(argv) {
5568
5801
  if (head.some((word) => word === "--help" || word === "--help=true" || word === "-h")) return words(head);
5569
5802
  return null;
5570
5803
  }
5804
+ /** No profile yet in the Ghostly folder these global options name: `ghostly`'s first run there. */
5805
+ function newHome(argv) {
5806
+ try {
5807
+ return listProfiles(ghostlyHome(parseArgs([...argv], {}).options.home)).length === 0;
5808
+ } catch {
5809
+ return false;
5810
+ }
5811
+ }
5571
5812
  async function main(input) {
5572
5813
  const argv = liftGlobals(input);
5573
5814
  const helpFor = argv.length === 0 || globalOption(argv[0]) ? [] : helpAsked(argv);
5574
5815
  if (helpFor) {
5575
- process.stdout.write((helpFor.length ? commandHelp(helpFor) : help()) + "\n");
5816
+ process.stdout.write((helpFor.length ? commandHelp(helpFor) : help(argv[0] !== "help" && newHome(argv))) + "\n");
5576
5817
  return 0;
5577
5818
  }
5578
5819
  if (argv[0] === "--version" || argv[0] === "version") {
5579
- const parsed = parseArgs(argv.slice(1), {});
5820
+ const parsed = parseArgs(argv.slice(1), {}, void 0, { command: "version" });
5580
5821
  noMoreThan(0, parsed.positionals, "version");
5581
5822
  pretty = parsed.options.pretty === true;
5582
5823
  print({ version: VERSION });
@@ -5640,6 +5881,7 @@ async function main(input) {
5640
5881
  * A command line that names no command. The words of a group (`ghostly chat`, `ghostly wallet frob`, `ghostly x401
5641
5882
  * credential`) are answered with the group's commands, as `ghostly help chat` lists them; before, it was only "Unknown
5642
5883
  * command: chat". The longest group the words name answers: `x401 credential frob` lists add, list and remove.
5884
+ * A word near one of them is a typo: `chat lst` and `sned hi` say the command meant (`chat list`, `send`) and its help.
5643
5885
  */
5644
5886
  function unknownCommand(first, second, third) {
5645
5887
  const asked = [
@@ -5648,14 +5890,24 @@ function unknownCommand(first, second, third) {
5648
5890
  third
5649
5891
  ].filter((word) => !!word);
5650
5892
  const all = helpRows().map((row) => commandWords(row.usage));
5893
+ const takes = (group) => [...new Set(all.filter((words) => words.length > group.length && group.every((word, i) => words[i] === word)).map((words) => words[group.length]))];
5894
+ const meant = (typed, words) => new CliError("usage", `Unknown command: ${typed.join(" ")} (did you mean ${words.join(" ")}? ghostly help ${words.join(" ")})`);
5651
5895
  for (let depth = Math.min(asked.length, 2); depth >= 1; depth--) {
5652
5896
  const group = asked.slice(0, depth), name = group.join(" "), extra = asked[depth];
5653
- const subs = [...new Set(all.filter((words) => words.length > depth && group.every((word, i) => words[i] === word)).map((words) => words[depth]))];
5897
+ const subs = takes(group);
5654
5898
  if (!subs.length) continue;
5899
+ const near = extra === void 0 ? void 0 : nearest(extra, subs);
5900
+ if (near) return meant([...group, extra], [...group, near]);
5655
5901
  const list = `${subs.slice(0, -1).join(", ")}${subs.length > 1 ? " or " : ""}${subs.at(-1)}`;
5656
5902
  return new CliError("usage", extra ? `Unknown command: ${name} ${extra}: ghostly ${name} takes ${list} (ghostly help ${name})` : `ghostly ${name} takes a command: ${list} (ghostly help ${name})`);
5657
5903
  }
5658
- return new CliError("usage", `Unknown command: ${asked.slice(0, 2).join(" ") || "\"\""} (ghostly help)`);
5904
+ const near = asked[0] === void 0 ? void 0 : nearest(asked[0], takes([]));
5905
+ if (!near) return new CliError("usage", `Unknown command: ${asked[0] ?? "\"\""} (ghostly help)`);
5906
+ return asked[1] !== void 0 && takes([near]).includes(asked[1]) ? meant(asked.slice(0, 2), [near, asked[1]]) : meant([asked[0]], [near]);
5907
+ }
5908
+ /** The command a group's word names (`profile set`), for its usage errors; the group itself for a word it does not take. */
5909
+ function commandOf(group, sub) {
5910
+ return sub !== void 0 && helpRows().some((row) => commandWords(row.usage).join(" ") === `${group} ${sub}`) ? `${group} ${sub}` : group;
5659
5911
  }
5660
5912
  /** Leaves once what was printed reached stdout (a pipe drains asynchronously). */
5661
5913
  function exit(code) {
@@ -5691,4 +5943,4 @@ async function run(argv) {
5691
5943
  //#endregion
5692
5944
  export { run };
5693
5945
 
5694
- //# sourceMappingURL=main-6QOSvQ8b.js.map
5946
+ //# sourceMappingURL=main-BX4oPWCJ.js.map