@ghostlytools/cli 1.7.2 → 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 (96) hide show
  1. package/README.md +37 -24
  2. package/SKILL.md +10 -4
  3. package/dist/assets/{api-CcuCtc1H.js → api-Chhvpwok.js} +2 -2
  4. package/dist/assets/{api-tSZELCPQ.js → api-D3i2hwy0.js} +340 -155
  5. package/dist/assets/api-D3i2hwy0.js.map +1 -0
  6. package/dist/assets/{apiKit-BFk7GAk9.js → apiKit-BtsHrnoo.js} +60 -8
  7. package/dist/assets/apiKit-BtsHrnoo.js.map +1 -0
  8. package/dist/assets/{apps-D6THreq_.js → apps-BFJTqvAt.js} +1 -1
  9. package/dist/assets/{apps-C5Mi6x9Q.js → apps-BHl97rHs.js} +11 -9
  10. package/dist/assets/apps-BHl97rHs.js.map +1 -0
  11. package/dist/assets/{arkade-Cz0B9bJ0.js → arkade-BFE8KkEE.js} +2 -2
  12. package/dist/assets/{arkade-Cz0B9bJ0.js.map → arkade-BFE8KkEE.js.map} +1 -1
  13. package/dist/assets/{backup-A0hIa9GE.js → backup-Bbsr6nDi.js} +1 -1
  14. package/dist/assets/{backup-Wb2sm2dd.js → backup-CxACdtQX.js} +7 -7
  15. package/dist/assets/{backup-Wb2sm2dd.js.map → backup-CxACdtQX.js.map} +1 -1
  16. package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
  17. package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
  18. package/dist/assets/{buttons-Cf70NVYq.js → buttons-CieBtXEO.js} +35 -9
  19. package/dist/assets/buttons-CieBtXEO.js.map +1 -0
  20. package/dist/assets/buttons-YtAj3R_E.js +2 -0
  21. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-QmtwDj-N.js} +2 -2
  22. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-QmtwDj-N.js.map} +1 -1
  23. package/dist/assets/{envelope-kQ5kYjVE.js → envelope-DYiGwzq_.js} +2 -2
  24. package/dist/assets/{envelope-kQ5kYjVE.js.map → envelope-DYiGwzq_.js.map} +1 -1
  25. package/dist/assets/{errors-mnjSQlbX.js → errors-QUGP-jIF.js} +2 -2
  26. package/dist/assets/errors-QUGP-jIF.js.map +1 -0
  27. package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
  28. package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
  29. package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
  30. package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
  31. package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
  32. package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
  33. package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
  34. package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
  35. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
  36. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
  37. package/dist/assets/{groupFiles-D9Ttlm3M.js → groupFiles-CBJIEvCE.js} +572 -6
  38. package/dist/assets/groupFiles-CBJIEvCE.js.map +1 -0
  39. package/dist/assets/{host-DpypH-fR.js → host-Va-r_KJz.js} +84 -23
  40. package/dist/assets/host-Va-r_KJz.js.map +1 -0
  41. package/dist/assets/{hyperdhtRelay-D1rj84v2.js → hyperdhtRelay-B2uK9tJv.js} +2 -2
  42. package/dist/assets/{hyperdhtRelay-D1rj84v2.js.map → hyperdhtRelay-B2uK9tJv.js.map} +1 -1
  43. package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
  44. package/dist/assets/idb-BkOJES5_.js.map +1 -0
  45. package/dist/assets/{irohWeb-BTSlWgEX.js → irohWeb-DxeEgQ-W.js} +2 -2
  46. package/dist/assets/{irohWeb-BTSlWgEX.js.map → irohWeb-DxeEgQ-W.js.map} +1 -1
  47. package/dist/assets/{main-BwgoQZVu.js → main-BX4oPWCJ.js} +589 -192
  48. package/dist/assets/main-BX4oPWCJ.js.map +1 -0
  49. package/dist/assets/{mainline-B1urhbEZ.js → mainline-IfWQOB-J.js} +39 -12
  50. package/dist/assets/mainline-IfWQOB-J.js.map +1 -0
  51. package/dist/assets/{networkReason-D2Z0BdIj.js → networkReason-N2vAaoth.js} +3 -3
  52. package/dist/assets/{networkReason-D2Z0BdIj.js.map → networkReason-N2vAaoth.js.map} +1 -1
  53. package/dist/assets/{nwc-T2aUK6bi.js → nwc-CzyCtNK2.js} +3 -3
  54. package/dist/assets/{nwc-T2aUK6bi.js.map → nwc-CzyCtNK2.js.map} +1 -1
  55. package/dist/assets/{nwcProvider-Dz-ty_DE.js → nwcProvider-DjWmEn3j.js} +2 -2
  56. package/dist/assets/{nwcProvider-Dz-ty_DE.js.map → nwcProvider-DjWmEn3j.js.map} +1 -1
  57. package/dist/assets/{profiles-C6XWqre5.js → profiles-DcCeOi7J.js} +104 -10
  58. package/dist/assets/profiles-DcCeOi7J.js.map +1 -0
  59. package/dist/assets/{registry-BlSTJlbv.js → registry-BmS02J5h.js} +1 -1
  60. package/dist/assets/{registry-Bazitl0a.js → registry-CeW8XEQc.js} +45 -14
  61. package/dist/assets/registry-CeW8XEQc.js.map +1 -0
  62. package/dist/assets/{resolve-Bx1Eeg-w.js → resolve-BvHkAhDH.js} +66 -29
  63. package/dist/assets/resolve-BvHkAhDH.js.map +1 -0
  64. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-mTTp3XNs.js} +2 -2
  65. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-mTTp3XNs.js.map} +1 -1
  66. package/dist/assets/{server-CnPj9wWh.js → server-BUcJo4vz.js} +1033 -821
  67. package/dist/assets/server-BUcJo4vz.js.map +1 -0
  68. package/dist/assets/{src-BsznF3XG.js → src-BB5-5P3s.js} +645 -196
  69. package/dist/assets/src-BB5-5P3s.js.map +1 -0
  70. package/dist/assets/{translate-cDBotA-b.js → translate-2WyaRVCr.js} +11 -9
  71. package/dist/assets/translate-2WyaRVCr.js.map +1 -0
  72. package/dist/assets/{usdt-DxxLdG60.js → usdt-BLazHiaP.js} +3 -3
  73. package/dist/assets/{usdt-DxxLdG60.js.map → usdt-BLazHiaP.js.map} +1 -1
  74. package/dist/assets/{words-qH8gGtmc.js → words-BaumxjXe.js} +5 -3
  75. package/dist/assets/words-BaumxjXe.js.map +1 -0
  76. package/dist/ghostly.mjs +1 -1
  77. package/package.json +1 -1
  78. package/dist/assets/api-tSZELCPQ.js.map +0 -1
  79. package/dist/assets/apiKit-BFk7GAk9.js.map +0 -1
  80. package/dist/assets/apps-C5Mi6x9Q.js.map +0 -1
  81. package/dist/assets/buttons-Bxxu3lSk.js +0 -2
  82. package/dist/assets/buttons-Cf70NVYq.js.map +0 -1
  83. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  84. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  85. package/dist/assets/groupFiles-D9Ttlm3M.js.map +0 -1
  86. package/dist/assets/host-DpypH-fR.js.map +0 -1
  87. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  88. package/dist/assets/main-BwgoQZVu.js.map +0 -1
  89. package/dist/assets/mainline-B1urhbEZ.js.map +0 -1
  90. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  91. package/dist/assets/registry-Bazitl0a.js.map +0 -1
  92. package/dist/assets/resolve-Bx1Eeg-w.js.map +0 -1
  93. package/dist/assets/server-CnPj9wWh.js.map +0 -1
  94. package/dist/assets/src-BsznF3XG.js.map +0 -1
  95. package/dist/assets/translate-cDBotA-b.js.map +0 -1
  96. package/dist/assets/words-qH8gGtmc.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-BsznF3XG.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-qH8gGtmc.js";
3
- import { i as localFileError, n as EXIT, r as asCliError, t as CliError } from "./errors-mnjSQlbX.js";
4
- import { p as namedByThem, t as CONTACT_KEY } from "./apiKit-BFk7GAk9.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.2",
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
@@ -131,6 +133,10 @@ function parseArgs(argv, spec, idSlot = () => false) {
131
133
  };
132
134
  const positionals = [];
133
135
  const options = {};
