@ghostlytools/cli 1.7.3 → 1.8.0

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 (106) hide show
  1. package/README.md +30 -19
  2. package/SKILL.md +6 -4
  3. package/dist/assets/{api-B42F9ytB.js → api-Dj1yn0px.js} +2 -2
  4. package/dist/assets/{api-tf-wAAnB.js → api-I_KbuXHa.js} +192 -88
  5. package/dist/assets/api-I_KbuXHa.js.map +1 -0
  6. package/dist/assets/{apiKit-DJb9hulp.js → apiKit-C-_PWZvy.js} +44 -9
  7. package/dist/assets/apiKit-C-_PWZvy.js.map +1 -0
  8. package/dist/assets/{apps-DIrWmLgL.js → apps-DKIe8VjF.js} +11 -8
  9. package/dist/assets/apps-DKIe8VjF.js.map +1 -0
  10. package/dist/assets/{apps-BfoDISRg.js → apps-DbEfL_3b.js} +1 -1
  11. package/dist/assets/{arkade-CJAhhgPQ.js → arkade-k1bdSm70.js} +2 -2
  12. package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-k1bdSm70.js.map} +1 -1
  13. package/dist/assets/{backup-BkUeeduy.js → backup-Cdd6-HNu.js} +1 -1
  14. package/dist/assets/{backup-Bko-AAm0.js → backup-beKfbfNk.js} +7 -7
  15. package/dist/assets/{backup-Bko-AAm0.js.map → backup-beKfbfNk.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-BO1_7V4L.js +2 -0
  21. package/dist/assets/{buttons-DeA6Yddq.js → buttons-ClI13rdv.js} +7 -6
  22. package/dist/assets/buttons-ClI13rdv.js.map +1 -0
  23. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-DtrL5lE5.js} +2 -2
  24. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-DtrL5lE5.js.map} +1 -1
  25. package/dist/assets/{envelope-Cz5fc7BM.js → envelope-B88yiCQj.js} +2 -2
  26. package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-B88yiCQj.js.map} +1 -1
  27. package/dist/assets/{errors-mnjSQlbX.js → errors-R4S2SAEM.js} +8 -3
  28. package/dist/assets/errors-R4S2SAEM.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-DjQc5XXv.js} +151 -28
  40. package/dist/assets/groupFiles-DjQc5XXv.js.map +1 -0
  41. package/dist/assets/{host-BX0DmKW6.js → host-CNWGB3-j.js} +86 -24
  42. package/dist/assets/host-CNWGB3-j.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-g7eXzf5h.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-g7eXzf5h.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-Bx8dI4be.js} +2 -2
  48. package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-Bx8dI4be.js.map} +1 -1
  49. package/dist/assets/{main-6QOSvQ8b.js → main-BRxhBctJ.js} +462 -126
  50. package/dist/assets/main-BRxhBctJ.js.map +1 -0
  51. package/dist/assets/{mainline-BfwezHWi.js → mainline-CwuS6ngj.js} +39 -12
  52. package/dist/assets/mainline-CwuS6ngj.js.map +1 -0
  53. package/dist/assets/mints-BaOmx517.js +2 -0
  54. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  55. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  56. package/dist/assets/{networkReason-Ba9415nn.js → networkReason-CIAMieQm.js} +3 -3
  57. package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-CIAMieQm.js.map} +1 -1
  58. package/dist/assets/{nwc-ovXSN2M2.js → nwc-C9JLJJkL.js} +3 -3
  59. package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-C9JLJJkL.js.map} +1 -1
  60. package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-pFMrsUJh.js} +2 -2
  61. package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-pFMrsUJh.js.map} +1 -1
  62. package/dist/assets/{profiles-C6XWqre5.js → profiles-MFtCmJwK.js} +104 -10
  63. package/dist/assets/profiles-MFtCmJwK.js.map +1 -0
  64. package/dist/assets/{registry-B0Uv9yL6.js → registry-Cks7FA_o.js} +45 -14
  65. package/dist/assets/registry-Cks7FA_o.js.map +1 -0
  66. package/dist/assets/{registry-CFtlhWCI.js → registry-DY2ixQfU.js} +1 -1
  67. package/dist/assets/{resolve-BzFG4WDU.js → resolve-C4Y2HPqQ.js} +79 -30
  68. package/dist/assets/resolve-C4Y2HPqQ.js.map +1 -0
  69. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-BCRCjhdF.js} +27 -3
  70. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  71. package/dist/assets/{server-BGCuHbmQ.js → server-D9RAmGdm.js} +1398 -358
  72. package/dist/assets/server-D9RAmGdm.js.map +1 -0
  73. package/dist/assets/{src-DWw2hUE5.js → src-1RU4TilT.js} +1416 -234
  74. package/dist/assets/src-1RU4TilT.js.map +1 -0
  75. package/dist/assets/{translate-DObb-1tq.js → translate-od5GbpvR.js} +19 -13
  76. package/dist/assets/translate-od5GbpvR.js.map +1 -0
  77. package/dist/assets/{usdt-Bkva90Vo.js → usdt-DldXV0MR.js} +3 -3
  78. package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-DldXV0MR.js.map} +1 -1
  79. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  80. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  81. package/dist/assets/{words-odSAoasK.js → words-BS2qq_vV.js} +7 -4
  82. package/dist/assets/words-BS2qq_vV.js.map +1 -0
  83. package/dist/ghostly.mjs +1 -1
  84. package/examples/claude-code-agent.sh +1 -1
  85. package/package.json +1 -1
  86. package/dist/assets/api-tf-wAAnB.js.map +0 -1
  87. package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
  88. package/dist/assets/apps-DIrWmLgL.js.map +0 -1
  89. package/dist/assets/buttons-Be7u0V5g.js +0 -2
  90. package/dist/assets/buttons-DeA6Yddq.js.map +0 -1
  91. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  92. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  93. package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
  94. package/dist/assets/host-BX0DmKW6.js.map +0 -1
  95. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  96. package/dist/assets/main-6QOSvQ8b.js.map +0 -1
  97. package/dist/assets/mainline-BfwezHWi.js.map +0 -1
  98. package/dist/assets/mints-BrlY773j.js.map +0 -1
  99. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  100. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  101. package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
  102. package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
  103. package/dist/assets/server-BGCuHbmQ.js.map +0 -1
  104. package/dist/assets/src-DWw2hUE5.js.map +0 -1
  105. package/dist/assets/translate-DObb-1tq.js.map +0 -1
  106. package/dist/assets/words-odSAoasK.js.map +0 -1
@@ -1,18 +1,19 @@
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 ROUTINE_STATES, Gn as GROUP_FILE_LIMITS, Qa as PR_STATES, Xa as ITEM_STATES, Ya as CRON_LINE, Za as PR_CHECKS, ao as cardLine, eo as RUN_RESULTS, lo as statusCardBytes, no as TASK_STATUSES, oo as cardUrl, pa as VOICE_LIMITS, to as STATUS_CARD_LIMITS } from "./src-1RU4TilT.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-BS2qq_vV.js";
3
+ import { i as localFileError, n as EXIT, r as asCliError, t as CliError } from "./errors-R4S2SAEM.js";
4
+ import { m as namedByThem, t as CONTACT_KEY } from "./apiKit-C-_PWZvy.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-MFtCmJwK.js";
6
+ import { n as waitNotice, r as waitsFor } from "./waitNotice-Ck3el3_Z.js";
7
+ 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-DtrL5lE5.js";
8
+ import { spawn } from "node:child_process";
7
9
  import { accessSync, closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
10
  import { dirname, resolve } from "node:path";
9
- import { spawn } from "node:child_process";
10
11
  import { connect } from "node:net";
11
12
  import { createInterface } from "node:readline";
12
13
  import { format } from "node:util";
13
14
  var package_default = {
14
15
  name: "@ghostlytools/cli",
15
- version: "1.7.3",
16
+ version: "1.8.0",
16
17
  type: "module",
17
18
  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
19
  license: "MIT",
@@ -117,8 +118,10 @@ var GLOBAL_OPTIONS = {
117
118
  * that starts with `-`, is longer than two characters and is no option of the command is the value (`--` starts one
118
119
  * id in 4096; `-x` stays an option). Any other positional that starts with `-` is refused instead of sent: a
119
120
  * mistyped flag must not reach a contact as text. Put `--` before a message that starts with a dash.
121
+ *
122
+ * An unknown option names the command `parsing` gives, the nearest of its options and its help.
120
123
  */
121
- function parseArgs(argv, spec, idSlot = () => false) {
124
+ function parseArgs(argv, spec, idSlot = () => false, parsing) {
122
125
  const all = {
123
126
  ...GLOBAL_OPTIONS,
124
127
  ...spec
@@ -153,7 +156,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
153
156
  inline = eq === -1 ? void 0 : arg.slice(eq + 1);
154
157
  } else {
155
158
  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)`);
159
+ if (!long) throw unknownOption(arg, all, parsing);
157
160
  name = long;
158
161
  }
159
162
  if (name.startsWith("no-") && all[name.slice(3)]?.type === "boolean" && inline === void 0) {
@@ -161,7 +164,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
161
164
  continue;
162
165
  }
163
166
  const option = all[name];
164
- if (!option) throw new CliError("usage", `Unknown option --${name}`);
167
+ if (!option) throw unknownOption(`--${name}`, all, parsing);
165
168
  if (option.type === "boolean") {
166
169
  if (inline !== void 0 && !["true", "false"].includes(inline)) throw new CliError("usage", `--${name} takes no value`);
167
170
  setBoolean(name, inline === void 0 || inline === "true");
@@ -187,7 +190,7 @@ function parseArgs(argv, spec, idSlot = () => false) {
187
190
  }
188
191
  continue;
189
192
  }
190
- if (arg.startsWith("-") && arg !== "-") throw new CliError("usage", `Unknown option ${arg} (put -- before text that starts with a dash)`);
193
+ if (arg.startsWith("-") && arg !== "-") throw unknownOption(arg, all, parsing);
191
194
  positionals.push(arg);
192
195
  }
193
196
  return {
@@ -195,6 +198,48 @@ function parseArgs(argv, spec, idSlot = () => false) {
195
198
  options
196
199
  };
197
200
  }
201
+ /**
202
+ * `Unknown option --wiat for ghostly send (did you mean --wait? ghostly help send)`. The `--` hint only where text comes
203
+ * and for a word with one dash, which may be text (`-1`, `-x`): `version -x` has no text to put after `--`.
204
+ */
205
+ function unknownOption(arg, all, parsing) {
206
+ const names = Object.entries(all).flatMap(([name, o]) => o.type === "boolean" ? [name, `no-${name}`] : [name]);
207
+ const near = nearest(arg.replace(/^--?/, ""), names);
208
+ const hints = [
209
+ ...near ? [`did you mean --${near}?`] : [],
210
+ ...parsing?.text && /^-[^-]/.test(arg) ? ["put -- before text that starts with a dash;"] : [],
211
+ ...parsing ? [`ghostly help ${parsing.command}`] : []
212
+ ];
213
+ return new CliError("usage", `Unknown option ${arg}${parsing ? ` for ghostly ${parsing.command}` : ""}${hints.length ? ` (${hints.join(" ")})` : ""}`);
214
+ }
215
+ /**
216
+ * The word of `words` a typo most likely meant: the nearest by Damerau-Levenshtein distance (a letter added, dropped,
217
+ * changed or two swapped), at most 2 and at most a third of the word's length (`wiat` one: `nope` is not `home`; `-x`
218
+ * none), else undefined.
219
+ */
220
+ function nearest(typed, words) {
221
+ const most = Math.min(2, Math.floor(typed.length / 3));
222
+ let best, bestDistance = most + 1;
223
+ for (const word of words) {
224
+ if (Math.abs(typed.length - word.length) >= bestDistance) continue;
225
+ const d = distance(typed, word);
226
+ if (d < bestDistance) {
227
+ best = word;
228
+ bestDistance = d;
229
+ }
230
+ }
231
+ return best;
232
+ }
233
+ /** The optimal string alignment distance: the edits that turn `a` into `b`, a swap of two neighbours one of them. */
234
+ function distance(a, b) {
235
+ const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
236
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
237
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
238
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
239
+ 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);
240
+ }
241
+ return d[a.length][b.length];
242
+ }
198
243
  /** Words as a sentence lists them: "a", "a or b", "a, b or c". */
199
244
  var listed$1 = (words) => words.length > 1 ? `${words.slice(0, -1).join(", ")} or ${words.at(-1)}` : words[0];
200
245
  /** The global option a word names (`--profile`, `--profile=bot`, `-p`), else undefined. */
@@ -875,12 +920,21 @@ function quota(card, usage) {
875
920
  if (card.left === void 0 && !used) throw new CliError("usage", `--left is needed (or --used with --limit): ghostly ${usage}`);
876
921
  return card;
877
922
  }
878
- /** A time a command names: milliseconds, or a date the JavaScript Date reads (`2026-09-30T01:00:00Z`). */
923
+ /** How the time flags say the dates they take (`--next`, `--resets`, `--also`'s `@`). */
924
+ 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";
925
+ /** An ISO date with no time, which `Date.parse` alone reads as UTC midnight: `2026-09-30`, `2026-09`. */
926
+ var ISO_DAY = /^(?:[+-]\d{6}|\d{4})-\d{2}(-\d{2})?$/;
927
+ /**
928
+ * A time a command names: milliseconds, or a date the JavaScript Date reads (`2026-09-30T01:00:00Z`). A date with no
929
+ * 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
930
+ * alone as UTC midnight (21:00 the day before in UTC-03, agents#2355), so that one is read as `2026-09-30T00:00`.
931
+ */
879
932
  function cardTime(value, flag) {
880
933
  if (value === void 0) return void 0;
881
934
  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)}`);
935
+ const day = ISO_DAY.exec(text);
936
+ const ms = /^\d+$/.test(text) ? milliseconds(text, flag) : Date.parse(day ? `${text}${day[1] ? "" : "-01"}T00:00` : text);
937
+ 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
938
  return ms;
885
939
  }
886
940
  /** `--run ok`, `--run failed:"CI flaked"`: a run of a routine, recorded as its last. */
@@ -938,7 +992,7 @@ var routineOptions = {
938
992
  },
939
993
  next: {
940
994
  type: "string",
941
- description: "Its next run: milliseconds or a date like 2026-09-30T01:00:00Z"
995
+ description: `Its next run: milliseconds or a date: ${CARD_TIME_FORMS}`
942
996
  },
943
997
  run: {
944
998
  type: "string",
@@ -1083,11 +1137,11 @@ var usageOptions = {
1083
1137
  },
1084
1138
  resets: {
1085
1139
  type: "string",
1086
- description: "When the window starts again: milliseconds or a date like 2026-10-07T18:00:00Z"
1140
+ description: `When the window starts again: milliseconds or a date: ${CARD_TIME_FORMS}`
1087
1141
  },
1088
1142
  also: {
1089
1143
  type: "list",
1090
- description: "Another window, window=percent[@time], like week=80@2026-10-10T00:00:00Z (up to 3; shown in the details)"
1144
+ 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
1145
  },
1092
1146
  id: {
1093
1147
  type: "string",
@@ -1157,7 +1211,7 @@ var commands$8 = {
1157
1211
  description: "Replace the three files when they are there"
1158
1212
  }
1159
1213
  },
1160
- run: async ({ options }, a) => (await import("./apps-BfoDISRg.js")).initApp(a.dir, {
1214
+ run: async ({ options }, a) => (await import("./apps-DbEfL_3b.js")).initApp(a.dir, {
1161
1215
  name: options.name,
1162
1216
  title: options.title,
1163
1217
  force: options.force === true
@@ -1197,7 +1251,7 @@ var commands$8 = {
1197
1251
  description: "This version's sequence, higher than the bundle at --out's (default: one more than it)"
1198
1252
  }
1199
1253
  },
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)
1254
+ run: async ({ options }, a) => (await import("./apps-DbEfL_3b.js")).publishApp(a.dir, keyFile(options.key, "app publish <dir> --key <file> [--out <file>] [--sequence n]"), here(options.out), options.sequence)
1201
1255
  },
1202
1256
  "app revoke": {
1203
1257
  method: "app.revoke",
@@ -1230,7 +1284,7 @@ var commands$8 = {
1230
1284
  description: "Allow --up-to past the bundle's own sequence (versions published from elsewhere)"
1231
1285
  }
1232
1286
  },
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]"), {
1287
+ run: async ({ options }, a) => (await import("./apps-DbEfL_3b.js")).revokeApp(a.dir, keyFile(options.key, "app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]"), {
1234
1288
  digests: options.digest,
1235
1289
  upTo: options["up-to"],
1236
1290
  reason: options.reason,
@@ -1291,7 +1345,7 @@ var commands$8 = {
1291
1345
  usage: "app verify <bundle|url>",
1292
1346
  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
1347
  args: ["bundle"],
1294
- run: async (_, a) => (await import("./apps-BfoDISRg.js")).verifyApp(a.bundle)
1348
+ run: async (_, a) => (await import("./apps-DbEfL_3b.js")).verifyApp(a.bundle)
1295
1349
  },
1296
1350
  "store sign": {
1297
1351
  method: "store.sign",
@@ -1308,7 +1362,7 @@ var commands$8 = {
1308
1362
  description: "The folder to write ghostly-store.json and ghostly-store.sig in (default: the index's)"
1309
1363
  }
1310
1364
  },
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))
1365
+ run: async ({ options }, a) => (await import("./apps-DbEfL_3b.js")).signStore(a.index, keyFile(options.key, "store sign <index> --key <file> [--out <dir>]"), here(options.out))
1312
1366
  }
1313
1367
  };
1314
1368
  //#endregion
@@ -3224,6 +3278,11 @@ function idSlot(command) {
3224
3278
  };
3225
3279
  return (index) => at(index) && (shift === 0 || index + shift >= names.length || at(index + shift));
3226
3280
  }
3281
+ /** Whether a command's last positional takes the rest of the line as words, not ids: a text, a name, a path, emoji. */
3282
+ function takesText(command) {
3283
+ const last = command.args?.at(-1)?.replace(/\?$/, "");
3284
+ return !!last?.endsWith("...") && !ID_ARGS.has(last.slice(0, -3));
3285
+ }
3227
3286
  /**
3228
3287
  * The placeholders a usage line shows for its positionals, in order: `chat pay <chat> <sats> [--memo t]` →
3229
3288
  * ["chat", "sats"]. One that is not a plain `<x>` (`[text... | --text <text>]`) is undefined; the flags end them.
@@ -3428,6 +3487,12 @@ function checkWebhook(url) {
3428
3487
  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
3488
  return parsed;
3430
3489
  }
3490
+ /**
3491
+ * The event number a cursor file holds, or undefined when there is no file (a first start: live events). A file that is
3492
+ * there and holds no whole number (empty, half-written, edited by hand) is refused, naming the file and what it holds:
3493
+ * taken as no cursor, the listener started at the journal's end and skipped every event since the last one handled,
3494
+ * without a word, and its next write replaced the file.
3495
+ */
3431
3496
  function readCursor(path) {
3432
3497
  if (!path || !existsSync(path)) return void 0;
3433
3498
  let text;
@@ -3436,8 +3501,11 @@ function readCursor(path) {
3436
3501
  } catch (error) {
3437
3502
  throw localFileError(error, path) ?? error;
3438
3503
  }
3439
- const value = Number(text.trim());
3440
- return Number.isInteger(value) && value >= 0 ? value : void 0;
3504
+ const trimmed = text.trim();
3505
+ const value = trimmed === "" ? NaN : Number(trimmed);
3506
+ if (Number.isSafeInteger(value) && value >= 0 && /^\d+$/.test(trimmed)) return value;
3507
+ const shown = trimmed === "" ? "nothing" : JSON.stringify(trimmed.length > 32 ? `${trimmed.slice(0, 32)}…` : trimmed);
3508
+ throw new CliError("bad_request", `${path} holds no event number (${shown}): fix or remove it, or give --since`);
3441
3509
  }
3442
3510
  /**
3443
3511
  * Whether a cursor can be kept at `path`, asked before anything starts: its folder is there and takes a file. Before, a
@@ -3717,7 +3785,7 @@ var Feed = class {
3717
3785
  pause;
3718
3786
  resume;
3719
3787
  held = false;
3720
- /** `since`: the last event taken, where a new subscription starts. */
3788
+ /** `since`: the last event taken (or, before one, the daemon's last seq when it subscribed), where a new subscription starts. */
3721
3789
  constructor(handle, since, pause, resume) {
3722
3790
  this.handle = handle;
3723
3791
  this.since = since;
@@ -3801,6 +3869,9 @@ function followDaemon(address, client, handle, since, holdMs = PAUSE_HOLD_MS, pr
3801
3869
  if (current !== c) return;
3802
3870
  current = null;
3803
3871
  reconnect(1e3);
3872
+ }).then((answer) => {
3873
+ if (feed.since === void 0 && typeof answer?.lastSeq === "number") feed.since = answer.lastSeq;
3874
+ return answer;
3804
3875
  });
3805
3876
  return {
3806
3877
  subscribed: follow(client),
@@ -3922,6 +3993,37 @@ async function completeWithPipedEvidence(call, params, read, note) {
3922
3993
  evidence
3923
3994
  });
3924
3995
  }