136
+ const setBoolean = (name, value) => {
137
+ if (all[name].eitherWay && options[name] !== void 0 && options[name] !== value) throw new CliError("usage", `--${name} or --no-${name}, not both`);
138
+ options[name] = value;
139
+ };
134
140
  for (let i = 0; i < argv.length; i++) {
135
141
  const arg = argv[i];
136
142
  if (arg === "--") {
@@ -149,18 +155,18 @@ function parseArgs(argv, spec, idSlot = () => false) {
149
155
  inline = eq === -1 ? void 0 : arg.slice(eq + 1);
150
156
  } else {
151
157
  const long = byShort.get(arg.slice(1));
152
- 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);
153
159
  name = long;
154
160
  }
155
161
  if (name.startsWith("no-") && all[name.slice(3)]?.type === "boolean" && inline === void 0) {
156
- options[name.slice(3)] = false;
162
+ setBoolean(name.slice(3), false);
157
163
  continue;
158
164
  }
159
165
  const option = all[name];
160
- if (!option) throw new CliError("usage", `Unknown option --${name}`);
166
+ if (!option) throw unknownOption(`--${name}`, all, parsing);
161
167
  if (option.type === "boolean") {
162
168
  if (inline !== void 0 && !["true", "false"].includes(inline)) throw new CliError("usage", `--${name} takes no value`);
163
- options[name] = inline === void 0 ? true : inline === "true";
169
+ setBoolean(name, inline === void 0 || inline === "true");
164
170
  continue;
165
171
  }
166
172
  let value = inline;
@@ -183,7 +189,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
183
189
  }
184
190
  continue;
185
191
  }
186
- 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);
187
193
  positionals.push(arg);
188
194
  }
189
195
  return {
@@ -191,6 +197,47 @@ function parseArgs(argv, spec, idSlot = () => false) {
191
197
  options
192
198
  };
193
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
+ }
194
241
  /** Words as a sentence lists them: "a", "a or b", "a, b or c". */
195
242
  var listed$1 = (words) => words.length > 1 ? `${words.slice(0, -1).join(", ")} or ${words.at(-1)}` : words[0];
196
243
  /** The global option a word names (`--profile`, `--profile=bot`, `-p`), else undefined. */
@@ -610,7 +657,10 @@ function typingFor(options) {
610
657
  if (options.stop === true) throw new CliError("usage", "--for keeps it on: not with --stop");
611
658
  return seconds;
612
659
  }
613
- /** The ranges the API takes (api.ts, files.ts): the most minutes of a `--hold` (a week, HOLD_MAX_MINUTES), seconds. */
660
+ /**
661
+ * The ranges the API takes (api.ts, files.ts): the most minutes of a `--hold` (a week, HOLD_MAX_MINUTES), seconds;
662
+ * `chat connect`'s, the chat link's own wait for a contact (CONNECT_MAX_SECONDS).
663
+ */
614
664
  var HOLD_MINUTES = 10080;
615
665
  var WAIT_SECONDS = 3600;
616
666
  var LONG_WAIT_SECONDS = 86400;
@@ -868,12 +918,21 @@ function quota(card, usage) {
868
918
  if (card.left === void 0 && !used) throw new CliError("usage", `--left is needed (or --used with --limit): ghostly ${usage}`);
869
919
  return card;
870
920
  }
871
- /** 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
+ */
872
930
  function cardTime(value, flag) {
873
931
  if (value === void 0) return void 0;
874
932
  const text = String(value).trim();
875
- const ms = /^\d+$/.test(text) ? milliseconds(text, flag) : Date.parse(text);
876
- 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)}`);
877
936
  return ms;
878
937
  }
879
938
  /** `--run ok`, `--run failed:"CI flaked"`: a run of a routine, recorded as its last. */
@@ -931,7 +990,7 @@ var routineOptions = {
931
990
  },
932
991
  next: {
933
992
  type: "string",
934
- 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}`
935
994
  },