3996
+ /**
3997
+ * `settings set <key> <json-value>`'s value: from stdin when it is `-`, or when none is given and stdin is not a
3998
+ * terminal (a pipe nobody writes: the note, then the usage error, as for a join). A TURN password (`iceServers` with a
3999
+ * `credential`) given on the command line still goes, with the ps/history warning: `settings get` hides it as a secret.
4000
+ */
4001
+ async function settingValue(key, value, read, tty = false, note = () => {}) {
4002
+ const usage = "Missing <json-value>: ghostly settings set <key> <json-value>";
4003
+ if (value !== void 0 && value !== "-") return {
4004
+ value,
4005
+ ...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} -)` }
4006
+ };
4007
+ if (value === void 0 && tty) throw new CliError("usage", usage);
4008
+ const text = (value === "-" ? await read() : await readUnasked(read, note, {
4009
+ what: "the value",
4010
+ missing: "Missing <json-value>",
4011
+ command: `settings set ${key}`,
4012
+ as: "an argument"
4013
+ })).replace(/\r?\n$/, "");
4014
+ if (!text.trim()) throw new CliError("usage", value === "-" ? `Missing <json-value> on stdin: … | ghostly settings set ${key} -` : usage);
4015
+ return { value: text };
4016
+ }
4017
+ /** Whether an `iceServers` value as typed holds a TURN password: an entry with a `credential` that is not empty. */
4018
+ function hasCredential(value) {
4019
+ let servers;
4020
+ try {
4021
+ servers = JSON.parse(value);
4022
+ } catch {
4023
+ return false;
4024
+ }
4025
+ return Array.isArray(servers) && servers.some((server) => !!server && typeof server === "object" && typeof server.credential === "string" && server.credential !== "");
4026
+ }
3925
4027
  async function readUnasked(read, note, ask) {
3926
4028
  let noteTimer, giveUpTimer;
3927
4029
  const stop = () => {
@@ -3991,15 +4093,15 @@ var VERSION = package_default.version;
3991
4093
  * command a running daemon answers loads none of them, and starts about as fast as Node does. Statically imported, they
3992
4094
  * cost every command ~100 ms before its socket was opened.
3993
4095
  */
3994
- var engineApi = () => import("./api-B42F9ytB.js");
3995
- var engineHost = () => import("./host-BX0DmKW6.js");
4096
+ var engineApi = () => import("./api-Dj1yn0px.js");
4097
+ var engineHost = () => import("./host-CNWGB3-j.js");
3996
4098
  /**
3997
4099
  * `--translate <lang>`'s translator, or null (not asked; or the runtime is not there, said on stderr). Loaded only when
3998
4100
  * asked: the app's message parser it reads costs every other command nothing.
3999
4101
  */
4000
4102
  async function translatorFor(value, home) {
4001
4103
  if (value === void 0) return null;
4002
- const { loadDetector, openTranslator, translateTarget } = await import("./translate-DObb-1tq.js");
4104
+ const { loadDetector, openTranslator, translateTarget } = await import("./translate-od5GbpvR.js");
4003
4105
  return openTranslator({
4004
4106
  home,
4005
4107
  to: translateTarget(value),
@@ -4203,62 +4305,68 @@ function answerWithin(method, params) {
4203
4305
  if (waits !== void 0) return (waits + 10) * 1e3;
4204
4306
  if (readOnly(method, params)) return ANSWER_MS;
4205
4307
  }
4206
- /**
4207
- * The seconds a call without `--timeout` waits for the contact: the daemon's defaults (`num(params, "timeout", …)` in
4208
- * api.ts, files.ts, buttons.ts and statusCards.ts), so that a bot's `chat wait` or `send --wait sent` on a daemon that
4209
- * stopped answering ends when the wait would have. A call that does not wait is none.
4210
- */
4211
- function waitsFor(method, params) {
4212
- if (method === "chat.wait") return 60;
4213
- if (method === "file.wait" || method === "file.save" && params.wait === true) return 300;
4214
- if (typeof params.wait === "string" && params.wait !== "none") return 30;
4215
- }
4216
4308
  async function session(g, options) {
4217
4309
  requireProfile(g);
4218
4310
  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
- }
4311
+ if (client) return throughDaemon(client);
4238
4312
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
4239
4313
  const host = await openOneShot(g, options);
4314
+ if (host instanceof DaemonClient) return throughDaemon(host);
4240
4315
  return {
4241
4316
  mode: "one-shot",
4242
4317
  call: (m, p) => callApi(host.ctx, m, p ?? {}),
4243
- close: () => host.close()
4318
+ close: () => host.close(),
4319
+ abort: () => host.close()
4320
+ };
4321
+ }
4322
+ function throughDaemon(client) {
4323
+ const warned = warnVersion(client);
4324
+ const call = async (m, p) => {
4325
+ const timeoutMs = answerWithin(m, p ?? {});
4326
+ if (timeoutMs === void 0 && !await settlesWithin(warned, ANSWER_MS)) {
4327
+ client.destroy();
4328
+ 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 });
4329
+ }
4330
+ return client.call(m, p, { timeoutMs });
4331
+ };
4332
+ return {
4333
+ mode: "daemon",
4334
+ call,
4335
+ close: async () => {
4336
+ await warned;
4337
+ client.close();
4338
+ },
4339
+ abort: async () => {
4340
+ client.destroy();
4341
+ }
4244
4342
  };
4245
4343
  }
4246
4344
  /** 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
4345
  var HOLDER_WAIT_MS = 5e3;
4346
+ /** How long it waits for the profile's daemon that is starting (`startingDaemon`): its engine takes seconds on a large profile. */
4347
+ var STARTING_WAIT_MS = 3e4;
4248
4348
  /**
4249
4349
  * Opens the profile in this process for a one-shot command. Another one that holds it (a script's `&`, a second
4250
4350
  * 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.
4351
+ * exit code. One still holding it after HOLDER_WAIT_MS is answered with the next step. A daemon takes the profile before
4352
+ * its socket listens (its engine starts in between, seconds on a large profile): once one answers there, the command
4353
+ * goes through it, its client the answer. Only the lock was looked at again, and a command run while the daemon started
4354
+ * failed busy, told to start the daemon that was running. A daemon that marked its start is waited for up to
4355
+ * STARTING_WAIT_MS, and named as the holder. A `listen` with no daemon opens it the same way, as the daemon (`mode`).
4252
4356
  */
4253
- async function openOneShot(g, options = {}) {
4357
+ async function openOneShot(g, options = {}, mode = "one-shot") {
4254
4358
  const { openHost } = await engineHost();
4255
- const until = Date.now() + HOLDER_WAIT_MS;
4359
+ const from = Date.now();
4256
4360
  for (;;) try {
4257
- return await openHost(g.paths, "one-shot", VERSION, options);
4361
+ return await openHost(g.paths, mode, VERSION, options);
4258
4362
  } catch (error) {
4259
4363
  if (!(error instanceof CliError) || error.code !== "busy") throw error;
4260
- const left = until - Date.now();
4364
+ const starting = startingDaemon(g.paths);
4365
+ const client = await connectDaemon(g.paths);
4366
+ if (client) return client;
4367
+ const left = from + (starting === null ? HOLDER_WAIT_MS : STARTING_WAIT_MS) - Date.now();
4261
4368
  if (left <= 0) {
4369
+ 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
4370
  const pid = error.details?.pid;
4263
4371
  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
4372
  }
@@ -4272,12 +4380,78 @@ async function openOneShot(g, options = {}) {
4272
4380
  */
4273
4381
  async function withSession(g, work, options = {}) {
4274
4382
  const s = await session(g, options);
4383
+ const stops = interruptible(s);
4275
4384
  try {
4276
- return await work(s);
4385
+ return await stops.run(work);
4277
4386
  } finally {
4278
4387
  await s.close();
4388
+ stops.off();
4279
4389
  }
4280
4390
  }
4391
+ /** How long a wait goes on before a terminal is told what it waits for: a command done by then says nothing. */
4392
+ var WAIT_NOTICE_MS = 1e3;
4393
+ /** How long Ctrl-C gives the profile to close before the command leaves anyway (a second Ctrl-C leaves at once). */
4394
+ var INTERRUPT_CLOSE_MS = 1e4;
4395
+ /**
4396
+ * Ctrl-C while a session's command runs (agents#2354): the command stops where it is, a one-shot's profile closes (its
4397
+ * lock released, as `daemon` does in `stopper`), one line on stderr says what became of what it waited on, stdout has
4398
+ * the `interrupted` error, and the exit is 130. Killed by SIGINT, it said nothing, left `daemon.lock` behind, and the
4399
+ * person did not learn that the message still goes (and sent it again). Ctrl-C once the work is done (the profile
4400
+ * closing) only lets the answer out. A wait that goes on past WAIT_NOTICE_MS says what it waits for, on a terminal only:
4401
+ * stderr of a bot's pipe stays clean.
4402
+ */
4403
+ function interruptible(s) {
4404
+ let interrupted = false, done = false, left = false;
4405
+ const pending = /* @__PURE__ */ new Set();
4406
+ const onSignal = () => {
4407
+ if (interrupted) process.exit(EXIT.interrupted);
4408
+ interrupted = true;
4409
+ if (done) return;
4410
+ const [first] = pending, waiting = [...pending].find((call) => call.notice)?.notice;
4411
+ const words = waiting ? `stopped waiting (Ctrl-C): ${waiting.stopped}` : "stopped (Ctrl-C) before the command answered";
4412
+ const leave = () => {
4413
+ if (left) return;
4414
+ left = true;
4415
+ process.stderr.write(`ghostly: ${words}\n`);
4416
+ print({ error: new CliError("interrupted", words[0].toUpperCase() + words.slice(1), first ? { method: first.method } : void 0).toJSON() });
4417
+ exit(EXIT.interrupted);
4418
+ };
4419
+ setTimeout(leave, INTERRUPT_CLOSE_MS).unref();
4420
+ s.abort().catch(() => {}).then(leave);
4421
+ };
4422
+ process.on("SIGINT", onSignal);
4423
+ const held = (promise) => new Promise((resolve, reject) => {
4424
+ promise.then((value) => {
4425
+ if (!interrupted || done) resolve(value);
4426
+ }, (error) => {
4427
+ if (!interrupted || done) reject(error);
4428
+ });
4429
+ });
4430
+ const call = (method, params) => {
4431
+ const entry = {
4432
+ method,
4433
+ notice: waitNotice(method, params ?? {}, s.mode)
4434
+ };
4435
+ pending.add(entry);
4436
+ const notice = entry.notice;
4437
+ const timer = notice && process.stderr.isTTY ? setTimeout(() => process.stderr.write(`ghostly: ${notice.waiting}\n`), WAIT_NOTICE_MS) : void 0;
4438
+ return held(s.call(method, params).finally(() => {
4439
+ clearTimeout(timer);
4440
+ pending.delete(entry);
4441
+ }));
4442
+ };
4443
+ return {
4444
+ run: (work) => held(work({
4445
+ ...s,
4446
+ call
4447
+ }).finally(() => {
4448
+ if (!interrupted) done = true;
4449
+ })),
4450
+ off: () => {
4451
+ process.off("SIGINT", onSignal);
4452
+ }
4453
+ };
4454
+ }
4281
4455
  /**
4282
4456
  * A one-shot join waits up to 60 s for the inviter. Its answer says whether the chat paired and at what stage it is; one
4283
4457
  * not paired yet comes with the next step, since nothing pairs once the command has left.
@@ -4394,7 +4568,7 @@ var SPECIAL = [
4394
4568
  cursor: o("string", "A file that keeps the last seq handled (read at start, written after each event)"),
4395
4569
  type: o("list", "Only events of this type (message.received) or family (message, or group.typing.); repeat for more"),
4396
4570
  turns: o("boolean", "Only agent turns: each message received, and each group message that mentions you, as one agent.turn event"),
4397
- from: o("list", "Only this chat's events (id, prefix, name or the contact's key; again for more)"),
4571
+ from: o("list", "Only this chat's events (id, a label given here or the contact's key; again for more)"),
4398
4572
  group: o("list", "Only this group's events (again for more); with --from or --group, nobody else's event gets through"),
4399
4573
  exec: o("string", "Run this command per event, the event as JSON on stdin"),
4400
4574
  webhook: o("string", "POST each event to this URL"),
@@ -4407,7 +4581,7 @@ var SPECIAL = [
4407
4581
  "The profile's settings",
4408
4582
  { "show-secret": o("boolean", "Show credentials too") }
4409
4583
  ],
4410
- ["settings set <key> <json-value>", "Change one: relays, irohRelays, hyperdhtRelay, iceServers, publicProfiles, online, shareProfile, sendTyping, autoDownloads, serveFiles, nick"],
4584
+ ["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
4585
  [
4412
4586
  "engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]",
4413
4587
  "Any call of the app's engine, with its own parameters (engine --list --verbose names them)",
@@ -4459,31 +4633,87 @@ function beside(rows, more) {
4459
4633
  }
4460
4634
  return out;
4461
4635
  }
4462
- function help() {
4636
+ /**
4637
+ * The width the help is laid out to: $COLUMNS, else the terminal's when stdout is one (80 when it says nothing), else
4638
+ * none: piped, each row stays one line for grep. At a fixed 58-column usage, 170 of the 195 lines of `ghostly help` passed
4639
+ * 80 columns, and an 80-column terminal broke every summary mid-word into column 0.
4640
+ */
4641
+ function helpColumns() {
4642
+ const given = Number(process.env.COLUMNS);
4643
+ if (Number.isInteger(given) && given > 0) return given;
4644
+ return process.stdout.isTTY ? process.stdout.columns || 80 : void 0;
4645
+ }
4646
+ /** `prefix`, then `text`'s words in lines of at most `columns` (a longer word alone), each after the first `indent` in. */
4647
+ function wrap(prefix, text, columns, indent) {
4648
+ const lines = [];
4649
+ let line = prefix, started = false;
4650
+ for (const word of text.trim().match(/\S+ */g) ?? []) {
4651
+ if (started && (line + word.trimEnd()).length > columns) {
4652
+ lines.push(line.trimEnd());
4653
+ line = " ".repeat(indent);
4654
+ }
4655
+ line += word;
4656
+ started = true;
4657
+ }
4658
+ return [...lines, line.trimEnd()];
4659
+ }
4660
+ /** Lines of text as written, or, laid out to `columns` and one of them wider, as one paragraph wrapped at their indent. */
4661
+ function paragraph(lines, columns) {
4662
+ if (columns === void 0 || lines.every((line) => line.length <= columns)) return lines;
4663
+ const indent = lines[0].length - lines[0].trimStart().length;
4664
+ return wrap(" ".repeat(indent), lines.join(" "), columns, indent);
4665
+ }
4666
+ /**
4667
+ * A help row: `label` (a usage or an option, with its indent), its `text` from column `at`, or under the label when the
4668
+ * label takes that room. Laid out to `columns`, the text wraps at its column; with under 40 columns left for it (an
4669
+ * 80-column terminal beside the 58 of a usage), it goes under its label, 2 further in.
4670
+ */
4671
+ function helpRow(label, text, at, columns) {
4672
+ const long = label.length > at - 2;
4673
+ if (columns === void 0) return [long ? `${label}\n${" ".repeat(at)}${text}` : label.padEnd(at) + text];
4674
+ const indent = label.length - label.trimStart().length;
4675
+ const labelLines = wrap(" ".repeat(indent), label, columns, indent + 4);
4676
+ if (columns - at < 40) return [...labelLines, ...wrap(" ".repeat(indent + 2), text, columns, indent + 2)];
4677
+ if (long) return [...labelLines, ...wrap(" ".repeat(at), text, columns, at)];
4678
+ return wrap(label.padEnd(at), text, columns, at);
4679
+ }
4680
+ /**
4681
+ * What `ghostly` says first in a Ghostly folder with no profile yet: where to start, as the README's "Five minutes"
4682
+ * does, before the whole list. `$ ` keeps the lines apart from the list's commands.
4683
+ */
4684
+ var FIRST_STEPS = [
4685
+ "First steps:",
4686
+ " $ ghostly invite create --label alice make an invite for a contact",
4687
+ " $ ghostly invite join - join one (pasted on stdin)",
4688
+ " $ ghostly daemon --detach keep the profile online",
4689
+ " $ ghostly help <command> one command and its options"
4690
+ ];
4691
+ function help(firstSteps = false) {
4692
+ const columns = helpColumns();
4463
4693
  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
4694
  return [
4466
- `ghostly ${VERSION}: Ghostly for bots and terminals, the app's own engine without a screen.`,
4695
+ ...paragraph([`ghostly ${VERSION}: Ghostly for bots and terminals, the app's own engine without a screen.`], columns),
4467
4696
  "",