936
995
  run: {
937
996
  type: "string",
@@ -1076,11 +1135,11 @@ var usageOptions = {
1076
1135
  },
1077
1136
  resets: {
1078
1137
  type: "string",
1079
- 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}`
1080
1139
  },
1081
1140
  also: {
1082
1141
  type: "list",
1083
- 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)"
1084
1143
  },
1085
1144
  id: {
1086
1145
  type: "string",
@@ -1150,7 +1209,7 @@ var commands$8 = {
1150
1209
  description: "Replace the three files when they are there"
1151
1210
  }
1152
1211
  },
1153
- run: async ({ options }, a) => (await import("./apps-D6THreq_.js")).initApp(a.dir, {
1212
+ run: async ({ options }, a) => (await import("./apps-BFJTqvAt.js")).initApp(a.dir, {
1154
1213
  name: options.name,
1155
1214
  title: options.title,
1156
1215
  force: options.force === true
@@ -1190,7 +1249,7 @@ var commands$8 = {
1190
1249
  description: "This version's sequence, higher than the bundle at --out's (default: one more than it)"
1191
1250
  }
1192
1251
  },
1193
- run: async ({ options }, a) => (await import("./apps-D6THreq_.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)
1194
1253
  },
1195
1254
  "app revoke": {
1196
1255
  method: "app.revoke",
@@ -1223,7 +1282,7 @@ var commands$8 = {
1223
1282
  description: "Allow --up-to past the bundle's own sequence (versions published from elsewhere)"
1224
1283
  }
1225
1284
  },
1226
- run: async ({ options }, a) => (await import("./apps-D6THreq_.js")).revokeApp(a.dir, keyFile(options.key, "app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>]"), {
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]"), {
1227
1286
  digests: options.digest,
1228
1287
  upTo: options["up-to"],
1229
1288
  reason: options.reason,
@@ -1284,7 +1343,7 @@ var commands$8 = {
1284
1343
  usage: "app verify <bundle|url>",
1285
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",
1286
1345
  args: ["bundle"],
1287
- run: async (_, a) => (await import("./apps-D6THreq_.js")).verifyApp(a.bundle)
1346
+ run: async (_, a) => (await import("./apps-BFJTqvAt.js")).verifyApp(a.bundle)
1288
1347
  },
1289
1348
  "store sign": {
1290
1349
  method: "store.sign",
@@ -1301,7 +1360,7 @@ var commands$8 = {
1301
1360
  description: "The folder to write ghostly-store.json and ghostly-store.sig in (default: the index's)"
1302
1361
  }
1303
1362
  },
1304
- run: async ({ options }, a) => (await import("./apps-D6THreq_.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))
1305
1364
  }
1306
1365
  };
1307
1366
  //#endregion
@@ -1341,7 +1400,7 @@ var commands$7 = {
1341
1400
  rate
1342
1401
  },
1343
1402
  params: ({ options }, a) => {
1344
- if (a.mode !== void 0 && a.mode !== "on" && a.mode !== "off") throw new CliError("usage", "ghostly call auto [on|off] [--from <chat>]... [--rate n]");
1403
+ if (a.mode !== void 0 && a.mode !== "on" && a.mode !== "off") throw new CliError("usage", `call auto takes on or off, not ${JSON.stringify(a.mode)}: ghostly call auto [on|off] [--from <chat>]... [--rate 48000]`);
1345
1404
  if (a.mode !== "on" && (options.from !== void 0 || options.rate !== void 0)) throw new CliError("usage", "--from and --rate go with on: ghostly call auto on --from <chat>");
1346
1405
  refs(options.from, "from", "chat");
1347
1406
  if (a.mode === void 0) return {};
@@ -1385,6 +1444,49 @@ var commands$7 = {
1385
1444
  };
1386
1445
  //#endregion
1387
1446
  //#region src/commands/chats.ts
1447
+ /** `react` and `pin` in a 1:1 chat: until the contact confirmed it, by default without a daemon (the process leaves). */
1448
+ var confirmWait = {
1449
+ wait: {
1450
+ type: "string",
1451
+ choices: ["none", "confirmed"],
1452
+ description: "none or confirmed: until the contact confirmed it, in a 1:1 chat (default: none with a daemon, confirmed without)"
1453
+ },
1454
+ timeout: groupWait.timeout
1455
+ };
1456
+ /** The card commands: in a chat a one-shot stays until the card went out, as `send` (a group has no receipts). */
1457
+ var ONE_SHOT_DEFAULT = (word) => `(default: none with a daemon; without one, ${word} in a chat and none in a group)`;
1458
+ var cardWait = {
1459
+ wait: {
1460
+ type: "string",
1461
+ choices: [
1462
+ "none",
1463
+ "sent",
1464
+ "delivered"
1465
+ ],
1466
+ description: `none, sent or delivered; in a group none or sent: until an edge took it ${ONE_SHOT_DEFAULT("sent")}`
1467
+ },
1468
+ timeout: groupWait.timeout
1469
+ };
1470
+ var cardUpdateWait = {
1471
+ wait: {
1472
+ type: "string",
1473
+ choices: [
1474
+ "none",
1475
+ "confirmed",
1476
+ "sent"
1477
+ ],
1478
+ description: `none, confirmed (a chat's contact took it) or sent (a group's edge took it) ${ONE_SHOT_DEFAULT("confirmed")}`
1479
+ },
1480
+ timeout: groupWait.timeout
1481
+ };
1482
+ var usageWait = {
1483
+ wait: {
1484
+ type: "string",
1485
+ choices: ["none", "sent"],
1486
+ description: `none or sent: until the contact has it in a chat, an edge took it in a group ${ONE_SHOT_DEFAULT("sent")}`
1487
+ },
1488
+ timeout: groupWait.timeout
1489
+ };
1388
1490
  var BUTTON_UPDATE = "button update <chat|group> <message> [--chosen <button>] [--close] [--text <text>] [--force] [--wait none|confirmed|sent] [--timeout s]";
1389
1491
  /** Invites, chats and messages: one entry per command, in alphabetical order (test/commands.test.ts checks). */
1390
1492
  var commands$6 = {
@@ -1463,10 +1565,17 @@ var commands$6 = {
1463
1565
  },
1464
1566
  "chat connect": {
1465
1567
  method: "chat.connect",
1466
- usage: "chat connect <chat>",
1568
+ usage: "chat connect <chat> [--timeout s]",
1467
1569
  summary: "Reconnect a chat now (ends a --hold)",
1468
1570
  args: ["chat"],
1469
- params: (_, { chat }) => ({ chat })
1571
+ options: { timeout: {
1572
+ type: "number",
1573
+ description: `Seconds to wait for the contact (default and at most 90)`
1574
+ } },
1575
+ params: ({ options }, { chat }) => ({
1576
+ chat,
1577
+ timeout: timeout(options, 90)
1578
+ })
1470
1579
  },
1471
1580
  "chat disconnect": {
1472
1581
  method: "chat.disconnect",
@@ -1665,22 +1774,35 @@ var commands$6 = {
1665
1774
  },
1666
1775
  "message delete": {
1667
1776
  method: "chat.delete",
1668
- usage: "message delete <chat|group> <message> [--everyone]",
1777
+ usage: "message delete <chat|group> <message> [--everyone [--wait none|confirmed] [--timeout s]]",
1669
1778
  summary: "Forget a message on this device (the contact keeps theirs); --everyone deletes one of yours, in a chat or a group, from every member's device",
1670
1779
  args: ["chat", "message"],
1671
- options: { everyone: {
1672
- type: "boolean",
1673
- description: "Delete a message of yours for everyone (a chat or a group)"
1674
- } },
1675
- params: ({ options }, a) => ({
1676
- chat: a.chat,
1677
- message: a.message,
1678
- everyone: options.everyone === true
1679
- })
1780
+ options: {
1781
+ everyone: {
1782
+ type: "boolean",
1783
+ description: "Delete a message of yours for everyone (a chat or a group)"
1784
+ },
1785
+ wait: {
1786
+ type: "string",
1787
+ choices: ["none", "confirmed"],
1788
+ description: "With --everyone in a chat: none or confirmed, until the contact has it (default: none with a daemon, confirmed without)"
1789
+ },
1790
+ timeout: wait.timeout
1791
+ },
1792
+ params: ({ options }, a) => {
1793
+ for (const flag of ["wait", "timeout"]) if (options[flag] !== void 0 && options.everyone !== true) throw new CliError("usage", `--${flag} goes with --everyone`);
1794
+ return {
1795
+ chat: a.chat,
1796
+ message: a.message,
1797
+ everyone: options.everyone === true,
1798
+ wait: options.wait,
1799
+ timeout: timeout(options)
1800
+ };
1801
+ }
1680
1802
  },
1681
1803
  "message details": {
1682
1804
  method: "chat.details",
1683
- usage: "message details <chat> <message>",
1805
+ usage: "message details <chat|group> <message>",
1684
1806
  summary: "How a message travelled",
1685
1807
  args: ["chat", "message"],
1686
1808
  params: (_, a) => ({
@@ -1700,41 +1822,51 @@ var commands$6 = {
1700
1822
  },
1701
1823
  "pin": {
1702
1824
  method: "chat.pin",
1703
- usage: "pin <chat|group> <message> | --remove",
1825
+ usage: "pin <chat|group> <message> | --remove [--wait none|confirmed] [--timeout s]",
1704
1826
  summary: "Pin a message at the top of a chat or group (one per chat: it replaces the pinned one); --remove unpins",
1705
1827
  args: ["chat", "message...?"],
1706
- options: { remove: {
1707
- type: "boolean",
1708
- description: "Unpin the chat's pinned message (it names no message)"
1709
- } },
1828
+ options: {
1829
+ remove: {
1830
+ type: "boolean",
1831
+ description: "Unpin the chat's pinned message (it names no message)"
1832
+ },
1833
+ ...confirmWait
1834
+ },
1710
1835
  params: ({ options }, a) => {
1711
1836
  if (a.message === void 0 && options.remove !== true) throw new CliError("usage", "Missing <message>: ghostly pin <chat|group> <message> | --remove");
1712
1837
  if (a.message?.includes(" ")) throw new CliError("usage", "Too many arguments: ghostly pin <chat|group> <message> | --remove");
1713
1838
  return {
1714
1839
  chat: a.chat,
1715
1840
  message: a.message,
1716
- remove: options.remove === true
1841
+ remove: options.remove === true,
1842
+ wait: options.wait,
1843
+ timeout: timeout(options)
1717
1844
  };
1718
1845
  }
1719
1846
  },
1720
1847
  "react": {
1721
1848
  method: "chat.react",
1722
- usage: "react <chat> <message> <emoji> [--remove]",
1849
+ usage: "react <chat> <message> <emoji> [--remove] [--wait none|confirmed] [--timeout s]",
1723
1850
  summary: "React to a message with one emoji (it replaces yours); --remove takes yours back",
1724
1851
  args: [
1725
1852
  "chat",
1726
1853
  "message",
1727
1854
  "emoji...?"
1728
1855
  ],
1729
- options: { remove: {
1730
- type: "boolean",
1731
- description: "Take your reaction back"
1732
- } },
1856
+ options: {
1857
+ remove: {
1858
+ type: "boolean",
1859
+ description: "Take your reaction back"
1860
+ },
1861
+ ...confirmWait
1862
+ },
1733
1863
  params: ({ options }, a) => ({
1734
1864
  chat: a.chat,
1735
1865
  message: a.message,
1736
1866
  emoji: a.emoji,
1737
- remove: options.remove === true
1867
+ remove: options.remove === true,
1868
+ wait: options.wait,
1869
+ timeout: timeout(options)
1738
1870
  })
1739
1871
  },
1740
1872
  "routine send": {
@@ -1748,8 +1880,7 @@ var commands$6 = {
1748
1880
  description: "The routine's id, kept across updates (default: made up)"
1749
1881
  },
1750
1882
  ...routineOptions,
1751
- ...groupWait,
1752
- wait: wait.wait
1883
+ ...cardWait
1753
1884
  },
1754
1885
  params: ({ options }, { chat }) => ({
1755
1886
  chat,
@@ -1768,16 +1899,7 @@ var commands$6 = {
1768
1899
  args: ["chat", "routine"],
1769
1900
  options: {
1770
1901
  ...routineOptions,
1771
- wait: {
1772
- type: "string",
1773
- choices: [
1774
- "none",
1775
- "confirmed",
1776
- "sent"
1777
- ],
1778
- description: "none (default), confirmed (a chat's contact took it) or sent (a group's edge took it)"
1779
- },
1780
- timeout: groupWait.timeout
1902
+ ...cardUpdateWait
1781
1903
  },
1782
1904
  params: ({ options }, a) => ({
1783
1905
  chat: a.chat,
@@ -1826,8 +1948,7 @@ var commands$6 = {
1826
1948
  description: "The task's id, kept across updates (default: made up)"
1827
1949
  },
1828
1950
  ...taskOptions,
1829
- ...groupWait,
1830
- wait: wait.wait
1951
+ ...cardWait
1831
1952
  },
1832
1953
  params: ({ options }, { chat }) => ({
1833
1954
  chat,
@@ -1845,16 +1966,7 @@ var commands$6 = {
1845
1966
  args: ["chat", "task"],
1846
1967
  options: {
1847
1968
  ...taskOptions,
1848
- wait: {
1849
- type: "string",
1850
- choices: [
1851
- "none",
1852
- "confirmed",
1853
- "sent"
1854
- ],
1855
- description: "none (default), confirmed (a chat's contact took it) or sent (a group's edge took it)"
1856
- },
1857
- timeout: groupWait.timeout
1969
+ ...cardUpdateWait
1858
1970
  },
1859
1971
  params: ({ options }, a) => ({
1860
1972
  chat: a.chat,
@@ -1901,10 +2013,11 @@ var commands$6 = {
1901
2013
  args: ["chat?"],
1902
2014
  options: {
1903
2015
  ...usageOptions,
1904
- ...groupWait
2016
+ ...usageWait
1905
2017
  },
1906
2018
  params: ({ options }, { chat }) => {
1907
2019
  if (!chat && options.all !== true) throw new CliError("usage", "Name a chat or group, or give --all: ghostly usage send <chat|--all> --left <percent>");
2020
+ if (chat && options.all === true) throw new CliError("usage", "Name a chat or group or give --all, not both: ghostly usage send <chat|--all> --left <percent>");
1908
2021
  return {
1909
2022
  chat,
1910
2023
  all: options.all === true,
@@ -2479,7 +2592,7 @@ var commands$2 = {
2479
2592
  },
2480
2593
  stdin: {
2481
2594
  type: "boolean",
2482
- description: "The tool's output, from stdin"
2595
+ description: "The tool's output, from stdin (piped to it without the flag is read too)"
2483
2596
  }
2484
2597
  },
2485
2598
  params: ({ options }, a) => {
@@ -3163,6 +3276,11 @@ function idSlot(command) {
3163
3276
  };
3164
3277
  return (index) => at(index) && (shift === 0 || index + shift >= names.length || at(index + shift));
3165
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
+ }
3166
3284
  /**
3167
3285
  * The placeholders a usage line shows for its positionals, in order: `chat pay <chat> <sats> [--memo t]` →
3168
3286
  * ["chat", "sats"]. One that is not a plain `<x>` (`[text... | --text <text>]`) is undefined; the flags end them.
@@ -3367,6 +3485,12 @@ function checkWebhook(url) {
3367
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");
3368
3486
  return parsed;
3369
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
+ */
3370
3494
  function readCursor(path) {
3371
3495
  if (!path || !existsSync(path)) return void 0;
3372
3496
  let text;
@@ -3375,8 +3499,11 @@ function readCursor(path) {
3375
3499
  } catch (error) {
3376
3500
  throw localFileError(error, path) ?? error;
3377
3501
  }
3378
- const value = Number(text.trim());
3379
- 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`);
3380
3507
  }