4468
- "Usage: ghostly <command> [options] (JSON on stdout; errors as {\"error\":{code,message}} with an exit code)",
4697
+ ...firstSteps ? [...FIRST_STEPS, ""] : [],
4698
+ ...paragraph(["Usage: ghostly <command> [options] (JSON on stdout; errors as {\"error\":{code,message}} with an exit code)"], columns),
4469
4699
  "",
4470
- ...rows.map(([usage, summary]) => ` ${usage.length > width ? usage + "\n " + " ".repeat(width) : usage.padEnd(width)} ${summary}`),
4700
+ ...rows.flatMap(([usage, summary]) => helpRow(` ${usage}`, summary, 62, columns)),
4471
4701
  "",
4472
4702
  "Options for every command:",
4473
- ...Object.entries(GLOBAL_OPTIONS).map(([name, o]) => ` --${name}${o.short ? `, -${o.short}` : ""}`.padEnd(24) + o.description),
4703
+ ...Object.entries(GLOBAL_OPTIONS).flatMap(([name, o]) => helpRow(` --${name}${o.short ? `, -${o.short}` : ""}`, o.description, 24, columns)),
4474
4704
  "",
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."
4705
+ ...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, 130 stopped with Ctrl-C."], columns),
4706
+ ...paragraph(["More: https://ghostly.tools/cli, or the README.md beside this CLI."], columns)
4478
4707
  ].join("\n");