3381
3508
  /**
3382
3509
  * Whether a cursor can be kept at `path`, asked before anything starts: its folder is there and takes a file. Before, a
@@ -3656,7 +3783,7 @@ var Feed = class {
3656
3783
  pause;
3657
3784
  resume;
3658
3785
  held = false;
3659
- /** `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. */
3660
3787
  constructor(handle, since, pause, resume) {
3661
3788
  this.handle = handle;
3662
3789
  this.since = since;
@@ -3740,6 +3867,9 @@ function followDaemon(address, client, handle, since, holdMs = PAUSE_HOLD_MS, pr
3740
3867
  if (current !== c) return;
3741
3868
  current = null;
3742
3869
  reconnect(1e3);
3870
+ }).then((answer) => {
3871
+ if (feed.since === void 0 && typeof answer?.lastSeq === "number") feed.since = answer.lastSeq;
3872
+ return answer;
3743
3873
  });
3744
3874
  return {
3745
3875
  subscribed: follow(client),
@@ -3839,6 +3969,59 @@ async function textFromStdin(read, command, asked, note) {
3839
3969
  as: "arguments"
3840
3970
  })).replace(/\n$/, "");
3841
3971
  }
3972
+ /**
3973
+ * `identity complete <draft>` with neither --evidence-file nor --stdin, stdin not a terminal: asked with nothing first,
3974
+ * since a published record takes none; a draft that answers it takes a tool's output (`details.needs`) is asked again
3975
+ * with what was piped, read as a send reads its text.
3976
+ */
3977
+ async function completeWithPipedEvidence(call, params, read, note) {
3978
+ try {
3979
+ return await call(params);
3980
+ } catch (error) {
3981
+ if (!(error instanceof CliError) || error.details?.needs !== "evidence") throw error;
3982
+ }
3983
+ const evidence = await readUnasked(read, note, {
3984
+ what: "what the tool printed",
3985
+ missing: "Missing what the tool printed",
3986
+ command: `identity complete ${String(params.draft)}`,
3987
+ as: "--evidence-file f"
3988
+ });
3989
+ return call({
3990
+ ...params,
3991
+ evidence
3992
+ });
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
+ }
3842
4025
  async function readUnasked(read, note, ask) {
3843
4026
  let noteTimer, giveUpTimer;
3844
4027
  const stop = () => {
@@ -3856,6 +4039,39 @@ async function readUnasked(read, note, ask) {
3856
4039
  }
3857
4040
  }
3858
4041
  /**
4042
+ * `identity add`'s fields: each `--field name=value`, then with `--stdin` the `name=value` lines piped to it (a NIP-46
4043
+ * signer's bunker:// link holds the signer's secret). `secret`: the names the signer's form marks `kind: "secret"`
4044
+ * (`identitySecretFields`); one given as a `--field` still goes, with the warning. Neither error repeats a value.
4045
+ */
4046
+ async function identityFields(items, stdin, secret, read, tty = false) {
4047
+ const fields = {};
4048
+ for (const item of items) {
4049
+ const eq = item.indexOf("=");
4050
+ if (eq < 1) throw new CliError("usage", "--field takes name=value, and one has no name or no =");
4051
+ fields[item.slice(0, eq)] = item.slice(eq + 1);
4052
+ }
4053
+ const onLine = secret.filter((name) => fields[name] !== void 0);
4054
+ if (stdin) {
4055
+ if (tty) throw new CliError("usage", "--stdin takes the fields as name=value lines piped to it (… | ghostly identity add <provider> --signer id --stdin), not a terminal");
4056
+ for (const line of (await read()).split(/\r?\n/)) {
4057
+ if (!line.trim()) continue;
4058
+ const eq = line.indexOf("=");
4059
+ if (eq < 1) throw new CliError("usage", "--stdin takes name=value lines, and one has no name or no =");
4060
+ fields[line.slice(0, eq).trim()] = line.slice(eq + 1);
4061
+ }
4062
+ }
4063
+ if (!onLine.length) return { fields };
4064
+ return {
4065
+ fields,
4066
+ warning: `${onLine.map((name) => `--field ${name}`).join(", ")} on the command line shows in ps and the shell's history: give ${onLine.length > 1 ? "them" : "it"} on stdin instead (--stdin, name=value lines)`
4067
+ };
4068
+ }
4069
+ /** The fields a provider's signer marks `kind: "secret"`: the one `--signer` names, or any of its signers when none is. */
4070
+ function identitySecretFields(provider, signer) {
4071
+ const signers = (provider?.signers ?? []).filter((s) => signer === void 0 || s.id === signer);
4072
+ return [...new Set(signers.flatMap((s) => (s.fields ?? []).filter((f) => f.kind === "secret").map((f) => f.name)))];
4073
+ }
4074
+ /**
3859
4075
  * `wallet create --value`: the names given on the command line that the chosen source's form marks `kind: "secret"`
3860
4076
  * (an NWC URI, a macaroon, a rune, an RPC password), as a warning. `list`: a `wallet.list` answer, where the forms are.
3861
4077
  */
@@ -3875,15 +4091,15 @@ var VERSION = package_default.version;
3875
4091
  * command a running daemon answers loads none of them, and starts about as fast as Node does. Statically imported, they
3876
4092
  * cost every command ~100 ms before its socket was opened.
3877
4093
  */
3878
- var engineApi = () => import("./api-CcuCtc1H.js");
3879
- var engineHost = () => import("./host-DpypH-fR.js");
4094
+ var engineApi = () => import("./api-Chhvpwok.js");
4095
+ var engineHost = () => import("./host-Va-r_KJz.js");
3880
4096
  /**
3881
4097
  * `--translate <lang>`'s translator, or null (not asked; or the runtime is not there, said on stderr). Loaded only when
3882
4098
  * asked: the app's message parser it reads costs every other command nothing.
3883
4099
  */
3884
4100
  async function translatorFor(value, home) {
3885
4101
  if (value === void 0) return null;
3886
- const { loadDetector, openTranslator, translateTarget } = await import("./translate-cDBotA-b.js");
4102
+ const { loadDetector, openTranslator, translateTarget } = await import("./translate-2WyaRVCr.js");
3887
4103
  return openTranslator({
3888
4104
  home,
3889
4105
  to: translateTarget(value),
@@ -4100,49 +4316,61 @@ function waitsFor(method, params) {
4100
4316
  async function session(g, options) {
4101
4317
  requireProfile(g);
4102
4318
  const client = await connectDaemon(g.paths);
4103
- if (client) {
4104
- const warned = warnVersion(client);
4105
- const call = async (m, p) => {
4106
- const timeoutMs = answerWithin(m, p ?? {});
4107
- if (timeoutMs === void 0 && !await settlesWithin(warned, ANSWER_MS)) {
4108
- client.destroy();
4109
- 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 });
4110
- }
4111
- return client.call(m, p, { timeoutMs });
4112
- };
4113
- return {
4114
- mode: "daemon",
4115
- call,
4116
- close: async () => {
4117
- await warned;
4118
- client.close();
4119
- }
4120
- };
4121
- }
4319
+ if (client) return throughDaemon(client);
4122
4320
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
4123
4321
  const host = await openOneShot(g, options);
4322
+ if (host instanceof DaemonClient) return throughDaemon(host);
4124
4323
  return {
4125
4324
  mode: "one-shot",
4126
4325
  call: (m, p) => callApi(host.ctx, m, p ?? {}),
4127
4326
  close: () => host.close()
4128
4327
  };
4129
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
+ }
4130
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. */
4131
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;
4132
4352
  /**
4133
4353
  * Opens the profile in this process for a one-shot command. Another one that holds it (a script's `&`, a second
4134
4354
  * terminal) is waited for: both used to fail at once, and a backgrounded send was lost unless the script checked its
4135
- * 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`).
4136
4360
  */
4137
- async function openOneShot(g, options = {}) {
4361
+ async function openOneShot(g, options = {}, mode = "one-shot") {
4138
4362
  const { openHost } = await engineHost();
4139
- const until = Date.now() + HOLDER_WAIT_MS;
4363
+ const from = Date.now();
4140
4364
  for (;;) try {
4141
- return await openHost(g.paths, "one-shot", VERSION, options);
4365
+ return await openHost(g.paths, mode, VERSION, options);
4142
4366
  } catch (error) {
4143
4367
  if (!(error instanceof CliError) || error.code !== "busy") throw error;
4144
- 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();
4145
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 });
4146
4374
  const pid = error.details?.pid;
4147
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);
4148
4376
  }
@@ -4252,7 +4480,7 @@ var SPECIAL = [
4252
4480
  "Keep the profile online (foreground; --detach runs it in the background)",
4253
4481
  {
4254
4482
  detach: o("boolean", "Run in the background (log in the profile folder)"),
4255
- timeout: o("number", "Seconds --detach waits for it to start (default 60)")
4483
+ timeout: o("number", "Seconds it waits for a command that holds the profile, and --detach for it to start (default 60)")
4256
4484
  }
4257
4485
  ],
4258
4486
  [
@@ -4291,7 +4519,7 @@ var SPECIAL = [
4291
4519
  "The profile's settings",
4292
4520
  { "show-secret": o("boolean", "Show credentials too") }
4293
4521
  ],
4294
- ["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"],
4295
4523
  [
4296
4524
  "engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]",
4297
4525
  "Any call of the app's engine, with its own parameters (engine --list --verbose names them)",
@@ -4309,11 +4537,12 @@ var SPECIAL = [
4309
4537
  ],
4310
4538
  ["call pipe [<chat|call>]", "A call's audio on stdin/stdout: raw s16le mono PCM at the call's rate (e.g. with sox or ffmpeg)"],
4311
4539
  [
4312
- "identity add <provider> [subject] [--signer id] [--field name=value]... [--days n]",
4540
+ "identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]",
4313
4541
  "Make an identity proof (a tool's or a published one finishes with identity complete)",
4314
4542
  {
4315
4543
  signer: o("string", "Which signer makes the proof (identity providers lists them)"),
4316
4544
  field: o("list", "A field of the provider's form, name=value"),
4545
+ stdin: o("boolean", "Take the fields as name=value lines on stdin (a signer's link: out of ps and the shell's history)"),
4317
4546
  days: o("number", "How long the proof holds"),
4318
4547
  timeout: o("number", "Seconds to wait for an approval")
4319
4548
  }
@@ -4342,31 +4571,87 @@ function beside(rows, more) {
4342
4571
  }
4343
4572
  return out;
4344
4573
  }
4345
- 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();
4346
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]];
4347
- const width = 58;
4348
4632
  return [
4349
- `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),
4350
4634
  "",
4351
- "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),
4352
4637
  "",
4353
- ...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)),
4354
4639
  "",
4355
4640
  "Options for every command:",
4356
- ...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)),
4357
4642
  "",
4358
- "A <chat> is its id, a unique prefix of it, or its name; a <group> the same. Exit codes: 0 done, 1 failed,",
4359
- "2 usage, 3 not found, 4 timed out, 5 needs --force/--yes/--confirm-real.",
4360
- "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)
4361
4645
  ].join("\n");
4362
4646
  }
4647
+ var EVERY_COMMAND = "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h";
4363
4648
  /** What `ghostly help help` answers. */
4364
- var HELP_USAGE = [
4649
+ var helpUsage = (columns) => [
4365
4650
  "Usage: ghostly help [<command>...]",
4366
4651
  "",
4367
- " 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),
4368
4653
  "",
4369
- "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h"
4654
+ ...paragraph([EVERY_COMMAND], columns)
4370
4655
  ].join("\n");
4371
4656
  /** Every command's help row: usage, summary and, for the table and text commands, their options. */
4372
4657
  function helpRows() {
@@ -4394,7 +4679,8 @@ function commandWords(usage) {
4394
4679
  * options; for a group (`ghostly help file`), the group's commands.
4395
4680
  */
4396
4681
  function commandHelp(words) {
4397
- if (words[0] === "help") return HELP_USAGE;
4682
+ const columns = helpColumns();
4683
+ if (words[0] === "help") return helpUsage(columns);
4398
4684
  const named = (list) => helpRows().filter((row) => {
4399
4685
  const own = commandWords(row.usage);
4400
4686
  return list.every((word, i) => own[i] === word);
@@ -4403,31 +4689,31 @@ function commandHelp(words) {
4403
4689
  let rows = named(words);
4404
4690
  while (!rows.length && words.length > 1) rows = named(words = words.slice(0, -1));
4405
4691
  const asked = words.join(" ");
4406
- if (!rows.length) throw new CliError("usage", `Unknown command: ${asked} (ghostly help)`);
4692
+ if (!rows.length) throw unknownCommand(given[0], given[1], given[2]);
4407
4693
  const exact = rows.filter((row) => commandWords(row.usage).join(" ") === asked);
4408
4694
  if (!exact.length && words.length < given.length) throw unknownCommand(given[0], given[1], given[2]);
4409
4695
  const lines = [];
4410
4696
  for (const row of exact) {
4411
- 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));
4412
4698
  const options = Object.entries(row.options ?? {}).filter(([, o]) => o.description);
4413
4699
  if (options.length) {
4414
4700
  lines.push("", "Options:");
4415
4701
  const labels = options.map(([name, o]) => ` --${o.negatedOnly ? "no-" : ""}${name}${o.type === "boolean" ? "" : ` <${o.type === "number" ? "n" : "value"}>`}`);
4416
4702
  const width = Math.max(26, ...labels.map((label) => label.length + 2));
4417
- 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)));
4418
4704
  }
4419
- 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));
4420
4706
  lines.push("");
4421
4707
  }
4422
4708
  const rest = rows.filter((row) => !exact.includes(row));
4423
4709
  if (rest.length) {
4424
4710
  const width = Math.min(58, Math.max(...rest.map((row) => row.usage.length)));
4425
4711
  const count = `${rest.length}${exact.length ? " more" : ""} command${rest.length === 1 ? "" : "s"}`;
4426
- lines.push(`ghostly ${asked}: ${count} (ghostly help ${asked} <command> for one)`, "");
4427
- 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));
4428
4714
  lines.push("");
4429
4715
  }
4430
- lines.push("Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h");
4716
+ lines.push(...paragraph([EVERY_COMMAND], columns));
4431
4717
  return lines.join("\n");
4432
4718
  }
4433
4719
  async function profileCommand(sub, argv) {
@@ -4477,16 +4763,18 @@ async function profileCommand(sub, argv) {
4477
4763
  },
4478
4764
  "share-profile": {
4479
4765
  type: "boolean",
4480
- description: ""
4766
+ description: "",
4767
+ eitherWay: true
4481
4768
  }
4482
4769
  }
4483
- }[sub ?? ""] ?? {});
4770
+ }[sub ?? ""] ?? {}, void 0, { command: commandOf("profile", sub) });
4484
4771
  const g = globals(parsed);
4485
4772
  pretty = g.pretty;
4486
4773
  switch (sub) {
4487
4774
  case "create": {
4488
4775
  const [name] = parsed.positionals;
4489
- if (!name || parsed.positionals.length > 1) throw new CliError("usage", "ghostly profile create <name>");
4776
+ if (!name) throw new CliError("usage", "Missing <name>: ghostly profile create <name> [--use] [--name <shown name>]");
4777
+ noMoreThan(1, parsed.positionals, "profile create <name> [--use] [--name <shown name>]");
4490
4778
  const shownName = parsed.options.name === void 0 ? void 0 : checkShownName(parsed.options.name);
4491
4779
  const paths = createProfile(g.home, name);
4492
4780
  let shown = null;
@@ -4527,7 +4815,7 @@ async function profileCommand(sub, argv) {
4527
4815
  }
4528
4816
  case "use": {
4529
4817
  const [name] = parsed.positionals;
4530
- if (!name) throw new CliError("usage", "ghostly profile use <name>");
4818
+ if (!name) throw new CliError("usage", "Missing <name>: ghostly profile use <name>");
4531
4819
  noMoreThan(1, parsed.positionals, "profile use <name>");
4532
4820
  selectProfile(g.home, name);
4533
4821
  print({ current: name });
@@ -4542,14 +4830,14 @@ async function profileCommand(sub, argv) {
4542
4830
  const params = {};
4543
4831
  if (parsed.options.name !== void 0) params.name = parsed.options.name;
4544
4832
  if (parsed.options["share-profile"] !== void 0) params.shareProfile = parsed.options["share-profile"];
4545
- if (!Object.keys(params).length) throw new CliError("usage", "ghostly profile set [--name <name>] [--share-profile | --no-share-profile]");
4833
+ if (!Object.keys(params).length) throw new CliError("usage", "Nothing to change: ghostly profile set [--name <name>] [--share-profile | --no-share-profile]");
4546
4834
  print(await withSession(g, (s) => s.call("profile.set", params)));
4547
4835
  return;
4548
4836
  }
4549
4837
  case "backup": {
4550
4838
  noMoreThan(0, parsed.positionals, "profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light]");
4551
4839
  const out = parsed.options.out;
4552
- if (typeof out !== "string") throw new CliError("usage", "ghostly profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light] (or GHOSTLY_BACKUP_PASSPHRASE)");
4840
+ if (typeof out !== "string") throw new CliError("usage", "Missing --out: ghostly profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light]");
4553
4841
  const unsealed = parsed.options.passphrase === false;
4554
4842
  if (parsed.options.passphrase === true) throw new CliError("usage", "The passphrase comes from --passphrase-file or GHOSTLY_BACKUP_PASSPHRASE, never the command line");
4555
4843
  if (unsealed && (parsed.options["passphrase-file"] !== void 0 || process.env.GHOSTLY_BACKUP_PASSPHRASE)) throw new CliError("usage", "A passphrase is set (--passphrase-file or GHOSTLY_BACKUP_PASSPHRASE) and --no-passphrase was given: choose one");
@@ -4571,10 +4859,10 @@ async function profileCommand(sub, argv) {
4571
4859
  }
4572
4860
  case "restore": {
4573
4861
  const [given, name] = parsed.positionals;
4574
- if (!given || !name) throw new CliError("usage", "ghostly profile restore <file> <new profile> [--passphrase-file f] [--use]");
4862
+ if (!given || !name) throw new CliError("usage", `Missing <${given ? "new profile" : "file"}>: ghostly profile restore <file> <new profile> [--passphrase-file f] [--use]`);
4575
4863
  noMoreThan(2, parsed.positionals, "profile restore <file> <new profile> [--passphrase-file f] [--use]");
4576
4864
  const file = here(given);
4577
- const { backupFileProtection, restoreProfile } = await import("./backup-A0hIa9GE.js");
4865
+ const { backupFileProtection, restoreProfile } = await import("./backup-Bbsr6nDi.js");
4578
4866
  const protection = await backupFileProtection(file);
4579
4867
  const paths = await restoreProfile(g.home, checkProfileName(name), file, protection === "none" ? void 0 : backupPassphrase(parsed.options["passphrase-file"], RESTORE_PASSPHRASE));
4580
4868
  if (parsed.options.use) selectProfile(g.home, name);
@@ -4635,11 +4923,30 @@ function backupPassphrase(file, missing = BACKUP_PASSPHRASE) {
4635
4923
  if (!value) throw new CliError("bad_request", `${file} is empty: it holds the backup's passphrase`);
4636
4924
  return value;
4637
4925
  }
4638
- async function runDaemon(g) {
4926
+ /** Set on `startDetached`'s child: its parent waits for the profile and starts it again, so the child does not wait too. */
4927
+ var DETACHED_CHILD = "GHOSTLY_DAEMON_DETACHED";
4928
+ /**
4929
+ * The daemon in this process. A one-shot command that holds the profile for a moment (a bot's `send` in the gap of a
4930
+ * service manager's restart) is waited for until `seconds`, as `daemon --detach` waits for it: the first look used to be
4931
+ * the answer, and the profile was left with no daemon. A daemon that comes up meanwhile is the answer instead.
4932
+ */
4933
+ async function runDaemon(g, seconds) {
4639
4934
  requireProfile(g);
4640
- if (await connectDaemon(g.paths)) throw new CliError("busy", `A daemon already runs profile ${g.profile}`);
4935
+ const detached = process.env[DETACHED_CHILD] === "1";
4936
+ delete process.env[DETACHED_CHILD];
4641
4937
  const { keepServing, openHost, serve } = await engineHost();
4642
- const host = await openHost(g.paths, "daemon", VERSION);
4938
+ const until = Date.now() + seconds * 1e3;
4939
+ let host;
4940
+ for (;;) {
4941
+ if (await connectDaemon(g.paths)) throw new CliError("busy", `A daemon already runs profile ${g.profile}`);
4942
+ try {
4943
+ host = await openHost(g.paths, "daemon", VERSION);
4944
+ break;
4945
+ } catch (error) {
4946
+ if (detached || !(error instanceof CliError) || error.code !== "busy" || Date.now() >= until) throw error;
4947
+ await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(100, until - Date.now()))));
4948
+ }
4949
+ }
4643
4950
  let served;
4644
4951
  try {
4645
4952
  served = await serve(host);
@@ -4677,7 +4984,7 @@ async function daemonCommand(argv) {
4677
4984
  type: "number",
4678
4985
  description: ""
4679
4986
  }
4680
- });
4987
+ }, void 0, { command: commandOf("daemon", sub) });
4681
4988
  const g = globals(parsed);