4479
4708
  }
4709
+ var EVERY_COMMAND = "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h";
4480
4710
  /** What `ghostly help help` answers. */
4481
- var HELP_USAGE = [
4711
+ var helpUsage = (columns) => [
4482
4712
  "Usage: ghostly help [<command>...]",
4483
4713
  "",
4484
- " Help for every command, or for one command or a group of them (also ghostly <command> --help)",
4714
+ ...paragraph([" Help for every command, or for one command or a group of them (also ghostly <command> --help)"], columns),
4485
4715
  "",
4486
- "Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h"
4716
+ ...paragraph([EVERY_COMMAND], columns)
4487
4717
  ].join("\n");
4488
4718
  /** Every command's help row: usage, summary and, for the table and text commands, their options. */
4489
4719
  function helpRows() {
@@ -4511,7 +4741,8 @@ function commandWords(usage) {
4511
4741
  * options; for a group (`ghostly help file`), the group's commands.
4512
4742
  */
4513
4743
  function commandHelp(words) {
4514
- if (words[0] === "help") return HELP_USAGE;
4744
+ const columns = helpColumns();
4745
+ if (words[0] === "help") return helpUsage(columns);
4515
4746
  const named = (list) => helpRows().filter((row) => {
4516
4747
  const own = commandWords(row.usage);
4517
4748
  return list.every((word, i) => own[i] === word);
@@ -4520,31 +4751,31 @@ function commandHelp(words) {
4520
4751
  let rows = named(words);
4521
4752
  while (!rows.length && words.length > 1) rows = named(words = words.slice(0, -1));
4522
4753
  const asked = words.join(" ");
4523
- if (!rows.length) throw new CliError("usage", `Unknown command: ${asked || "\"\""} (ghostly help)`);
4754
+ if (!rows.length) throw unknownCommand(given[0], given[1], given[2]);
4524
4755
  const exact = rows.filter((row) => commandWords(row.usage).join(" ") === asked);
4525
4756
  if (!exact.length && words.length < given.length) throw unknownCommand(given[0], given[1], given[2]);
4526
4757
  const lines = [];
4527
4758
  for (const row of exact) {
4528
- lines.push(`Usage: ghostly ${row.usage}`, "", ` ${row.summary}`);
4759
+ lines.push(...columns === void 0 ? [`Usage: ghostly ${row.usage}`] : wrap("Usage: ghostly ", row.usage, columns, 4), "", ...paragraph([` ${row.summary}`], columns));
4529
4760
  const options = Object.entries(row.options ?? {}).filter(([, o]) => o.description);
4530
4761
  if (options.length) {
4531
4762
  lines.push("", "Options:");
4532
4763
  const labels = options.map(([name, o]) => ` --${o.negatedOnly ? "no-" : ""}${name}${o.type === "boolean" ? "" : ` <${o.type === "number" ? "n" : "value"}>`}`);
4533
4764
  const width = Math.max(26, ...labels.map((label) => label.length + 2));
4534
- options.forEach(([, o], i) => lines.push(labels[i].padEnd(width) + o.description));
4765
+ options.forEach(([, o], i) => lines.push(...helpRow(labels[i], o.description, width, columns)));
4535
4766
  }
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 --.");
4767
+ 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
4768
  lines.push("");
4538
4769
  }
4539
4770
  const rest = rows.filter((row) => !exact.includes(row));
4540
4771
  if (rest.length) {
4541
4772
  const width = Math.min(58, Math.max(...rest.map((row) => row.usage.length)));
4542
4773
  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}`);
4774
+ lines.push(...paragraph([`ghostly ${asked}: ${count} (ghostly help ${asked} <command> for one)`], columns), "");
4775
+ for (const row of rest) lines.push(...helpRow(` ${row.usage}`, row.summary, width + 4, columns));
4545
4776
  lines.push("");
4546
4777
  }
4547
- lines.push("Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h");
4778
+ lines.push(...paragraph([EVERY_COMMAND], columns));
4548
4779
  return lines.join("\n");
4549
4780
  }
4550
4781
  async function profileCommand(sub, argv) {
@@ -4598,7 +4829,7 @@ async function profileCommand(sub, argv) {
4598
4829
  eitherWay: true
4599
4830
  }
4600
4831
  }
4601
- }[sub ?? ""] ?? {});
4832
+ }[sub ?? ""] ?? {}, void 0, { command: commandOf("profile", sub) });
4602
4833
  const g = globals(parsed);
4603
4834
  pretty = g.pretty;
4604
4835
  switch (sub) {
@@ -4693,7 +4924,7 @@ async function profileCommand(sub, argv) {
4693
4924
  if (!given || !name) throw new CliError("usage", `Missing <${given ? "new profile" : "file"}>: ghostly profile restore <file> <new profile> [--passphrase-file f] [--use]`);
4694
4925
  noMoreThan(2, parsed.positionals, "profile restore <file> <new profile> [--passphrase-file f] [--use]");
4695
4926
  const file = here(given);
4696
- const { backupFileProtection, restoreProfile } = await import("./backup-BkUeeduy.js");
4927
+ const { backupFileProtection, restoreProfile } = await import("./backup-Cdd6-HNu.js");
4697
4928
  const protection = await backupFileProtection(file);
4698
4929
  const paths = await restoreProfile(g.home, checkProfileName(name), file, protection === "none" ? void 0 : backupPassphrase(parsed.options["passphrase-file"], RESTORE_PASSPHRASE));
4699
4930
  if (parsed.options.use) selectProfile(g.home, name);
@@ -4815,7 +5046,7 @@ async function daemonCommand(argv) {
4815
5046
  type: "number",
4816
5047
  description: ""
4817
5048
  }
4818
- });
5049
+ }, void 0, { command: commandOf("daemon", sub) });
4819
5050
  const g = globals(parsed);
4820
5051
  pretty = g.pretty;
4821
5052
  if (!sub || [
@@ -4827,8 +5058,13 @@ async function daemonCommand(argv) {
4827
5058
  knownProfile(g);
4828
5059
  const client = await connectDaemon(g.paths);
4829
5060
  if (!client) {
5061
+ const starting = startingDaemon(g.paths);
4830
5062
  print({
4831
5063
  running: false,
5064
+ ...starting === null ? {} : {
5065
+ starting: true,
5066
+ pid: starting
5067
+ },
4832
5068
  profile: g.profile,
4833
5069
  socket: g.paths.socket
4834
5070
  });
@@ -4848,19 +5084,24 @@ async function daemonCommand(argv) {
4848
5084
  if (sub === "stop") {
4849
5085
  knownProfile(g);
4850
5086
  const stopFor = seconds(parsed, 20);
4851
- const client = await connectDaemon(g.paths);
5087
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4852
5088
  if (!client) throw new CliError("not_found", `No daemon runs profile ${g.profile}`);
5089
+ const { pid, listen } = await stopDaemon(g, client, stopFor);
5090
+ if (listen) process.stderr.write(listenEnded(pid));
4853
5091
  print({
4854
5092
  stopped: true,
4855
- pid: await stopDaemon(g, client, stopFor)
5093
+ pid,
5094
+ ...listen && { listen: true }
4856
5095
  });
4857
5096
  return;
4858
5097
  }
4859
5098
  if (sub === "restart") {
4860
5099
  const stopFor = seconds(parsed, 20), startFor = seconds(parsed, 60);
4861
- const client = await connectDaemon(g.paths);
5100
+ const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);
4862
5101
  const probe = client ? client.call("status").catch(() => null) : null;
4863
- const stopped = client ? await stopDaemon(g, client, stopFor) : null;
5102
+ const ended = client ? await stopDaemon(g, client, stopFor) : null;
5103
+ const stopped = ended?.pid ?? null;
5104
+ if (ended?.listen) process.stderr.write(listenEnded(ended.pid));
4864
5105
  const before = (await probe)?.version ?? null;
4865
5106
  let started;
4866
5107
  try {
@@ -4877,6 +5118,7 @@ async function daemonCommand(argv) {
4877
5118
  print({
4878
5119
  restarted: true,
4879
5120
  stopped,
5121
+ ...ended?.listen && { listen: true },
4880
5122
  before,
4881
5123
  version: VERSION,
4882
5124
  ...started
@@ -4891,6 +5133,24 @@ async function daemonCommand(argv) {
4891
5133
  }
4892
5134
  print(await startDetached(g, startFor));
4893
5135
  }
5136
+ /**
5137
+ * The profile's daemon that is starting (`startingDaemon`: it holds the profile, its socket does not listen yet), once
5138
+ * its socket answers, waited for up to `seconds`; null when none is starting. One still starting then is the answer,
5139
+ * `timeout` with its pid. `daemon stop` said no daemon ran, and the daemon came up a moment later; `daemon restart`
5140
+ * failed busy and left the old code running.
5141
+ */
5142
+ async function startedDaemon(g, seconds) {
5143
+ const until = Date.now() + seconds * 1e3;
5144
+ for (;;) {
5145
+ const pid = startingDaemon(g.paths);
5146
+ const client = await connectDaemon(g.paths);
5147
+ if (client) return client;
5148
+ if (pid === null) return null;
5149
+ const left = until - Date.now();
5150
+ 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 });
5151
+ await new Promise((resolve) => setTimeout(resolve, Math.min(100, left)));
5152
+ }
5153
+ }
4894
5154
  /** `--timeout <s>`, or `fallback` without one: seconds above 0 (0 or less would not wait at all). */
4895
5155
  function seconds(parsed, fallback) {
4896
5156
  const value = parsed.options.timeout;
@@ -4906,9 +5166,9 @@ function seconds(parsed, fallback) {
4906
5166
  * `process.kill` with either name is TerminateProcess: the first signal ends it, there is no second.
4907
5167
  */
4908
5168
  async function stopDaemon(g, client, seconds) {
4909
- let pid, answered = true;
5169
+ let pid, answered = true, listen = false;
4910
5170
  try {
4911
- ({pid} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
5171
+ ({pid, listen = false} = await client.call("daemon.stop", {}, { timeoutMs: seconds * 1e3 }));
4912
5172
  } catch (error) {
4913
5173
  const refused = isNotTheDaemon(error);
4914
5174
  if (!(error instanceof CliError && error.code === "timeout") && !refused) throw error;
@@ -4930,14 +5190,24 @@ async function stopDaemon(g, client, seconds) {
4930
5190
  }
4931
5191
  return !running();
4932
5192
  };
4933
- if (await gone()) return pid;
5193
+ if (await gone()) return {
5194
+ pid,
5195
+ listen
5196
+ };
4934
5197
  if (!answered) {
4935
5198
  process.stderr.write(`ghostly: the daemon (process ${pid}) did not stop on SIGTERM in ${seconds} s: killing it\n`);
4936
5199
  signal(pid, "SIGKILL");
4937
- if (await gone()) return pid;
5200
+ if (await gone()) return {
5201
+ pid,
5202
+ listen
5203
+ };
4938
5204
  }
4939
5205
  throw new CliError("timeout", `The daemon (process ${pid}) has not stopped yet`, { pid });
4940
5206
  }
5207
+ /** What `daemon stop` and `restart` say of a daemon that was a `listen` running the profile: that listen is over. */
5208
+ function listenEnded(pid) {
5209
+ 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`;
5210
+ }
4941
5211
  /** Throws busy, with its pid, when a process other than `except` holds the profile. */
4942
5212
  function heldBy(g, except) {
4943
5213
  const owner = lockOwner(g.paths);
@@ -5111,7 +5381,7 @@ async function listenCommand(argv) {
5111
5381
  type: "string",
5112
5382
  description: ""
5113
5383
  }
5114
- });
5384
+ }, void 0, { command: "listen" });
5115
5385
  noMoreThan(0, parsed.positionals, SPECIAL.find(([usage]) => usage.startsWith("listen "))[0]);
5116
5386
  const blank = (value) => typeof value === "string" && value.trim() === "";
5117
5387
  if (blank(parsed.options.webhook)) throw new CliError("usage", "--webhook needs a URL");
@@ -5164,9 +5434,10 @@ async function listenCommand(argv) {
5164
5434
  });
5165
5435
  };
5166
5436
  requireProfile(g);
5167
- const client = await connectDaemon(g.paths);
5168
- if (client) await warnVersion(client);
5169
- if (client) {
5437
+ const opened = await connectDaemon(g.paths) ?? await openOneShot(g, {}, "daemon");
5438
+ if (opened instanceof DaemonClient) {
5439
+ const client = opened;
5440
+ await warnVersion(client);
5170
5441
  const handle = await start((m, p) => client.call(m, p), async (chat) => {
5171
5442
  const c = await connectDaemon(g.paths, 1e3);
5172
5443
  if (!c) return null;
@@ -5194,8 +5465,8 @@ async function listenCommand(argv) {
5194
5465
  process.on("SIGTERM", stop);
5195
5466
  return;
5196
5467
  }
5197
- const [{ keepServing, openHost, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5198
- const host = await openHost(g.paths, "daemon", VERSION);
5468
+ const [{ keepServing, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5469
+ const host = opened;
5199
5470
  const call = (m, p) => callApi(host.ctx, m, p);
5200
5471
  const handle = await start(call, async (chat) => (await call("chat.get", { chat })).peer || null).catch(async (error) => {
5201
5472
  await host.close();
@@ -5214,7 +5485,13 @@ async function listenCommand(argv) {
5214
5485
  setTimeout(() => process.exit(code), 2e4).unref();
5215
5486
  served.close().then(() => host.close()).finally(() => process.exit(code));
5216
5487
  };
5217
- host.ctx.stop = stop;
5488
+ host.ctx.listen = true;
5489
+ host.ctx.stop = () => {
5490
+ 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)`;
5491
+ process.stderr.write(`ghostly: ${message}. Start ghostly daemon --detach first, then listen through it: a restart then does not end the listen\n`);
5492
+ print({ error: new CliError("unavailable", message).toJSON() });
5493
+ quit(EXIT.unavailable);
5494
+ };
5218
5495
  onStopSignals(stop);
5219
5496
  onReaderGone(stop);
5220
5497
  let off = null, left = [];
@@ -5271,7 +5548,7 @@ async function engineCommand(argv) {
5271
5548
  type: "boolean",
5272
5549
  description: ""
5273
5550
  }
5274
- });
5551
+ }, void 0, { command: "engine" });
5275
5552
  const g = globals(parsed);
5276
5553
  pretty = g.pretty;
5277
5554
  if (parsed.options.list) {
@@ -5316,7 +5593,10 @@ async function settingsCommand(sub, argv) {
5316
5593
  const parsed = parseArgs(argv, { "show-secret": {
5317
5594
  type: "boolean",
5318
5595
  description: ""
5319
- } });
5596
+ } }, void 0, {
5597
+ command: commandOf("settings", sub),
5598
+ text: sub === "set"
5599
+ });
5320
5600
  const g = globals(parsed);
5321
5601
  pretty = g.pretty;
5322
5602
  if (sub === "get") {
@@ -5325,9 +5605,11 @@ async function settingsCommand(sub, argv) {
5325
5605
  return;
5326
5606
  }
5327
5607
  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>`);
5608
+ const [key, given] = parsed.positionals;
5609
+ if (!key) throw new CliError("usage", "Missing <key>: ghostly settings set <key> <json-value>");
5330
5610
  noMoreThan(2, parsed.positionals, "settings set <key> <json-value>");
5611
+ const { value, warning } = await settingValue(key, given, readStdin, process.stdin.isTTY === true, (note) => process.stderr.write(`ghostly: ${note}\n`));
5612
+ if (warning) process.stderr.write(`ghostly: ${warning}\n`);
5331
5613
  let parsedValue;
5332
5614
  try {
5333
5615
  parsedValue = JSON.parse(value);
@@ -5342,7 +5624,10 @@ async function settingsCommand(sub, argv) {
5342
5624
  }
5343
5625
  async function textCommand(name, argv) {
5344
5626
  const spec = TEXT_COMMANDS[name];
5345
- const parsed = parseArgs(argv, spec.options, idSlot(spec));
5627
+ const parsed = parseArgs(argv, spec.options, idSlot(spec), {
5628
+ command: name,
5629
+ text: true
5630
+ });
5346
5631
  const g = globals(parsed);
5347
5632
  pretty = g.pretty;
5348
5633
  const [target, ...rest] = parsed.positionals;
@@ -5366,7 +5651,7 @@ async function textCommand(name, argv) {
5366
5651
  };
5367
5652
  if (spec.target === "group") params.mentions = parsed.options.mention ?? [];
5368
5653
  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));
5654
+ if (!spec.message) Object.assign(params, (await import("./buttons-BO1_7V4L.js")).buttonsOf(parsed.options));
5370
5655
  print(await withSession(g, (s) => {
5371
5656
  if (spec.target === "chat") {
5372
5657
  params.wait = parsed.options.wait ?? (s.mode === "one-shot" ? spec.message ? "confirmed" : "sent" : "none");
@@ -5405,14 +5690,14 @@ async function identityAddCommand(argv) {
5405
5690
  type: "number",
5406
5691
  description: ""
5407
5692
  }
5408
- });
5693
+ }, void 0, { command: "identity add" });
5409
5694
  const g = globals(parsed);
5410
5695
  pretty = g.pretty;
5411
5696
  const [provider, ...subject] = parsed.positionals;
5412
5697
  if (!provider) throw new CliError("usage", "Missing <provider>: ghostly identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]");
5413
5698
  inRange(parsed.options, "timeout", "a number of seconds", 5, 3600);
5414
5699
  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;
5700
+ const known = parsed.options.days !== void 0 || items.length ? (await import("./registry-DY2ixQfU.js")).IDENTITY_PROVIDERS.find((p) => p.id === provider) : void 0;
5416
5701
  if (known && parsed.options.days !== void 0) inRange(parsed.options, "days", "a whole number", 1, known.validity.maxDays, true);
5417
5702
  const { fields, warning } = await identityFields(items, parsed.options.stdin === true, identitySecretFields(known, parsed.options.signer), readStdin, process.stdin.isTTY === true);
5418
5703
  if (warning) process.stderr.write(`ghostly: ${warning}\n`);
@@ -5427,9 +5712,7 @@ async function identityAddCommand(argv) {
5427
5712
  const tell = (event) => {
5428
5713
  if (event.type === "identity.approval" || event.type === "identity.progress") process.stderr.write(JSON.stringify(event) + "\n");
5429
5714
  };
5430
- requireProfile(g);
5431
- const client = await connectDaemon(g.paths);
5432
- if (client) {
5715
+ const addThroughDaemon = async (client) => {
5433
5716
  await warnVersion(client);
5434
5717
  const watcher = await connectDaemon(g.paths);
5435
5718
  await watcher?.subscribe(void 0, tell);
@@ -5439,10 +5722,19 @@ async function identityAddCommand(argv) {
5439
5722
  client.close();
5440
5723
  watcher?.close();
5441
5724
  }
5725
+ };
5726
+ requireProfile(g);
5727
+ const client = await connectDaemon(g.paths);
5728
+ if (client) {
5729
+ await addThroughDaemon(client);
5442
5730
  return;
5443
5731
  }
5444
5732
  const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);
5445
5733
  const host = await openOneShot(g);
5734
+ if (host instanceof DaemonClient) {
5735
+ await addThroughDaemon(host);
5736
+ return;
5737
+ }
5446
5738
  const off = host.ctx.hub.onEvent(tell);
5447
5739
  try {
5448
5740
  const result = await callApi(host.ctx, "identity.add", params);
@@ -5458,7 +5750,10 @@ async function identityAddCommand(argv) {
5458
5750
  }
5459
5751
  async function tableCommand(name, argv) {
5460
5752
  const command = COMMANDS[name];
5461
- const parsed = parseArgs(argv, command.options ?? {}, idSlot(command));
5753
+ const parsed = parseArgs(argv, command.options ?? {}, idSlot(command), {
5754
+ command: name,
5755
+ text: takesText(command)
5756
+ });
5462
5757
  const g = globals(parsed);
5463
5758
  pretty = g.pretty;
5464
5759
  const args = positionals(command, parsed.positionals);
@@ -5512,7 +5807,7 @@ async function tableCommand(name, argv) {
5512
5807
  });
5513
5808
  if (translator) {
5514
5809
  try {
5515
- printAnswer(await (await import("./translate-DObb-1tq.js")).translateAnswer(result, translator));
5810
+ printAnswer(await (await import("./translate-od5GbpvR.js")).translateAnswer(result, translator));
5516
5811
  } finally {
5517
5812
  translator.close();
5518
5813
  }
@@ -5525,7 +5820,7 @@ async function tableCommand(name, argv) {
5525
5820
  * contact's, raw PCM); what the command says goes to stderr. It ends when the call does.
5526
5821
  */
5527
5822
  async function callPipeCommand(argv) {
5528
- const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }));
5823
+ const parsed = parseArgs(argv, {}, idSlot({ args: ["call...?"] }), { command: "call pipe" });
5529
5824
  const g = globals(parsed);
5530
5825
  const ref = parsed.positionals.join(" ") || void 0;
5531
5826
  const client = await connectDaemon(g.paths);
@@ -5551,7 +5846,9 @@ async function callPipeCommand(argv) {
5551
5846
  }
5552
5847
  /**
5553
5848
  * The command's words when the line asks for help (`help <words>`, or `--help`/`--help=true`/`-h` before any `--`), else
5554
- * null. `--help=false` asks for none: the command runs.
5849
+ * null. `--help=false` asks for none: the command runs. A `-h` or `--help` that is an option's value, as the parser
5850
+ * reads it (`profile set --name --help`, `edit … --text "$NEW"`), asks for none either: it printed the help with exit 0
5851
+ * and changed nothing.
5555
5852
  */
5556
5853
  function helpAsked(argv) {
5557
5854
  const end = argv.indexOf("--");
@@ -5565,18 +5862,46 @@ function helpAsked(argv) {
5565
5862
  return out;
5566
5863
  };
5567
5864
  if (head[0] === "help") return words(head.slice(1));
5568
- if (head.some((word) => word === "--help" || word === "--help=true" || word === "-h")) return words(head);
5865
+ const options = optionsOf(words(head));
5866
+ for (let i = 0; i < head.length; i++) {
5867
+ const word = head[i];
5868
+ if (word === "--help" || word === "--help=true" || word === "-h") return words(head);
5869
+ const option = word.startsWith("--") ? word.includes("=") ? void 0 : options[word.slice(2)] : word.length === 2 && word.startsWith("-") ? Object.values(options).find((o) => o.short === word.slice(1)) : void 0;
5870
+ if (!option || option.type === "boolean") continue;
5871
+ if (option.optionalValue && !(i + 1 < head.length && head[i + 1] !== "" && Number.isFinite(Number(head[i + 1])))) continue;
5872
+ i++;
5873
+ }
5569
5874
  return null;
5570
5875
  }
5876
+ /** The options of the command `words` name (its longest command), with the global ones: what takes a value on its line. */
5877
+ function optionsOf(words) {
5878
+ for (let n = words.length; n > 0; n--) {
5879
+ const asked = words.slice(0, n).join(" ");
5880
+ const row = helpRows().find((r) => commandWords(r.usage).join(" ") === asked);
5881
+ if (row) return {
5882
+ ...GLOBAL_OPTIONS,
5883
+ ...row.options
5884
+ };
5885
+ }
5886
+ return GLOBAL_OPTIONS;
5887
+ }
5888
+ /** No profile yet in the Ghostly folder these global options name: `ghostly`'s first run there. */
5889
+ function newHome(argv) {
5890
+ try {
5891
+ return listProfiles(ghostlyHome(parseArgs([...argv], {}).options.home)).length === 0;
5892
+ } catch {
5893
+ return false;
5894
+ }
5895
+ }
5571
5896
  async function main(input) {
5572
5897
  const argv = liftGlobals(input);
5573
5898
  const helpFor = argv.length === 0 || globalOption(argv[0]) ? [] : helpAsked(argv);
5574
5899
  if (helpFor) {
5575
- process.stdout.write((helpFor.length ? commandHelp(helpFor) : help()) + "\n");
5900
+ process.stdout.write((helpFor.length ? commandHelp(helpFor) : help(argv[0] !== "help" && newHome(argv))) + "\n");
5576
5901
  return 0;
5577
5902
  }
5578
5903
  if (argv[0] === "--version" || argv[0] === "version") {
5579
- const parsed = parseArgs(argv.slice(1), {});
5904
+ const parsed = parseArgs(argv.slice(1), {}, void 0, { command: "version" });
5580
5905
  noMoreThan(0, parsed.positionals, "version");
5581
5906
  pretty = parsed.options.pretty === true;
5582
5907
  print({ version: VERSION });
@@ -5640,6 +5965,7 @@ async function main(input) {
5640
5965
  * A command line that names no command. The words of a group (`ghostly chat`, `ghostly wallet frob`, `ghostly x401
5641
5966
  * credential`) are answered with the group's commands, as `ghostly help chat` lists them; before, it was only "Unknown
5642
5967
  * command: chat". The longest group the words name answers: `x401 credential frob` lists add, list and remove.
5968
+ * 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
5969
  */
5644
5970
  function unknownCommand(first, second, third) {
5645
5971
  const asked = [
@@ -5648,14 +5974,24 @@ function unknownCommand(first, second, third) {
5648
5974
  third
5649
5975
  ].filter((word) => !!word);
5650
5976
  const all = helpRows().map((row) => commandWords(row.usage));
5977
+ const takes = (group) => [...new Set(all.filter((words) => words.length > group.length && group.every((word, i) => words[i] === word)).map((words) => words[group.length]))];
5978
+ const meant = (typed, words) => new CliError("usage", `Unknown command: ${typed.join(" ")} (did you mean ${words.join(" ")}? ghostly help ${words.join(" ")})`);
5651
5979
  for (let depth = Math.min(asked.length, 2); depth >= 1; depth--) {
5652
5980
  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]))];
5981
+ const subs = takes(group);
5654
5982
  if (!subs.length) continue;
5983
+ const near = extra === void 0 ? void 0 : nearest(extra, subs);
5984
+ if (near) return meant([...group, extra], [...group, near]);
5655
5985
  const list = `${subs.slice(0, -1).join(", ")}${subs.length > 1 ? " or " : ""}${subs.at(-1)}`;
5656
5986
  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
5987
  }
5658
- return new CliError("usage", `Unknown command: ${asked.slice(0, 2).join(" ") || "\"\""} (ghostly help)`);
5988
+ const near = asked[0] === void 0 ? void 0 : nearest(asked[0], takes([]));
5989
+ if (!near) return new CliError("usage", `Unknown command: ${asked[0] ?? "\"\""} (ghostly help)`);
5990
+ return asked[1] !== void 0 && takes([near]).includes(asked[1]) ? meant(asked.slice(0, 2), [near, asked[1]]) : meant([asked[0]], [near]);
5991
+ }
5992
+ /** The command a group's word names (`profile set`), for its usage errors; the group itself for a word it does not take. */
5993
+ function commandOf(group, sub) {
5994
+ return sub !== void 0 && helpRows().some((row) => commandWords(row.usage).join(" ") === `${group} ${sub}`) ? `${group} ${sub}` : group;
5659
5995
  }
5660
5996
  /** Leaves once what was printed reached stdout (a pipe drains asynchronously). */
5661
5997
  function exit(code) {
@@ -5691,4 +6027,4 @@ async function run(argv) {
5691
6027
  //#endregion
5692
6028
  export { run };
5693
6029
 
5694
- //# sourceMappingURL=main-6QOSvQ8b.js.map
6030
+ //# sourceMappingURL=main-BRxhBctJ.js.map