4682
4989
  pretty = g.pretty;
4683
4990
  if (!sub || [
@@ -4689,8 +4996,13 @@ async function daemonCommand(argv) {
4689
4996
  knownProfile(g);
4690
4997
  const client = await connectDaemon(g.paths);
4691
4998
  if (!client) {
4999
+ const starting = startingDaemon(g.paths);
4692
5000
  print({
4693
5001
  running: false,
5002
+ ...starting === null ? {} : {
5003
+ starting: true,
5004
+ pid: starting
5005
+ },
4694
5006
  profile: g.profile,
4695
5007
  socket: g.paths.socket
4696
5008
  });
@@ -4710,19 +5022,24 @@ async function daemonCommand(argv) {
4710
5022
  if (sub === "stop") {
4711
5023
  knownProfile(g);
4712
5024
  const stopFor = seconds(parsed, 20);
4713
- const client = await connectDaemon(g.paths);
5025
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4714
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));
4715
5029
  print({
4716
5030
  stopped: true,
4717
- pid: await stopDaemon(g, client, stopFor)
5031
+ pid,
5032
+ ...listen && { listen: true }
4718
5033
  });
4719
5034
  return;
4720
5035
  }
4721
5036
  if (sub === "restart") {
4722
5037
  const stopFor = seconds(parsed, 20), startFor = seconds(parsed, 60);
4723
- const client = await connectDaemon(g.paths);
5038
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4724
5039
  const probe = client ? client.call("status").catch(() => null) : null;
4725
- 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));
4726
5043
  const before = (await probe)?.version ?? null;
4727
5044
  let started;
4728
5045
  try {
@@ -4739,6 +5056,7 @@ async function daemonCommand(argv) {
4739
5056
  print({
4740
5057
  restarted: true,
4741
5058
  stopped,
5059
+ ...ended?.listen && { listen: true },
4742
5060
  before,
4743
5061
  version: VERSION,
4744
5062
  ...started
@@ -4748,11 +5066,29 @@ async function daemonCommand(argv) {
4748
5066
  if (sub) throw unknownCommand("daemon", sub);
4749
5067
  const startFor = seconds(parsed, 60);
4750
5068
  if (!parsed.options.detach) {
4751
- await runDaemon(g);
5069
+ await runDaemon(g, startFor);
4752
5070
  return;
4753
5071
  }
4754
5072
  print(await startDetached(g, startFor));
4755
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
+ }
4756
5092
  /** `--timeout <s>`, or `fallback` without one: seconds above 0 (0 or less would not wait at all). */
4757
5093
  function seconds(parsed, fallback) {
4758
5094
  const value = parsed.options.timeout;
@@ -4768,9 +5104,9 @@ function seconds(parsed, fallback) {
4768
5104
  * `process.kill` with either name is TerminateProcess: the first signal ends it, there is no second.
4769
5105
  */
4770
5106
  async function stopDaemon(g, client, seconds) {
4771
- let pid, answered = true;
5107
+ let pid, answered = true, listen = false;
4772
5108
  try {
4773
- ({pid} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
5109
+ ({pid, listen = false} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
4774
5110
  } catch (error) {
4775
5111
  const refused = isNotTheDaemon(error);
4776
5112
  if (!(error instanceof CliError && error.code === "timeout") && !refused) throw error;
@@ -4792,14 +5128,24 @@ async function stopDaemon(g, client, seconds) {
4792
5128
  }
4793
5129
  return !running();
4794
5130
  };
4795
- if (await gone()) return pid;
5131
+ if (await gone()) return {
5132
+ pid,
5133
+ listen
5134
+ };
4796
5135
  if (!answered) {
4797
5136
  process.stderr.write(`ghostly: the daemon (process ${pid}) did not stop on SIGTERM in ${seconds} s: killing it\n`);
4798
5137
  signal(pid, "SIGKILL");
4799
- if (await gone()) return pid;
5138
+ if (await gone()) return {
5139
+ pid,
5140
+ listen
5141
+ };
4800
5142
  }
4801
5143
  throw new CliError("timeout", `The daemon (process ${pid}) has not stopped yet`, { pid });
4802
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
+ }
4803
5149
  /** Throws busy, with its pid, when a process other than `except` holds the profile. */
4804
5150
  function heldBy(g, except) {
4805
5151
  const owner = lockOwner(g.paths);
@@ -4858,7 +5204,11 @@ async function spawnDaemon(g, until) {
4858
5204
  "ignore",
4859
5205
  log,
4860
5206
  log
4861
- ]
5207
+ ],
5208
+ env: {
5209
+ ...process.env,
5210
+ [DETACHED_CHILD]: "1"
5211
+ }
4862
5212
  });
4863
5213
  closeSync(log);
4864
5214
  child.unref();
@@ -4969,7 +5319,7 @@ async function listenCommand(argv) {
4969
5319
  type: "string",
4970
5320
  description: ""
4971
5321
  }
4972
- });
5322
+ }, void 0, { command: "listen" });
4973
5323
  noMoreThan(0, parsed.positionals, SPECIAL.find(([usage]) => usage.startsWith("listen "))[0]);
4974
5324
  const blank = (value) => typeof value === "string" && value.trim() === "";
4975
5325
  if (blank(parsed.options.webhook)) throw new CliError("usage", "--webhook needs a URL");
@@ -5022,9 +5372,10 @@ async function listenCommand(argv) {
5022
5372
  });
5023
5373
  };
5024
5374
  requireProfile(g);
5025
- const client = await connectDaemon(g.paths);
5026
- if (client) await warnVersion(client);
5027
- 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);
5028
5379
  const handle = await start((m, p) => client.call(m, p), async (chat) => {
5029
5380
  const c = await connectDaemon(g.paths, 1e3);
5030
5381
  if (!c) return null;
@@ -5052,8 +5403,8 @@ async function listenCommand(argv) {
5052
5403
  process.on("SIGTERM", stop);
5053
5404
  return;
5054
5405
  }
5055
- const [{ keepServing, openHost, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5056
- const host = await openHost(g.paths, "daemon", VERSION);
5406
+ const [{ keepServing, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5407
+ const host = opened;
5057
5408
  const call = (m, p) => callApi(host.ctx, m, p);
5058
5409
  const handle = await start(call, async (chat) => (await call("chat.get", { chat })).peer || null).catch(async (error) => {
5059
5410
  await host.close();
@@ -5072,7 +5423,13 @@ async function listenCommand(argv) {
5072
5423
  setTimeout(() => process.exit(code), 2e4).unref();
5073
5424
  served.close().then(() => host.close()).finally(() => process.exit(code));
5074
5425
  };
5075
- 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
+ };
5076
5433
  onStopSignals(stop);
5077
5434
  onReaderGone(stop);
5078
5435
  let off = null, left = [];
@@ -5129,7 +5486,7 @@ async function engineCommand(argv) {
5129
5486
  type: "boolean",
5130
5487
  description: ""
5131
5488
  }
5132
- });
5489
+ }, void 0, { command: "engine" });
5133
5490
  const g = globals(parsed);
5134
5491
  pretty = g.pretty;
5135
5492
  if (parsed.options.list) {
@@ -5142,7 +5499,8 @@ async function engineCommand(argv) {
5142
5499
  return;
5143
5500
  }
5144
5501
  const [method, raw] = parsed.positionals;
5145
- if (!method || parsed.positionals.length > 2) throw new CliError("usage", "ghostly engine <method> [json-params | -]");
5502
+ if (!method) throw new CliError("usage", "Missing <method>: ghostly engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]");
5503
+ noMoreThan(2, parsed.positionals, "engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]");
5146
5504
  if (!ENGINE_METHODS.includes(method) && !ENGINE_READS.includes(method)) throw new CliError("not_found", `The engine has no call ${method} (ghostly engine --list)`);
5147
5505
  const showSecret = parsed.options["show-secret"] === true;
5148
5506
  if (SECRET_RESULTS.has(method) && !showSecret) throw new CliError("confirm", `${method} answers with secrets: add --show-secret to print them`);
@@ -5173,7 +5531,10 @@ async function settingsCommand(sub, argv) {
5173
5531
  const parsed = parseArgs(argv, { "show-secret": {
5174
5532
  type: "boolean",
5175
5533
  description: ""
5176
- } });
5534
+ } }, void 0, {
5535
+ command: commandOf("settings", sub),
5536
+ text: sub === "set"
5537
+ });
5177
5538
  const g = globals(parsed);
5178
5539
  pretty = g.pretty;
5179
5540
  if (sub === "get") {
@@ -5182,8 +5543,11 @@ async function settingsCommand(sub, argv) {
5182
5543
  return;
5183
5544
  }
5184
5545
  if (sub === "set") {
5185
- const [key, value] = parsed.positionals;
5186
- if (!key || value === void 0 || parsed.positionals.length > 2) throw new CliError("usage", "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>");
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`);
5187
5551
  let parsedValue;
5188
5552
  try {
5189
5553
  parsedValue = JSON.parse(value);
@@ -5198,12 +5562,15 @@ async function settingsCommand(sub, argv) {
5198
5562
  }
5199
5563
  async function textCommand(name, argv) {
5200
5564
  const spec = TEXT_COMMANDS[name];
5201
- const parsed = parseArgs(argv, spec.options, idSlot(spec));
5565
+ const parsed = parseArgs(argv, spec.options, idSlot(spec), {
5566
+ command: name,
5567
+ text: true
5568
+ });
5202
5569
  const g = globals(parsed);
5203
5570
  pretty = g.pretty;
5204
5571
  const [target, ...rest] = parsed.positionals;
5205
5572
  const [message, ...words] = spec.message ? rest : [void 0, ...rest];
5206
- if (!target || spec.message && !message) throw new CliError("usage", `ghostly ${spec.usage}`);
5573
+ if (!target || spec.message && !message) throw new CliError("usage", `Missing <${target ? "message" : spec.target}>: ghostly ${spec.usage}`);
5207
5574
  timeout(parsed.options);
5208
5575
  let text = words.join(" ");
5209
5576
  if (parsed.options.text !== void 0) {
@@ -5222,7 +5589,7 @@ async function textCommand(name, argv) {
5222
5589
  };
5223
5590
  if (spec.target === "group") params.mentions = parsed.options.mention ?? [];
5224
5591
  if (parsed.options.reply !== void 0) params.reply = parsed.options.reply;
5225
- if (!spec.message) Object.assign(params, (await import("./buttons-Bxxu3lSk.js")).buttonsOf(parsed.options));
5592
+ if (!spec.message) Object.assign(params, (await import("./buttons-YtAj3R_E.js")).buttonsOf(parsed.options));
5226
5593
  print(await withSession(g, (s) => {
5227
5594
  if (spec.target === "chat") {
5228
5595
  params.wait = parsed.options.wait ?? (s.mode === "one-shot" ? spec.message ? "confirmed" : "sent" : "none");
@@ -5249,6 +5616,10 @@ async function identityAddCommand(argv) {
5249
5616
  type: "list",
5250
5617
  description: ""
5251
5618
  },
5619
+ stdin: {
5620
+ type: "boolean",
5621
+ description: ""
5622
+ },
5252
5623
  days: {
5253
5624
  type: "number",
5254
5625
  description: ""
@@ -5257,22 +5628,17 @@ async function identityAddCommand(argv) {
5257
5628
  type: "number",
5258
5629
  description: ""
5259
5630
  }
5260
- });
5631
+ }, void 0, { command: "identity add" });
5261
5632
  const g = globals(parsed);
5262
5633
  pretty = g.pretty;
5263
5634
  const [provider, ...subject] = parsed.positionals;
5264
- if (!provider) throw new CliError("usage", "ghostly identity add <provider> [subject] [--signer id] [--field name=value]... [--days n]");
5265
- const fields = {};
5266
- for (const item of parsed.options.field ?? []) {
5267
- const eq = item.indexOf("=");
5268
- if (eq < 1) throw new CliError("usage", `--field takes name=value, not ${JSON.stringify(item)}`);
5269
- fields[item.slice(0, eq)] = item.slice(eq + 1);
5270
- }
5635
+ if (!provider) throw new CliError("usage", "Missing <provider>: ghostly identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]");
5271
5636
  inRange(parsed.options, "timeout", "a number of seconds", 5, 3600);
5272
- if (parsed.options.days !== void 0) {
5273
- const known = (await import("./registry-BlSTJlbv.js")).IDENTITY_PROVIDERS.find((p) => p.id === provider);
5274
- if (known) inRange(parsed.options, "days", "a whole number", 1, known.validity.maxDays, true);
5275
- }
5637
+ const items = parsed.options.field ?? [];
5638
+ const known = parsed.options.days !== void 0 || items.length ? (await import("./registry-BmS02J5h.js")).IDENTITY_PROVIDERS.find((p) => p.id === provider) : void 0;
5639
+ if (known && parsed.options.days !== void 0) inRange(parsed.options, "days", "a whole number", 1, known.validity.maxDays, true);
5640
+ const { fields, warning } = await identityFields(items, parsed.options.stdin === true, identitySecretFields(known, parsed.options.signer), readStdin, process.stdin.isTTY === true);
5641
+ if (warning) process.stderr.write(`ghostly: ${warning}\n`);
5276
5642
  const params = {
5277
5643
  provider,
5278
5644
  subject: subject.join(" ") || void 0,
@@ -5284,9 +5650,7 @@ async function identityAddCommand(argv) {
5284
5650
  const tell = (event) => {
5285
5651
  if (event.type === "identity.approval" || event.type === "identity.progress") process.stderr.write(JSON.stringify(event) + "\n");
5286
5652
  };
5287
- requireProfile(g);
5288
- const client = await connectDaemon(g.paths);
5289
- if (client) {
5653
+ const addThroughDaemon = async (client) => {
5290
5654
  await warnVersion(client);
5291
5655
  const watcher = await connectDaemon(g.paths);
5292
5656
  await watcher?.subscribe(void 0, tell);
@@ -5296,10 +5660,19 @@ async function identityAddCommand(argv) {
5296
5660
  client.close();
5297
5661
  watcher?.close();
5298
5662
  }
5663
+ };
5664
+ requireProfile(g);
5665
+ const client = await connectDaemon(g.paths);
5666
+ if (client) {
5667
+ await addThroughDaemon(client);
5299
5668
  return;
5300
5669
  }
5301
5670
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5302
5671
  const host = await openOneShot(g);
5672
+ if (host instanceof DaemonClient) {
5673
+ await addThroughDaemon(host);
5674
+ return;
5675
+ }
5303
5676
  const off = host.ctx.hub.onEvent(tell);
5304
5677
  try {
5305
5678
  const result = await callApi(host.ctx, "identity.add", params);
@@ -5315,7 +5688,10 @@ async function identityAddCommand(argv) {
5315
5688
  }
5316
5689
  async function tableCommand(name, argv) {
5317
5690
  const command = COMMANDS[name];
5318
- 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
+ });
5319
5695
  const g = globals(parsed);
5320
5696
  pretty = g.pretty;
5321
5697
  const args = positionals(command, parsed.positionals);
@@ -5326,6 +5702,7 @@ async function tableCommand(name, argv) {
5326
5702
  const params = command.params?.(parsed, args) ?? {};
5327
5703
  for (const key of Object.keys(params)) if (params[key] === void 0) delete params[key];
5328
5704
  const translator = await translatorFor(parsed.options.translate, g.home);
5705
+ const pipedEvidence = command.method === "identity.complete" && !params.evidenceFile && !params.stdin && process.stdin.isTTY !== true;
5329
5706
  if (command.method === "identity.complete") {
5330
5707
  if (params.evidenceFile) try {
5331
5708
  params.evidence = readFileSync(params.evidenceFile, "utf8");
@@ -5342,7 +5719,8 @@ async function tableCommand(name, argv) {
5342
5719
  } catch (error) {
5343
5720
  throw localFileError(error, params.file) ?? new CliError("usage", `Cannot read the credential: ${error instanceof Error ? error.message : String(error)}`);
5344
5721
  }
5345
- if (!params.credential) throw new CliError("bad_request", params.file === "-" ? "Nothing on stdin: give the SD-JWT VC the issuer sent" : `${params.file} is empty: it holds the SD-JWT VC the issuer sent`);
5722
+ if (!params.credential && params.file === "-") throw new CliError("usage", "Missing <file|->: give the SD-JWT VC on stdin (… | ghostly x401 credential add -) or as a file");
5723
+ if (!params.credential) throw new CliError("bad_request", `${params.file} is empty: it holds the SD-JWT VC the issuer sent`);
5346
5724
  delete params.file;
5347
5725
  }
5348
5726
  const lineValues = command.method === "wallet.create" ? Object.keys(params.values ?? {}) : [];
@@ -5353,7 +5731,7 @@ async function tableCommand(name, argv) {
5353
5731
  const warning = secretValuesWarning(await s.call("wallet.list", { network: params.network ?? "testnet" }).catch(() => void 0), params.type, params.provider, lineValues);
5354
5732
  if (warning) process.stderr.write(`ghostly: ${warning}\n`);
5355
5733
  }
5356
- const result = await s.call(command.method, params);
5734
+ const result = await (pipedEvidence ? completeWithPipedEvidence((p) => s.call(command.method, p), params, readStdin, (note) => process.stderr.write(`ghostly: ${note}\n`)) : s.call(command.method, params));
5357
5735
  if (command.method === "invite.join" && s.mode === "one-shot") {
5358
5736
  const joined = await oneShotJoinWait(s, result, typeof params.label === "string" ? params.label : void 0);
5359
5737
  if (joined.note) process.stderr.write(`ghostly: ${joined.note}\n`);
@@ -5367,7 +5745,7 @@ async function tableCommand(name, argv) {
5367
5745
  });
5368
5746
  if (translator) {
5369
5747
  try {
5370
- printAnswer(await (await import("./translate-cDBotA-b.js")).translateAnswer(result, translator));
5748
+ printAnswer(await (await import("./translate-2WyaRVCr.js")).translateAnswer(result, translator));
5371
5749
  } finally {
5372
5750
  translator.close();
5373
5751
  }
@@ -5380,7 +5758,7 @@ async function tableCommand(name, argv) {
5380
5758
  * contact's, raw PCM); what the command says goes to stderr. It ends when the call does.
5381
5759
  */
5382
5760
  async function callPipeCommand(argv) {
5383
- const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }));
5761
+ const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }), { command: "call pipe" });
5384
5762
  const g = globals(parsed);
5385
5763
  const ref = parsed.positionals.join(" ") || void 0;
5386
5764
  const client = await connectDaemon(g.paths);
@@ -5423,15 +5801,23 @@ function helpAsked(argv) {
5423
5801
  if (head.some((word) => word === "--help" || word === "--help=true" || word === "-h")) return words(head);
5424
5802
  return null;
5425
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
+ }
5426
5812
  async function main(input) {
5427
5813
  const argv = liftGlobals(input);
5428
5814
  const helpFor = argv.length === 0 || globalOption(argv[0]) ? [] : helpAsked(argv);
5429
5815
  if (helpFor) {
5430
- process.stdout.write((helpFor.length ? commandHelp(helpFor) : help()) + "\n");
5816
+ process.stdout.write((helpFor.length ? commandHelp(helpFor) : help(argv[0] !== "help" && newHome(argv))) + "\n");
5431
5817
  return 0;
5432
5818
  }
5433
5819
  if (argv[0] === "--version" || argv[0] === "version") {
5434
- const parsed = parseArgs(argv.slice(1), {});
5820
+ const parsed = parseArgs(argv.slice(1), {}, void 0, { command: "version" });
5435
5821
  noMoreThan(0, parsed.positionals, "version");
5436
5822
  pretty = parsed.options.pretty === true;
5437
5823
  print({ version: VERSION });
@@ -5495,6 +5881,7 @@ async function main(input) {
5495
5881
  * A command line that names no command. The words of a group (`ghostly chat`, `ghostly wallet frob`, `ghostly x401
5496
5882
  * credential`) are answered with the group's commands, as `ghostly help chat` lists them; before, it was only "Unknown
5497
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.
5498
5885
  */
5499
5886
  function unknownCommand(first, second, third) {
5500
5887
  const asked = [
@@ -5503,14 +5890,24 @@ function unknownCommand(first, second, third) {
5503
5890
  third
5504
5891
  ].filter((word) => !!word);
5505
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(" ")})`);
5506
5895
  for (let depth = Math.min(asked.length, 2); depth >= 1; depth--) {
5507
5896
  const group = asked.slice(0, depth), name = group.join(" "), extra = asked[depth];
5508
- 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);
5509
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]);
5510
5901
  const list = `${subs.slice(0, -1).join(", ")}${subs.length > 1 ? " or " : ""}${subs.at(-1)}`;
5511
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})`);
5512
5903
  }
5513
- 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;
5514
5911
  }
5515
5912
  /** Leaves once what was printed reached stdout (a pipe drains asynchronously). */
5516
5913
  function exit(code) {
@@ -5546,4 +5943,4 @@ async function run(argv) {
5546
5943
  //#endregion
5547
5944
  export { run };
5548
5945
 
5549
- //# sourceMappingURL=main-BwgoQZVu.js.map
5946
+ //# sourceMappingURL=main-BX4oPWCJ.js.map