@ghostlytools/cli 1.13.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/dist/assets/{api-CVtg7MpI.js → api-DF36rBJK.js} +2 -2
- package/dist/assets/{api-CjOaoG-v.js → api-Dnq86JAA.js} +135 -37
- package/dist/assets/api-Dnq86JAA.js.map +1 -0
- package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-nLK4jeTq.js} +3 -3
- package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-nLK4jeTq.js.map} +1 -1
- package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-wqBWi3Ry.js} +2 -2
- package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-wqBWi3Ry.js.map} +1 -1
- package/dist/assets/{apps-Cuk45sz5.js → apps-DBVhKpfe.js} +10 -10
- package/dist/assets/apps-DBVhKpfe.js.map +1 -0
- package/dist/assets/{apps-DjY095Af.js → apps-nLtyhC2f.js} +1 -1
- package/dist/assets/{backup-DekVCDWv.js → backup-Bczllmzf.js} +4 -4
- package/dist/assets/{backup-DekVCDWv.js.map → backup-Bczllmzf.js.map} +1 -1
- package/dist/assets/{backup-B56sQqoQ.js → backup-D6s0LQdg.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
- package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-DML_-Xbv.js} +2 -2
- package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-DML_-Xbv.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
- package/dist/assets/{buttons-BGxzOtrq.js → buttons-B3C3vdhH.js} +8 -8
- package/dist/assets/buttons-B3C3vdhH.js.map +1 -0
- package/dist/assets/buttons-DaY5FYlV.js +1 -0
- package/dist/assets/{client-DcQAfc3h.js → client-B7jRrSnb.js} +3 -3
- package/dist/assets/{client-DcQAfc3h.js.map → client-B7jRrSnb.js.map} +1 -1
- package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
- package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
- package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
- package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
- package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-H3i6o9Iy.js} +2 -2
- package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-H3i6o9Iy.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
- package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupMeta-goASqzOt.js → groupMeta--fxSh792.js} +72 -4
- package/dist/assets/groupMeta--fxSh792.js.map +1 -0
- package/dist/assets/{host-C2WRKj3g.js → host-CGzVFfMz.js} +169 -36
- package/dist/assets/host-CGzVFfMz.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-B4_wdCtx.js} +2 -2
- package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-B4_wdCtx.js.map} +1 -1
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-Ce-gWsRY.js} +2 -2
- package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-Ce-gWsRY.js.map} +1 -1
- package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-Dp1i8v6n.js} +12 -11
- package/dist/assets/irohWeb-Dp1i8v6n.js.map +1 -0
- package/dist/assets/{main-Dh7fePd8.js → main-C8J53SwH.js} +67 -62
- package/dist/assets/main-C8J53SwH.js.map +1 -0
- package/dist/assets/{ownDid-BErplN7N.js → ownDid-oa-T2vmZ.js} +8 -4
- package/dist/assets/ownDid-oa-T2vmZ.js.map +1 -0
- package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-Bc08eNJY.js} +6 -6
- package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-Bc08eNJY.js.map} +1 -1
- package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-Dppn8lUN.js} +3 -3
- package/dist/assets/pairedTransports-Dppn8lUN.js.map +1 -0
- package/dist/assets/{profiles-B8xO8-oj.js → profiles-B2uy04ph.js} +3 -3
- package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-B2uy04ph.js.map} +1 -1
- package/dist/assets/{registry-CU8PevhI.js → registry-DbTLLs3y.js} +9 -5
- package/dist/assets/registry-DbTLLs3y.js.map +1 -0
- package/dist/assets/{registry--Rg2YvOH.js → registry-bLIfG619.js} +1 -1
- package/dist/assets/{resolve-B1upovPM.js → resolve-DNX-eecG.js} +9 -4
- package/dist/assets/resolve-DNX-eecG.js.map +1 -0
- package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
- package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
- package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
- package/dist/assets/{server-Dgxx_DaN.js → server-DWJ4RzJn.js} +536 -209
- package/dist/assets/server-DWJ4RzJn.js.map +1 -0
- package/dist/assets/{translate-BcbSWkuq.js → translate-CHj_PdLg.js} +13 -8
- package/dist/assets/translate-CHj_PdLg.js.map +1 -0
- package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-Cvz5CiKR.js} +57 -3
- package/dist/assets/waitNotice-Cvz5CiKR.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-CjOaoG-v.js.map +0 -1
- package/dist/assets/apps-Cuk45sz5.js.map +0 -1
- package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
- package/dist/assets/buttons-CsN2WJOf.js +0 -1
- package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
- package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
- package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
- package/dist/assets/host-C2WRKj3g.js.map +0 -1
- package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
- package/dist/assets/main-Dh7fePd8.js.map +0 -1
- package/dist/assets/ownDid-BErplN7N.js.map +0 -1
- package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
- package/dist/assets/registry-CU8PevhI.js.map +0 -1
- package/dist/assets/resolve-B1upovPM.js.map +0 -1
- package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
- package/dist/assets/server-Dgxx_DaN.js.map +0 -1
- package/dist/assets/translate-BcbSWkuq.js.map +0 -1
- package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"main-Dh7fePd8.js","names":["listed","commands","commands","commands","commands","commands","commands","commands","commands","general","chats","groups","files","payments","identities","services","calls","apps","packageJson","sinceOf","since"],"sources":["../../package.json","../../src/args.ts","../../src/commands/shared.ts","../../src/commands/apps.ts","../../src/commands/calls.ts","../../src/commands/chats.ts","../../src/commands/files.ts","../../src/commands/general.ts","../../src/commands/groups.ts","../../src/commands/identities.ts","../../src/commands/payments.ts","../../src/commands/services.ts","../../src/commands/index.ts","../../src/listen.ts","../../src/secretInput.ts","../../src/main.ts"],"sourcesContent":["{\n \"name\": \"@ghostlytools/cli\",\n \"version\": \"1.13.0\",\n \"type\": \"module\",\n \"description\": \"Ghostly for bots and terminals: the app's own engine, headless on Node, behind a daemon and a `ghostly` command with JSON output.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/MiguelMedeiros/ghostly.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://ghostly.tools/cli\",\n \"bugs\": \"https://github.com/MiguelMedeiros/ghostly/issues\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"bin\": {\n \"ghostly\": \"./dist/ghostly.mjs\"\n },\n \"files\": [\n \"dist\",\n \"examples\",\n \"skills\",\n \"README.md\",\n \"SKILL.md\",\n \"npm-shrinkwrap.json\"\n ],\n \"engines\": {\n \"node\": \">=22.12\"\n },\n \"scripts\": {\n \"build\": \"vite build\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\",\n \"test\": \"vitest run\"\n },\n \"dependencies\": {\n \"@arkade-os/sdk\": \"0.5.4\",\n \"@atproto/jwk-webcrypto\": \"^0.3.4\",\n \"@atproto/oauth-client\": \"^0.9.3\",\n \"@bitcoindevkit/bdk-wallet-web\": \"0.4.0\",\n \"@bitcoinerlab/descriptors-scure\": \"^3.2.1\",\n \"@cashu/cashu-ts\": \"^4.13.0\",\n \"@fedimint/core\": \"0.0.0-canary-eea6a3c98909fa8e736d6dadb1f1243fd3322b27\",\n \"@fedimint/fedimint-client-wasm-bundler\": \"0.0.0-canary-eea6a3c98909fa8e736d6dadb1f1243fd3322b27\",\n \"@fedimint/types\": \"0.0.0-canary-eea6a3c98909fa8e736d6dadb1f1243fd3322b27\",\n \"@hyperswarm/dht-relay\": \"0.4.3\",\n \"@noble/ciphers\": \"^2.4.0\",\n \"@noble/curves\": \"^2.4.0\",\n \"@noble/hashes\": \"2.4.0\",\n \"@scure/base\": \"2.4.0\",\n \"@scure/bip32\": \"^2.4.0\",\n \"@scure/bip39\": \"2.4.0\",\n \"@scure/btc-signer\": \"2.4.1\",\n \"@secondts/bark\": \"0.27.0\",\n \"@serenity-kit/opaque\": \"1.1.0\",\n \"@synonymdev/pubky\": \"0.18.0\",\n \"@tetherto/wdk-wallet-evm\": \"1.0.0-beta.24\",\n \"b4a\": \"1.9.0\",\n \"bittorrent-dht\": \"11.0.12\",\n \"ethers\": \"6.17.0\",\n \"eventsource\": \"^5.1.4\",\n \"fake-indexeddb\": \"6.2.8\",\n \"hyperdht\": \"6.36.0\",\n \"keet-identity-key\": \"3.2.0\",\n \"mpg123-decoder\": \"1.0.3\",\n \"node-datachannel\": \"^0.33.6\",\n \"nostr-tools\": \"2.26.0\",\n \"opus-decoder\": \"0.7.12\",\n \"opusscript\": \"0.1.1\",\n \"ws\": \"8.22.1\"\n },\n \"devDependencies\": {\n \"@ghostly/browser\": \"*\",\n \"@ghostly/core\": \"*\",\n \"@ghostly/iroh-web\": \"*\",\n \"@types/node\": \"^26.6.6\",\n \"typescript\": \"^5.9.3\",\n \"vite\": \"^8.3.6\",\n \"vitest\": \"^5.1.0\"\n }\n}\n","import { CliError } from \"./errors\";\n\nexport type OptionType = \"string\" | \"number\" | \"boolean\" | \"list\";\nexport interface OptionSpec {\n type: OptionType; short?: string; description: string;\n /** A number option that may stand alone (then `true`): it takes the next word only when that is a number. */\n optionalValue?: boolean;\n /** What a number option takes, as its refusal says it (`a length in milliseconds`); default \"a number\". */\n takes?: string;\n /** A boolean the command takes only as `--no-<name>`: help shows it so. */\n negatedOnly?: boolean;\n /** A boolean whose usage shows `[--<name> | --no-<name>]`: both ways on one line are a usage error, not the last. */\n eitherWay?: boolean;\n /**\n * The words a string option takes: any other (or \"\") is a usage error that names the flag and lists them, before the\n * profile opens. Before, the API answered it (\"network must be one of mainnet, testnet\", bad_request, exit 1).\n */\n choices?: readonly string[];\n}\nexport interface Parsed { positionals: string[]; options: Record<string, string | number | boolean | string[] | undefined> }\n\n/**\n * A number as typed on the command line, in decimal digits only (`21`, `-5`, `12.5`); NaN for any other word.\n * `Number()` alone read `1e3` as 1,000, `0x10` as 16 and `\" 21\"` as 21: `chat pay bob 2e3`, a typo of 23, paid 2,000.\n */\nexport const decimalNumber = (value: string): number => /^-?\\d+(\\.\\d+)?$/.test(value) ? Number(value) : NaN;\nconst notANumber = (name: string, option: OptionSpec, value: string) => new CliError(\"usage\", `--${name} takes ${option.takes ?? \"a number\"}, not ${JSON.stringify(value)}`);\n\n/**\n * The word right after an option that stood alone because it was no number (`--voice 2s`), by the positionals a parse\n * returned: should the line have one too many, that word was the option's value, and `strayValue` says so.\n */\nconst lonelyValues = new WeakMap<readonly string[], { index: number; word: string; refusal: CliError }[]>();\n\n/** The refusal of an option's value that was taken as a positional (`--voice 2s`), else undefined. */\nexport function strayValue(values: readonly string[]): CliError | undefined {\n return lonelyValues.get(values)?.find(({ index, word }) => values[index] === word)?.refusal;\n}\n/**\n * The command a line is parsed for, as its unknown options name it: `send`, whether text comes on its line, and which\n * positionals take a number (`<sats>`): there a word like `-5` is that number, refused as one, not an unknown option.\n */\nexport interface ParseFor { command: string; text?: boolean; number?: (index: number) => boolean }\n\n/**\n * Options every command takes. They may come anywhere on the line.\n */\nexport const GLOBAL_OPTIONS: Record<string, OptionSpec> = {\n profile: { type: \"string\", short: \"p\", description: \"Profile to use (default: $GHOSTLY_PROFILE, then the current one)\" },\n home: { type: \"string\", description: \"Ghostly's folder (default: $GHOSTLY_HOME, then ~/.ghostly)\" },\n pretty: { type: \"boolean\", description: \"Indent the JSON output\" },\n help: { type: \"boolean\", short: \"h\", description: \"Show help\" },\n};\n\n/**\n * A small, strict parser: `--name value`, `--name=value`, `-x value`, boolean flags, repeatable lists, and `--`\n * before positionals that start with a dash.\n *\n * The value of an option is taken as is even when it starts with `-` (base64url keys and seeds do one time in 64:\n * the ghostly-cli lesson of #208). So is a positional that `idSlot` says takes an id, a key or a draft: there a word\n * that starts with `-`, is longer than two characters and is no option of the command is the value (`--` starts one\n * id in 4096; `-x` stays an option). Any other positional that starts with `-` is refused instead of sent: a\n * mistyped flag must not reach a contact as text. Put `--` before a message that starts with a dash. Where `parsing`\n * says a number comes, a word of a dash and a digit (`-5`) that is no option is that number, for the command to refuse\n * in its own words (`<sats> takes a whole number from 1 up, not -5`); no option's name starts with a digit.\n *\n * An unknown option names the command `parsing` gives, the nearest of its options and its help.\n */\nexport function parseArgs(argv: readonly string[], spec: Record<string, OptionSpec>, idSlot: (index: number) => boolean = () => false, parsing?: ParseFor): Parsed {\n const all = { ...GLOBAL_OPTIONS, ...spec };\n const byShort = new Map(Object.entries(all).filter(([, s]) => s.short).map(([name, s]) => [s.short!, name]));\n const isOption = (arg: string) => {\n if (!arg.startsWith(\"--\")) return arg.length === 2 && byShort.has(arg.slice(1));\n const name = arg.slice(2).split(\"=\")[0];\n return Object.hasOwn(all, name) || (name.startsWith(\"no-\") && all[name.slice(3)]?.type === \"boolean\");\n };\n const positionals: string[] = [];\n const lonely: { index: number; word: string; refusal: CliError }[] = [];\n const options: Parsed[\"options\"] = {};\n const setBoolean = (name: string, value: boolean) => {\n if (all[name].eitherWay && options[name] !== undefined && options[name] !== value) throw new CliError(\"usage\", `--${name} or --no-${name}, not both`);\n options[name] = value;\n };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--\") { positionals.push(...argv.slice(i + 1)); break; }\n if (/^-\\d/.test(arg) && parsing?.number?.(positionals.length) && !isOption(arg)) { positionals.push(arg); continue; }\n if (arg.startsWith(\"-\") && arg.length > 2 && idSlot(positionals.length) && !isOption(arg)) { positionals.push(arg); continue; }\n if (arg.startsWith(\"--\") || (arg.startsWith(\"-\") && arg.length === 2 && arg !== \"-\")) {\n let name: string, inline: string | undefined;\n if (arg.startsWith(\"--\")) {\n const eq = arg.indexOf(\"=\");\n name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);\n inline = eq === -1 ? undefined : arg.slice(eq + 1);\n } else {\n const long = byShort.get(arg.slice(1));\n if (!long) throw unknownOption(arg, all, parsing);\n name = long;\n }\n if (name.startsWith(\"no-\") && all[name.slice(3)]?.type === \"boolean\") {\n // `--no-pretty=true` was an unknown option whose nearest name was `--no-pretty`, the word typed.\n if (inline !== undefined) throw new CliError(\"usage\", `--${name} takes no value`);\n setBoolean(name.slice(3), false);\n continue;\n }\n const option = all[name];\n if (!option) throw unknownOption(`--${name}`, all, parsing);\n if (option.type === \"boolean\") {\n if (inline !== undefined && ![\"true\", \"false\"].includes(inline)) throw new CliError(\"usage\", `--${name} takes no value`);\n setBoolean(name, inline === undefined || inline === \"true\");\n continue;\n }\n let value = inline;\n // An empty word after it is its value, refused below: `--voice \"$MS\"` with MS unset, not a positional (\"Too many\n // arguments\", or \"Missing <path>\" with the path given). Number(\"\") is 0, so it is taken here.\n if (value === undefined && option.optionalValue && !(i + 1 < argv.length && Number.isFinite(Number(argv[i + 1])))) {\n options[name] = true;\n const next = argv[i + 1];\n if (next && !next.startsWith(\"-\")) lonely.push({ index: positionals.length, word: next, refusal: notANumber(name, option, next) });\n continue;\n }\n if (value === undefined) {\n if (i + 1 >= argv.length) throw new CliError(\"usage\", `--${name} needs a value`);\n value = argv[++i];\n }\n if (option.type === \"number\") {\n // Number(\"\") and Number(\" \") are 0: an unset variable must not read as 0 and be acted on.\n const number = decimalNumber(value);\n if (!Number.isFinite(number)) throw notANumber(name, option, value);\n options[name] = number;\n } else if (option.type === \"list\") {\n options[name] = [...((options[name] as string[] | undefined) ?? []), value];\n } else {\n if (option.choices && !option.choices.includes(value)) throw new CliError(\"usage\", `--${name} takes ${listed(option.choices)}, not ${JSON.stringify(value)}`);\n options[name] = value;\n }\n continue;\n }\n if (arg.startsWith(\"-\") && arg !== \"-\") throw unknownOption(arg, all, parsing);\n positionals.push(arg);\n }\n if (lonely.length) lonelyValues.set(positionals, lonely);\n return { positionals, options };\n}\n\n/**\n * `Unknown option --wiat for ghostly send (did you mean --wait? ghostly help send)`. The `--` hint only where text comes\n * and for a word with one dash, which may be text (`-1`, `-x`): `version -x` has no text to put after `--`.\n */\nfunction unknownOption(arg: string, all: Record<string, OptionSpec>, parsing: ParseFor | undefined, help = parsing ? `ghostly help ${parsing.command}` : undefined): CliError {\n const names = Object.entries(all).flatMap(([name, o]) => (o.type === \"boolean\" ? [name, `no-${name}`] : [name]));\n const near = nearest(arg.replace(/^--?/, \"\"), names);\n const privateKey = /PRIVATE KEY/.test(arg);\n const hints = [\n ...(near ? [`did you mean --${near}?`] : []),\n ...(privateKey ? [\"never paste a private key anywhere: Ghostly only needs the public key;\"] : []),\n ...(parsing?.text && /^-[^-]/.test(arg) ? [\"put -- before text that starts with a dash;\"] : []),\n ...(help ? [help] : []),\n ];\n return new CliError(\"usage\", `Unknown option ${shownOption(arg, privateKey)}${parsing ? ` for ghostly ${parsing.command}` : \"\"}${hints.length ? ` (${hints.join(\" \")})` : \"\"}`);\n}\n\n/**\n * An unknown option as its refusal names it: a pasted private key (a PEM or OpenPGP block starts with dashes), a word\n * with a line break or one longer than any option's name is described, not printed (docs/CLI.md \"Secrets stay hidden\").\n * A seed, an nsec, a hex key or a Cashu token is longer than 40 characters too.\n */\nfunction shownOption(arg: string, privateKey: boolean): string {\n if (privateKey) return \"(a private key)\";\n return arg.length > 40 || /[\\r\\n]/.test(arg) ? `(a ${arg.length}-character word)` : arg;\n}\n\n/**\n * A first word that starts with a dash and is no global option (`ghostly --porfile bot send …`, `ghostly -x status`):\n * `Unknown option --porfile (did you mean --profile? ghostly help)`, as after the command. Before, \"Unknown command\".\n */\nexport function unknownGlobalOption(arg: string): CliError {\n return unknownOption(arg.startsWith(\"--\") ? arg.split(\"=\")[0] : arg, GLOBAL_OPTIONS, undefined, \"ghostly help\");\n}\n\n/**\n * The word of `words` a typo most likely meant: the nearest by Damerau-Levenshtein distance (a letter added, dropped,\n * changed or two swapped), at most 2 and at most a third of the word's length (`wiat` one: `nope` is not `home`; `-x`\n * none), else undefined.\n */\nexport function nearest(typed: string, words: Iterable<string>): string | undefined {\n const most = Math.min(2, Math.floor(typed.length / 3));\n let best: string | undefined, bestDistance = most + 1;\n for (const word of words) {\n // The distance is at least the lengths' difference: a long text that starts with a dash builds no table per name.\n if (Math.abs(typed.length - word.length) >= bestDistance) continue;\n const d = distance(typed, word);\n if (d < bestDistance) { best = word; bestDistance = d; }\n }\n return best;\n}\n\n/** The optimal string alignment distance: the edits that turn `a` into `b`, a swap of two neighbours one of them. */\nfunction distance(a: string, b: string): number {\n const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));\n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);\n 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);\n }\n }\n return d[a.length][b.length];\n}\n\n/** The kind of value each key `settings set` takes has (api.ts `SETTABLE`). */\nexport type SettingKind = \"strings\" | \"string\" | \"boolean\" | \"ice\";\nconst SETTINGS_SET = \"ghostly settings set <key> <json-value> [--force]\";\n\n/**\n * A key `settings set` does not take is a usage error that names the nearest one (whatever its case: `sendtyping`)\n * and lists them, before stdin is read and the profile opens. Before, the API answered it once a one-shot was online\n * (bad_request, exit 1), with no \"did you mean\". The API keeps its own check for a socket's callers.\n */\nexport function checkSettingKey(key: string, kinds: Record<string, SettingKind>): SettingKind {\n if (Object.hasOwn(kinds, key)) return kinds[key];\n const byLower = new Map(Object.keys(kinds).map((name) => [name.toLowerCase(), name]));\n const near = byLower.get(nearest(key.toLowerCase(), byLower.keys()) ?? \"\");\n throw new CliError(\"usage\", `${key} is not a setting the CLI changes${near ? ` (did you mean ${near}?)` : \"\"}: ghostly settings set takes ${Object.keys(kinds).join(\", \")} (ghostly help settings set)`);\n}\n\n/** A value of another kind than its key takes (`online maybe`): a usage error too, before the profile opens. */\nexport function checkSettingValue(key: string, kind: SettingKind, value: unknown, typed: string): void {\n if (kind === \"boolean\" && typeof value !== \"boolean\") throw new CliError(\"usage\", `${key} takes true or false, not ${JSON.stringify(typed)}: ${SETTINGS_SET}`);\n // Not echoed: a TURN password may be in it.\n if (kind === \"strings\" && !(Array.isArray(value) && value.every((v) => typeof v === \"string\"))) throw new CliError(\"usage\", `${key} takes a JSON list of strings: ${SETTINGS_SET}`);\n if (kind === \"ice\" && !(Array.isArray(value) && value.every((v) => v && typeof v === \"object\"))) throw new CliError(\"usage\", `${key} takes a JSON list of ICE servers: ${SETTINGS_SET}`);\n}\n\n/** Words as a sentence lists them: \"a\", \"a or b\", \"a, b or c\". */\nconst listed = (words: readonly string[]) => (words.length > 1 ? `${words.slice(0, -1).join(\", \")} or ${words.at(-1)}` : words[0]);\n\n/** The global option a word names (`--profile`, `--profile=bot`, `-p`), else undefined. */\nexport function globalOption(arg: string): OptionSpec | undefined {\n const name = globalName(arg);\n return name ? GLOBAL_OPTIONS[name] : undefined;\n}\n\n/** The name of the global option a word names (`profile` for `-p`, `pretty` for `--no-pretty`), else undefined. */\nfunction globalName(arg: string): string | undefined {\n const eq = arg.indexOf(\"=\");\n const name = arg.startsWith(\"--\") ? arg.slice(2, eq === -1 ? undefined : eq) : arg.length === 2 && arg.startsWith(\"-\") ? Object.entries(GLOBAL_OPTIONS).find(([, o]) => o.short === arg.slice(1))?.[0] : undefined;\n if (name && Object.hasOwn(GLOBAL_OPTIONS, name)) return name;\n // A boolean's `--no-` form, as the parser reads it (with no value): before, `ghostly --no-pretty status` was no command.\n const negated = name?.startsWith(\"no-\") && eq === -1 ? name.slice(3) : undefined;\n return negated && GLOBAL_OPTIONS[negated]?.type === \"boolean\" ? negated : undefined;\n}\n\n/**\n * Global options given before the command (`ghostly --profile bot send …`) move after it, where every command's\n * parser reads them. Stops at `--` and at the first word that is not a global option. They go before the first word\n * after the command's that starts with a dash (its first option, or the `--` that ends them), else at the end: never\n * between an option and its value, which may itself be `--` (`--pretty profile set --name --`). One that takes a value\n * and is the last word has none: a usage error.\n */\nexport function liftGlobals(argv: readonly string[]): string[] {\n const lifted: string[] = [];\n let i = 0;\n while (i < argv.length) {\n const arg = argv[i];\n const eq = arg.indexOf(\"=\");\n const option = globalOption(arg);\n if (!option || arg === \"--\") break;\n const takesValue = option.type !== \"boolean\" && eq === -1;\n // `ghostly -p` alone: a usage error, as `ghostly send -p` is, not the help a line of global options alone shows.\n if (takesValue && i + 1 >= argv.length) throw new CliError(\"usage\", `--${globalName(arg)} needs a value`);\n lifted.push(...argv.slice(i, i + (takesValue ? 2 : 1)));\n i += takesValue ? 2 : 1;\n }\n const rest = argv.slice(i);\n // The first word is the command, also when it is `--version` or `--help`; a `--` there ends the options at once.\n const dash = rest[0] === \"--\" ? 0 : rest.findIndex((word, i) => i > 0 && word.startsWith(\"-\"));\n return dash === -1 ? [...rest, ...lifted] : [...rest.slice(0, dash), ...lifted, ...rest.slice(dash)];\n}\n","import { closeSync, openSync, readSync, type Stats, statSync } from \"node:fs\";\nimport { reactionEmoji } from \"@ghostly/core\";\n// From its own module, not the package: the command table is read by every command, and the package is all of the\n// protocol (~100 ms to load), which a command a daemon answers never needs.\nimport { CRON_LINE, ITEM_STATES, PR_CHECKS, PR_STATES, ROUTINE_STATES, RUN_RESULTS, STATUS_CARD_LIMITS, TASK_STATUSES, cardLine, cardUrl, statusCardBytes } from \"@ghostly/core/statusCards\";\nimport { decimalNumber, type OptionSpec, type Parsed } from \"../args\";\nimport { CliError, localFileError } from \"../errors\";\nimport { userPath } from \"../profiles\";\n\n/**\n * The commands that are one API method each: how the command line becomes the method's parameters. Commands with\n * their own flow (profiles, the daemon, listen, send's stdin, the engine passthrough) live in main.ts.\n */\nexport interface Command {\n method: string;\n usage: string;\n summary: string;\n options?: Record<string, OptionSpec>;\n /** Positionals, in order; a trailing `...` one takes the rest joined by spaces. */\n args?: string[];\n /** The words a positional takes, by its name in `args`: any other is a usage error before the profile opens. */\n words?: Record<string, readonly string[]>;\n params?: (parsed: Parsed, args: Record<string, string | undefined>) => Record<string, unknown>;\n /**\n * A command that runs here, on files, with no profile or daemon (the publisher tools of WISP 1200): its answer is\n * printed as a method's is, and `method` only names it.\n */\n run?: (parsed: Parsed, args: Record<string, string | undefined>) => Promise<Record<string, unknown>>;\n}\n\nexport const wait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"sent\", \"delivered\"], description: \"none, sent or delivered (default: none with a daemon, sent without)\" },\n timeout: { type: \"number\", description: \"Seconds to wait (default 30)\" },\n};\n/** A group has no receipts: `sent` waits until an edge took the frame (a member's, or one of my hubs'). */\nexport const groupWait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"sent\"], description: \"none or sent: until an edge took it (default none)\" },\n timeout: { type: \"number\", description: \"Seconds to wait (default 30)\" },\n};\n/** `listen`, `events` and `chat history`: received messages with `translation: { from, text }` (translate.ts). */\nexport const translate: OptionSpec = { type: \"string\", description: \"Not in this build yet (no language detector): messages print untranslated. Meant to add a translation into this language (en, pt...) to received messages, made on this machine\" };\nexport const net: OptionSpec ={ type: \"string\", choices: [\"mainnet\", \"testnet\"], description: \"mainnet or testnet (default testnet)\" };\nexport const card: OptionSpec = { type: \"string\", description: \"A Lightning card (its id; default: the network's default)\" };\nexport const memo: OptionSpec = { type: \"string\", description: \"What it is for (up to 140 characters)\" };\nexport const confirmReal: OptionSpec = { type: \"boolean\", description: \"Confirm a Mainnet (real money) spend\" };\n\n/**\n * A path as this command's working directory means it: the daemon runs elsewhere. \"\" (an unset variable in a script)\n * names no file, never the current folder; `~/…` is in the user's home (userPath).\n */\nexport function here(path: unknown): string | undefined {\n if (path === \"\") throw new CliError(\"usage\", \"A path given as \\\"\\\" names no file\");\n return typeof path === \"string\" ? userPath(path) : undefined;\n}\n\n/**\n * A path on this machine a command reads (`file send`, a picture, `profile backup --out`'s folder), looked at before the\n * profile opens: one not there is not_found (`missing`, or \"No such file or folder\"), one not allowed refused. Before, a\n * one-shot opened the profile and went online first (~1 s on a big profile) to say so. The API keeps its check for\n * socket callers; through a daemon it reads the same path.\n */\nexport function localStat(path: string, missing?: string): Stats {\n try { return statSync(path); } catch (error) {\n const known = localFileError(error, path);\n throw known?.code === \"not_found\" && missing ? new CliError(\"not_found\", missing) : known ?? error;\n }\n}\n\n/**\n * A picture's file (`profile picture`, `group picture`), in the API's words (groupAdmin.ts) when it is not there or a\n * folder. Only a folder is refused here: a pipe (`<(…)`) is read as a file.\n */\nexport function picture(path: string | undefined): string | undefined {\n if (path !== undefined && localStat(path).isDirectory()) throw new CliError(\"bad_request\", `${path} is a folder: name a file`);\n return path;\n}\n\n/** The most a command reads of stdin or of a file it sends: the longest request line a daemon reads (client.ts `MAX_LINE`). */\nexport const INPUT_BYTES = 16 * 1024 * 1024;\nexport const STDIN_TOO_BIG = \"More than 16 MiB came on stdin, more than any command takes (a long text goes as a file: ghostly file send <chat|group> <path>)\";\n\n/**\n * A file's text, or stdin's (`0`), up to `INPUT_BYTES`: more is refused as it comes. `app send … -`, a card's `--json`\n * and the files `identity complete` and `x401 credential add` send were read whole: 600 MiB answered V8's \"Cannot\n * create a string longer than 0x1fffffe8 characters\", and past 16 MiB a daemon cut the line (\"The daemon went away\").\n */\nexport function readInput(file: string | 0): string {\n const fd = file === 0 ? 0 : openSync(file, \"r\");\n try {\n const chunks: Buffer[] = [];\n let bytes = 0;\n for (;;) {\n const chunk = Buffer.allocUnsafe(1024 * 1024);\n const read = readSync(fd, chunk, 0, chunk.length, null);\n if (!read) return Buffer.concat(chunks).toString(\"utf8\");\n bytes += read;\n if (bytes > INPUT_BYTES) throw new CliError(\"bad_request\", file === 0 ? STDIN_TOO_BIG : `${file} holds more than 16 MiB, more than any command takes (a file to share goes as one: ghostly file send <chat|group> <path>)`);\n chunks.push(chunk.subarray(0, read));\n }\n } finally { if (file !== 0) closeSync(fd); }\n}\n\n/**\n * A list option that names chats (`--to`, `--from`): \"\" or \"group:\" alone (an unset variable in a script) names\n * nothing, and is a usage error before the profile opens; it was a prefix of every id and took the only chat or group.\n */\nexport function refs(values: unknown, flag: string, what: string): void {\n if (!Array.isArray(values)) return;\n for (const value of values) {\n if (typeof value === \"string\" && !value.replace(/^group:/, \"\").trim()) throw new CliError(\"usage\", `--${flag} ${JSON.stringify(value)} names no ${what}`);\n }\n}\n\n/**\n * A whole number of sats from the command line (`<sats>`), refused in a number flag's words: `<sats> takes a whole\n * number from 1 up, not -5`, a number as typed, other words quoted. Before: \"Not an amount in sats: \\\"-5\\\"\".\n */\nexport function sats(value: string | undefined): number {\n const n = decimalNumber(value ?? \"\");\n if (!Number.isSafeInteger(n) || n <= 0) {\n const shown = Number.isNaN(n) ? JSON.stringify(value) : value;\n throw new CliError(\"usage\", `<sats> takes a whole number from 1 up, not ${shown}`);\n }\n return n;\n}\n\n/** `name=value` options as an object. */\nexport function pairs(values: unknown): Record<string, string> | undefined {\n if (!Array.isArray(values) || !values.length) return undefined;\n const out: Record<string, string> = {};\n for (const item of values as string[]) {\n const eq = item.indexOf(\"=\");\n // Never the item itself: a --value is a wallet's seed phrase or macaroon as often as not (as `--field`'s, secretInput).\n if (eq < 1) throw new CliError(\"usage\", \"--value takes name=value, and one has no name or no =\");\n out[item.slice(0, eq)] = item.slice(eq + 1);\n }\n return out;\n}\n\nexport const rate: OptionSpec = { type: \"number\", description: \"The audio's sample rate: 48000 (default), 24000, 16000, 12000 or 8000\" };\nexport const force: OptionSpec = { type: \"boolean\", description: \"Send even if the text looks like a seed, a key or ecash\" };\nexport const reply: OptionSpec = { type: \"string\", description: \"Reply to this message (its id, from history or an event)\" };\n/** Buttons under a message (WISP 406 · Message Buttons): the text is the question. */\nexport const buttonOptions: Record<string, OptionSpec> = {\n button: { type: \"list\", description: \"A button under the message, id:Label (again for each, 1 to 6; the label may hold colons). A press comes back as button.pressed\" },\n style: { type: \"list\", description: \"A button's look, id=primary, neutral or danger\" },\n once: { type: \"boolean\", description: \"Each person answers once: after a press their app offers the buttons no more\" },\n id: { type: \"string\", description: \"The question's id (default: made up, ask-…)\" },\n};\n/** The group's entry link lets anyone join: printed only when asked for. */\nexport const showSecret: Record<string, OptionSpec> = { \"show-secret\": { type: \"boolean\", description: \"Print the group's entry link (anyone who has it can join)\" } };\n/** A pending chat's invite code lets whoever reads it take the chat: printed only when asked for. */\nexport const showInvite: Record<string, OptionSpec> = { \"show-secret\": { type: \"boolean\", description: \"Print a pending chat's invite code (whoever has it can take the chat)\" } };\nexport const secret = (options: Parsed[\"options\"]) => (options[\"show-secret\"] === true ? { showSecret: true } : {});\n\n/**\n * `--kind` of the typing commands: another word is a usage error (exit 2) before the profile opens, not the API's\n * \"kind must be one of\" (exit 1). The words are core's TYPING_KINDS, written out: the package is not loaded here.\n */\nexport const typingKind: OptionSpec = { type: \"string\", choices: [\"typing\", \"recording\", \"thinking\"], description: \"typing (default), recording (a voice note) or thinking\" };\n\n/**\n * `--for` of the typing commands: the seconds it is kept on, 1 to 600, and never with `--stop`. A usage error (exit 2)\n * that names the flag: before, the API's own check answered (\"for must be a number from 1 to 600\", exit 1).\n */\nexport function typingFor(options: Parsed[\"options\"]): number | undefined {\n const seconds = options.for;\n if (seconds === undefined) return undefined;\n if (typeof seconds !== \"number\" || !(seconds >= 1 && seconds <= 600)) throw new CliError(\"usage\", `--for takes a number of seconds from 1 to 600, not ${JSON.stringify(seconds)}`);\n if (options.stop === true) throw new CliError(\"usage\", \"--for keeps it on: not with --stop\");\n return seconds;\n}\n\n/**\n * The `<emoji>` of `react` and `group react`: one emoji (core's `reactionEmoji`), or none with `--remove`. Anything else\n * is a usage error (exit 2) before the profile opens, as `status set --emoji` is. Before, a one-shot opened the profile\n * and went online first, then the engine answered \"A reaction is one emoji\" (`bad_request`, exit 1), and a missing one\n * \"Give one emoji\" (exit 2) only from there. The API keeps its checks for socket callers.\n */\nexport function reaction(options: Parsed[\"options\"], emoji: string | undefined): string | undefined {\n if (options.remove === true) return emoji;\n if (!emoji) throw new CliError(\"usage\", \"Give one emoji, or --remove to take yours back\");\n if (!reactionEmoji(emoji)) throw new CliError(\"usage\", `<emoji> takes one emoji, not ${JSON.stringify(emoji)}`);\n return emoji;\n}\n\n/**\n * The ranges the API takes (api.ts, files.ts): the most minutes of a `--hold` (a week, HOLD_MAX_MINUTES), seconds;\n * `chat connect`'s, the chat link's own wait for a contact (CONNECT_MAX_SECONDS).\n */\nexport const HOLD_MINUTES = 10_080, WAIT_SECONDS = 3600, LONG_WAIT_SECONDS = 86_400, HISTORY_LIMIT = 10_000, CONNECT_SECONDS = 90;\n\n/**\n * A number flag out of the range the API takes: a usage error (exit 2) that names the flag, before the profile opens.\n * Before, the API's own check answered once it had opened (a one-shot went online first), in its parameter's words\n * (\"hold must be a number from 0 to 10080\", exit 1). The API keeps its check for socket callers.\n */\nexport function inRange(options: Parsed[\"options\"], flag: string, what: string, min: number, max: number, whole = false): number | undefined {\n const value = options[flag];\n if (value === undefined) return undefined;\n if (typeof value !== \"number\" || !(value >= min && value <= max) || (whole && !Number.isInteger(value)))\n throw new CliError(\"usage\", `--${flag} takes ${what} from ${min} to ${max}, not ${JSON.stringify(value)}`);\n return value;\n}\n\n/** `--timeout` of a command that waits: seconds, up to an hour (a send, a card, a button) or a day (`chat wait`, a file). */\nexport const timeout = (options: Parsed[\"options\"], max = WAIT_SECONDS) => inRange(options, \"timeout\", \"a number of seconds\", 1, max);\n/** `--limit` of a history: messages per page. */\nexport const pageLimit = (options: Parsed[\"options\"]) => inRange(options, \"limit\", \"a whole number\", 1, HISTORY_LIMIT, true);\n\n/** `--since` of `events` and `listen`: a seq, a whole number from 0 (a negative one replayed a made-up gap first). */\nexport function since(options: Parsed[\"options\"]): number | undefined {\n const value = options.since;\n if (value !== undefined && !(Number.isSafeInteger(value) && (value as number) >= 0)) throw new CliError(\"usage\", `--since takes a seq from 0 up, not ${JSON.stringify(value)}`);\n return value as number | undefined;\n}\n\n/**\n * A time given as digits: milliseconds. Unix seconds (from 1e9, 2001, up to 1e11, which as milliseconds would be 1970\n * to 1973) are refused with the milliseconds they mean: before, they were read as January 1970 without a word.\n */\nfunction milliseconds(text: string, flag: string): number {\n const ms = Number(text);\n if (ms >= 1e9 && ms < 1e11) throw new CliError(\"usage\", `--${flag} takes milliseconds, not seconds: ${text}000`);\n return ms;\n}\n\n/**\n * A history cursor: a time when it is all digits (`0` is from the start), else a message id. Message ids are never all\n * digits (`me_…`, `peer_…`): before, fewer than 10 digits were read as an id (\"No message 0\").\n */\nexport function cursor(value: unknown, flag: string): string | number | undefined {\n if (value === undefined) return undefined;\n const text = String(value).trim();\n return /^\\d+$/.test(text) ? milliseconds(text, flag) : text;\n}\n\n/**\n * A status card's fields given as JSON (WISP 405 · Status Cards): inline (`{...}`), `-` for stdin, or a file's path. The\n * flags given beside it win over it.\n */\nexport function cardJson(value: unknown): Record<string, unknown> {\n if (value === undefined) return {};\n const text = String(value).trim();\n // A file's path as here() reads it (\"\" names no file, not the current folder); a file not there or a folder is said\n // with its path, as `x401 credential add` says it: before, Node's text, and a folder's named no path.\n const file = text.startsWith(\"{\") || text === \"-\" ? undefined : here(text)!;\n let raw: string;\n try { raw = text.startsWith(\"{\") ? text : readInput(file ?? 0); }\n catch (error) { throw (error instanceof CliError && error) || (file !== undefined && localFileError(error, file)) || new CliError(\"usage\", `--json takes a card as JSON, - for stdin, or a file: ${error instanceof Error ? error.message : String(error)}`); }\n let parsed: unknown;\n try { parsed = JSON.parse(raw); } catch { throw new CliError(\"usage\", \"--json is not valid JSON\"); }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new CliError(\"usage\", \"--json is a JSON object of the card's fields\");\n return parsed as Record<string, unknown>;\n}\n\n/** Options every status card command takes. */\nexport const cardOptions: Record<string, OptionSpec> = {\n json: { type: \"string\", description: \"The card's fields as JSON: inline, - for stdin, or a file (flags win over it)\" },\n link: { type: \"list\", description: \"A link on the card: https://… or label=https://… (up to 4)\" },\n text: { type: \"string\", description: \"The text older apps show instead (default: written from the card)\" },\n force: { type: \"boolean\", description: \"Send even if the card's text looks like a seed, a key or ecash\" },\n};\n\n/** `--link label=https://…` or a bare link, as a card's links. */\nexport function cardLinks(values: unknown): { url: string; label?: string }[] | undefined {\n if (!Array.isArray(values) || !values.length) return undefined;\n given(\"link\", values, STATUS_CARD_LIMITS.links);\n return (values as string[]).map((value) => {\n const eq = value.indexOf(\"=\");\n const link = eq > 0 && !value.slice(0, eq).includes(\":\") ? { label: value.slice(0, eq), url: value.slice(eq + 1) } : { url: value };\n if (!cardUrl(link.url)) throw new CliError(\"usage\", `--link takes an https link of at most ${STATUS_CARD_LIMITS.url} characters, or label=link, not ${JSON.stringify(value)}`);\n cardText(\"--link's label\", link.label, STATUS_CARD_LIMITS.linkLabel, value);\n return link;\n });\n}\n\nexport const listed = (words: readonly string[]) => `${words.slice(0, -1).join(\", \")} or ${words.at(-1)}`;\n\n/**\n * A text flag as the card counts it (one line, the display rules): blank, or longer than `max`, is a usage error (exit 2)\n * that names the flag. Before, it reached the card's own check and failed as `bad_request` (exit 1) in the card's words\n * (\"Status card: title is at most 120 characters\"), the whole card in its details. `shown` is what the flag was given.\n */\nfunction cardText(flag: string, value: unknown, max: number, shown = value): void {\n if (value === undefined) return;\n const line = cardLine(String(value), Infinity);\n if (!line) throw new CliError(\"usage\", `${flag} takes text, not ${JSON.stringify(shown)}`);\n const length = [...line].length;\n if (length > max) throw new CliError(\"usage\", `${flag} takes at most ${max} characters, not ${length}`);\n}\n\n/** `--status`, `--state`, `--pr-state`, `--pr-checks`: one of their words, or a usage error that lists them. */\nfunction oneWord(options: Parsed[\"options\"], flag: string, words: readonly string[]): void {\n if (options[flag] !== undefined && !words.includes(options[flag] as string)) throw new CliError(\"usage\", `--${flag} takes ${listed(words)}, not ${JSON.stringify(options[flag])}`);\n}\n\n/** A flag given more times than the card holds: a usage error that says how many it takes. */\nfunction given(flag: string, values: unknown, max: number): void {\n if (Array.isArray(values) && values.length > max) throw new CliError(\"usage\", `--${flag} is given at most ${max} times, not ${values.length}`);\n}\n\n/**\n * `--item state:text` as a task's item. The word before the first colon is the state when it is one lowercase word (and\n * the colon does not start `://`): one of `ITEM_STATES`, or a usage error that lists them, so `queued:Publishing` is\n * refused rather than shown as that text. Anything else (`Step 2: build`, `Note: x`, a link, no colon) is the whole\n * text, pending; `pending:fix: tests` keeps a colon after a lowercase word.\n */\nexport function itemOf(value: string): { state: string; text: string } {\n const colon = value.indexOf(\":\");\n const word = colon > 0 ? value.slice(0, colon) : \"\";\n if (!/^[a-z]+$/.test(word) || value.startsWith(\"//\", colon + 1)) {\n cardText(\"--item's text\", value, STATUS_CARD_LIMITS.line);\n return { state: \"pending\", text: value };\n }\n if (!(ITEM_STATES as readonly string[]).includes(word))\n throw new CliError(\"usage\", `--item takes state:text, and ${JSON.stringify(word)} is not a state: use ${listed(ITEM_STATES)} (pending:<text> keeps a colon in the text), not ${JSON.stringify(value)}`);\n const text = value.slice(colon + 1).trim();\n cardText(\"--item's text\", text, STATUS_CARD_LIMITS.line, value);\n return { state: word, text };\n}\n\n/**\n * A card's fields past the bytes a card takes in all (`STATUS_CARD_LIMITS.bytes`, its JSON as UTF-8): a usage error\n * (exit 2) with its size and what to cut. Every flag can be within its own bound and the card not: 20 items of 200\n * characters past Latin (3 bytes each) take 12 KiB. Before, it failed as `bad_request` (exit 1), the whole card in it.\n */\nfunction cardBytes(fields: Record<string, unknown>, flags: string): Record<string, unknown> {\n const bytes = statusCardBytes(fields);\n if (bytes > STATUS_CARD_LIMITS.bytes)\n throw new CliError(\"usage\", `The card takes ${bytes} bytes, and holds at most ${STATUS_CARD_LIMITS.bytes} in all (a character past Latin takes 2 to 4): give shorter or fewer ${flags}`);\n return fields;\n}\n\n/**\n * A card's `--id` given as \"\" (an unset variable in a script: `--id \"$ID\"`) is a usage error. Taken as not given, a new\n * id was made, and a script meant to update its card posted a second one.\n */\nfunction cardId(options: Parsed[\"options\"]): void {\n if (options.id === \"\") throw new CliError(\"usage\", \"--id needs a card id\");\n}\n\n/** `--progress`, `--left`: a percent, or a usage error that names the flag. */\nfunction percent(options: Parsed[\"options\"], flag: string): void {\n const value = options[flag];\n if (value !== undefined && !(typeof value === \"number\" && value >= 0 && value <= 100)) throw new CliError(\"usage\", `--${flag} takes a percent from 0 to 100, not ${JSON.stringify(value)}`);\n}\n\n/**\n * `--pr-number`, `--additions`, `--used`, `--limit`…: a count as the card takes it, a whole number from `min` up to\n * `STATUS_CARD_LIMITS.count`. Before, it reached the card's check: `bad_request` (exit 1), \"Status card: pr.number is a\n * whole number from 1\".\n */\nconst cardCount = (options: Parsed[\"options\"], flag: string, min: number) => inRange(options, flag, \"a whole number\", min, STATUS_CARD_LIMITS.count, true);\n\n/** The flags of a task's pull request, and the field of `pr` each one gives. */\nconst PR_FLAGS = [[\"pr-url\", \"url\"], [\"pr-number\", \"number\"], [\"additions\", \"additions\"], [\"deletions\", \"deletions\"], [\"files\", \"files\"], [\"pr-state\", \"state\"], [\"pr-checks\", \"checks\"]] as const;\n\n/**\n * A task's fields from its flags; what was not given is left out, so an update changes only what it names. What a flag\n * got wrong is a usage error (exit 2) that names the flag: before, it reached the card's own check and failed as\n * `bad_request` (exit 1) in the card's words (\"Status card: done is at most total\").\n */\nexport function taskFields(options: Parsed[\"options\"]): Record<string, unknown> {\n const fields: Record<string, unknown> = { ...cardJson(options.json) };\n const set = (key: string, value: unknown) => { if (value !== undefined) fields[key] = value; };\n cardText(\"--title\", options.title, STATUS_CARD_LIMITS.title);\n cardText(\"--step\", options.step, STATUS_CARD_LIMITS.line);\n cardText(\"--branch\", options.branch, STATUS_CARD_LIMITS.branch);\n for (const [flag, words] of [[\"status\", TASK_STATUSES], [\"pr-state\", PR_STATES], [\"pr-checks\", PR_CHECKS]] as const) oneWord(options, flag, words);\n cardId(options);\n set(\"id\", options.id);\n set(\"title\", options.title);\n set(\"status\", options.status);\n percent(options, \"progress\");\n if (options.progress !== undefined && options.steps !== undefined) throw new CliError(\"usage\", \"--progress or --steps, not both\");\n set(\"progress\", options.progress);\n set(\"step\", options.step);\n set(\"branch\", options.branch);\n if (options.steps !== undefined) {\n const match = /^(\\d+)\\s*\\/\\s*(\\d+)$/.exec(String(options.steps));\n if (!match) throw new CliError(\"usage\", `--steps takes done/total, like 2/5, not ${JSON.stringify(options.steps)}`);\n fields.done = Number(match[1]); fields.total = Number(match[2]);\n if (Number(match[2]) > STATUS_CARD_LIMITS.count) throw new CliError(\"usage\", `--steps takes done/total of at most ${STATUS_CARD_LIMITS.count} steps, like 2/5, not ${JSON.stringify(options.steps)}`);\n if (Number(match[2]) < 1 || Number(match[1]) > Number(match[2])) throw new CliError(\"usage\", `--steps takes done/total with done at most total, like 2/5, not ${JSON.stringify(options.steps)}`);\n }\n if (options[\"pr-url\"] !== undefined && !cardUrl(options[\"pr-url\"])) throw new CliError(\"usage\", `--pr-url takes an https link of at most ${STATUS_CARD_LIMITS.url} characters, not ${JSON.stringify(options[\"pr-url\"])}`);\n for (const flag of [\"pr-number\", \"additions\", \"deletions\", \"files\"]) cardCount(options, flag, flag === \"pr-number\" ? 1 : 0);\n const pr: Record<string, unknown> = {};\n for (const [flag, key] of PR_FLAGS) if (options[flag] !== undefined) pr[key] = options[flag];\n if (Object.keys(pr).length) fields.pr = { ...(fields.pr && typeof fields.pr === \"object\" ? fields.pr as object : {}), ...pr };\n given(\"item\", options.item, STATUS_CARD_LIMITS.items);\n if (Array.isArray(options.item) && options.item.length) fields.items = (options.item as string[]).map(itemOf);\n given(\"tag\", options.tag, STATUS_CARD_LIMITS.tags);\n if (Array.isArray(options.tag) && options.tag.length) {\n const seen = new Set<string>();\n for (const tag of options.tag as string[]) {\n cardText(\"--tag\", tag, STATUS_CARD_LIMITS.tag);\n const clean = cardLine(tag, Infinity)!;\n if (seen.has(clean)) throw new CliError(\"usage\", `--tag ${JSON.stringify(clean)} is given twice`);\n seen.add(clean);\n }\n fields.tags = options.tag as string[];\n }\n set(\"parent\", options.parent);\n const links = cardLinks(options.link);\n if (links) fields.links = links;\n return cardBytes(fields, \"--item, --step, --link or --json\");\n}\n\n/**\n * The fields a new card cannot go without, given as a flag or in `--json`: a usage error (exit 2) that names the\n * flags. Before, a missing `--title` reached the card's own check and failed as `bad_request` (exit 1) with\n * \"Status card: title is text\".\n */\nexport function needs(card: Record<string, unknown>, fields: readonly (readonly [key: string, flag: string])[], usage: string): Record<string, unknown> {\n const missing = fields.filter(([key]) => typeof card[key] !== \"string\" || !(card[key] as string).trim()).map(([, flag]) => `--${flag}`);\n if (missing.length) throw new CliError(\"usage\", `${missing.join(\" and \")} ${missing.length > 1 ? \"are\" : \"is\"} needed: ghostly ${usage}`);\n return card;\n}\n\n/**\n * A new task's pull request goes by its link: `--pr-state` and the like without `--pr-url` (or `pr.url` in `--json`)\n * are a usage error that names them. An update's card may have the link already, so only a send asks.\n */\nexport function prLinked(card: Record<string, unknown>, options: Parsed[\"options\"], usage: string): Record<string, unknown> {\n const given = PR_FLAGS.filter(([flag]) => options[flag] !== undefined).map(([flag]) => `--${flag}`);\n if (!given.length || (card.pr as { url?: unknown }).url !== undefined) return card;\n throw new CliError(\"usage\", `${given.join(\" and \")} ${given.length > 1 ? \"go\" : \"goes\"} with --pr-url: ghostly ${usage}`);\n}\n\n/**\n * A usage card says how much is left: `--left`, or `--used` with `--limit`, as flags or in `--json`. The one that is\n * missing is a usage error that names the flag.\n */\nexport function quota(card: Record<string, unknown>, usage: string): Record<string, unknown> {\n const used = card.used !== undefined, limit = card.limit !== undefined;\n if (used !== limit) throw new CliError(\"usage\", `--${used ? \"used\" : \"limit\"} goes with --${used ? \"limit\" : \"used\"}: ghostly ${usage}`);\n if (card.left === undefined && !used) throw new CliError(\"usage\", `--left is needed (or --used with --limit): ghostly ${usage}`);\n return card;\n}\n\n/** How the time flags say the dates they take (`--next`, `--resets`, `--also`'s `@`). */\nexport const 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\";\n\n/** An ISO date with no time, which `Date.parse` alone reads as UTC midnight: `2026-09-30`, `2026-09`. */\nconst ISO_DAY = /^(?:[+-]\\d{6}|\\d{4})-\\d{2}(-\\d{2})?$/;\n\nconst MONTHS = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"];\n/** What `Date.parse` takes between a month's name and a number: `Apr 31`, `Apr-31`, `31/Apr`, `Apr.31`, `31 Apr,`. */\nconst NAME_SEP = \"[\\\\s,./-]*\";\n/** What `Date.parse` takes between two numbers of a date: `2026-4-31`, `2026/4/31`, `2026.4.31`, `2026, 4, 31`. */\nconst NUMBER_SEP = \"[\\\\s,./-]+\";\nconst MONTH_DAY = new RegExp(`\\\\b(${MONTHS.join(\"|\")})[a-z]*${NAME_SEP}(\\\\d{1,2})(?!\\\\d)`, \"i\");\nconst DAY_MONTH = new RegExp(`(?<!\\\\d)(\\\\d{1,2})${NAME_SEP}(${MONTHS.join(\"|\")})`, \"i\");\n\n/**\n * The year, month (1 to 12) and day a date is written with: `2026-04-31`, `2026/4/31`, `2026.4.31`, `4/31/2026`\n * (month first, as `Date.parse` reads it, also with a two-digit year), `Apr 31 2026`, `31-Apr-2026`. Between the numbers\n * `Date.parse` takes dashes, slashes, dots, commas and spaces alike (`2026 4 31`), so these do too. `Date.parse` takes\n * any day up to 31 and moves it past the month's end, so the day is checked here.\n */\nfunction writtenDay(text: string): [number, number, number] | undefined {\n const numeric = new RegExp(`^([+-]\\\\d{6}|\\\\d{4})${NUMBER_SEP}(\\\\d{1,2})${NUMBER_SEP}(\\\\d{1,2})(?!\\\\d)`).exec(text);\n if (numeric) return [Number(numeric[1]), Number(numeric[2]), Number(numeric[3])];\n const monthFirst = new RegExp(`^(\\\\d{1,2})${NUMBER_SEP}(\\\\d{1,2})${NUMBER_SEP}(\\\\d{4}|\\\\d{2})(?!\\\\d)`).exec(text);\n // A two-digit year is 1950 to 2049, as `Date.parse` takes it.\n const yy = (y: string) => (y.length === 2 ? Number(y) + (Number(y) < 50 ? 2000 : 1900) : Number(y));\n if (monthFirst) return [yy(monthFirst[3]!), Number(monthFirst[1]), Number(monthFirst[2])];\n const year = /\\b(\\d{4})\\b/.exec(text), monthDay = MONTH_DAY.exec(text), dayMonth = monthDay ? null : DAY_MONTH.exec(text);\n const [word, day] = monthDay ? [monthDay[1]!, monthDay[2]!] : dayMonth ? [dayMonth[2]!, dayMonth[1]!] : [];\n return year && word ? [Number(year[1]), MONTHS.indexOf(word.toLowerCase()) + 1, Number(day)] : undefined;\n}\n\n/**\n * A time a command names: milliseconds, or a date the JavaScript Date reads (`2026-09-30T01:00:00Z`). A date with no\n * 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\n * alone as UTC midnight (21:00 the day before in UTC-03, agents#2355), so that one is read as `2026-09-30T00:00`.\n * A day the month does not have (`2026-04-31`) is refused, where `Date.parse` made it May 1. A time more than a year\n * ahead is a usage error that names the flag and the last time it takes: before, it reached the card's check and failed\n * as `bad_request` (exit 1), \"Status card: resetsAt is a time in milliseconds, within a year\". A time past is taken.\n * `forms` is what a time it cannot read is told to be, for a flag that takes more (`status set --until 2h`).\n */\nexport function cardTime(value: unknown, flag: string, forms = `a time in milliseconds or a date: ${CARD_TIME_FORMS}`): number | undefined {\n if (value === undefined) return undefined;\n const text = String(value).trim();\n const day = ISO_DAY.exec(text);\n const ms = /^\\d+$/.test(text) ? milliseconds(text, flag) : Date.parse(day ? `${text}${day[1] ? \"\" : \"-01\"}T00:00` : text);\n if (!Number.isSafeInteger(ms) || ms <= 0) throw new CliError(\"usage\", `--${flag} takes ${forms}, not ${JSON.stringify(value)}`);\n const written = writtenDay(text);\n if (written) {\n const [year, month, date] = written, days = new Date(Date.UTC(year, month, 0)).getUTCDate();\n if (date > days) throw new CliError(\"usage\", `--${flag} takes a day the month has (${year}-${String(month).padStart(2, \"0\")} has ${days}), not ${JSON.stringify(value)}`);\n }\n const last = new Date(Date.now() + STATUS_CARD_LIMITS.nextRunMs);\n if (ms > last.getTime()) {\n const two = (n: number) => String(n).padStart(2, \"0\");\n const shown = `${last.getFullYear()}-${two(last.getMonth() + 1)}-${two(last.getDate())} ${two(last.getHours())}:${two(last.getMinutes())}`;\n throw new CliError(\"usage\", `--${flag} takes a time within a year from now (until ${shown}), not ${JSON.stringify(value)}`);\n }\n return ms;\n}\n\n/** `--run ok`, `--run failed:\"CI flaked\"`: a run of a routine, recorded as its last. */\nexport function runOf(value: unknown): { result: string; summary?: string } | undefined {\n if (value === undefined) return undefined;\n const text = String(value), colon = text.indexOf(\":\");\n const result = colon === -1 ? text : text.slice(0, colon), summary = colon === -1 ? \"\" : text.slice(colon + 1).trim();\n if (!(RUN_RESULTS as readonly string[]).includes(result)) throw new CliError(\"usage\", `--run takes ok, failed or skipped, and :a summary after it if you like, not ${JSON.stringify(value)}`);\n if (summary) cardText(\"--run's summary\", summary, STATUS_CARD_LIMITS.line);\n return { result, ...(summary && { summary }) };\n}\n\n/** A routine's fields from its flags; what was not given is left out. */\nexport function routineFields(options: Parsed[\"options\"]): Record<string, unknown> {\n const fields: Record<string, unknown> = { ...cardJson(options.json) };\n cardText(\"--name\", options.name, STATUS_CARD_LIMITS.title);\n cardText(\"--schedule\", options.schedule, STATUS_CARD_LIMITS.schedule);\n if (options.cron !== undefined && !CRON_LINE.test(String(options.cron).trim())) {\n const length = [...String(options.cron).trim()].length;\n throw new CliError(\"usage\", length > STATUS_CARD_LIMITS.cron ? `--cron takes at most ${STATUS_CARD_LIMITS.cron} characters, not ${length}`\n : `--cron takes a cron line of 0-9 A-Z a-z * , / ? # - and spaces, not ${JSON.stringify(options.cron)}`);\n }\n oneWord(options, \"state\", ROUTINE_STATES);\n cardId(options);\n for (const key of [\"id\", \"name\", \"schedule\", \"cron\", \"state\"] as const) if (options[key] !== undefined) fields[key] = options[key];\n const next = cardTime(options.next, \"next\");\n if (next !== undefined) fields.nextRunAt = next;\n const links = cardLinks(options.link);\n if (links) fields.links = links;\n return cardBytes(fields, \"--name, --schedule, --link or --json\");\n}\n\n/** Options a routine command takes, beside `cardOptions`. */\nexport const routineOptions: Record<string, OptionSpec> = {\n name: { type: \"string\", description: \"What the routine is (120 characters)\" },\n schedule: { type: \"string\", description: \"When it runs, as people say it: \\\"every day 01:00\\\" (80 characters)\" },\n cron: { type: \"string\", description: \"Its cron line, shown beside the schedule (never run)\" },\n state: { type: \"string\", description: \"active (default on send) or paused\" },\n next: { type: \"string\", description: `Its next run, within a year: milliseconds or a date: ${CARD_TIME_FORMS}` },\n run: { type: \"string\", description: \"Record a run now: ok, failed or skipped, with :a summary if you like (it becomes the last run)\" },\n ...cardOptions,\n};\n\n/** Options a task command takes, beside `cardOptions`. */\nexport const taskOptions: Record<string, OptionSpec> = {\n title: { type: \"string\", description: \"What the task is (120 characters)\" },\n status: { type: \"string\", description: \"queued, running (default on send), blocked, done, failed or cancelled\" },\n progress: { type: \"number\", description: \"Percent done, 0 to 100\" },\n steps: { type: \"string\", description: \"Steps done of total, like 2/5 (progress is worked out from them)\" },\n step: { type: \"string\", description: \"What it is doing now (200 characters)\" },\n item: { type: \"list\", description: \"A step or log line, state:text with state pending, running, done, failed or skipped (text alone: pending). A lowercase word before the first colon must be one of them; pending:fix: x keeps the colon. The list replaces the card's (up to 20; the card holds at most 8 KiB in all, and a character past Latin takes 2 to 4 bytes)\" },\n branch: { type: \"string\", description: \"The branch it works on\" },\n \"pr-url\": { type: \"string\", description: \"The pull request's https link\" },\n \"pr-number\": { type: \"number\", description: \"The pull request's number\" },\n additions: { type: \"number\", description: \"Lines the pull request adds\" },\n deletions: { type: \"number\", description: \"Lines the pull request removes\" },\n files: { type: \"number\", description: \"Files the pull request changes\" },\n \"pr-state\": { type: \"string\", description: \"Where the pull request stands: draft, open (ready for review), merged or closed\" },\n \"pr-checks\": { type: \"string\", description: \"The pull request's checks: passing, failing or pending\" },\n tag: { type: \"list\", description: \"A short label, like an area or a repository (24 characters); up to 3. An update's tags replace the card's: give all of them\" },\n parent: { type: \"string\", description: \"The id of the task of yours in this chat that this one is a part of\" },\n ...cardOptions,\n};\n\n/**\n * `--also week=80` or `--also week=80@2026-10-10T00:00:00Z`: another window of a usage card, its percent left and, after\n * `@`, when it resets.\n */\nexport function usageWindowOf(value: string): { window: string; left: number; resetsAt?: number } {\n const match = /^([^=]+)=(\\d+(?:\\.\\d+)?)(?:@(.+))?$/.exec(value.trim());\n if (!match) throw new CliError(\"usage\", `--also takes window=percent or window=percent@time, like week=80@2026-10-10T00:00:00Z, not ${JSON.stringify(value)}`);\n cardText(\"--also's window\", match[1], STATUS_CARD_LIMITS.usageWindow, value);\n if (Number(match[2]) > 100) throw new CliError(\"usage\", `--also takes a percent from 0 to 100, not ${match[2]}`);\n const resetsAt = cardTime(match[3], \"also\");\n return { window: match[1].trim(), left: Number(match[2]), ...(resetsAt !== undefined && { resetsAt }) };\n}\n\n/** A usage card's fields from its flags (WISP 405 § Usage); `--json` gives any of them, the flags win over it. */\nexport function usageFields(options: Parsed[\"options\"]): Record<string, unknown> {\n const fields: Record<string, unknown> = { ...cardJson(options.json) };\n percent(options, \"left\");\n if (options.left !== undefined && (options.used !== undefined || options.limit !== undefined)) throw new CliError(\"usage\", \"--left or --used with --limit, not both\");\n const used = cardCount(options, \"used\", 0), limit = cardCount(options, \"limit\", 1);\n if (used !== undefined && limit !== undefined && used > limit) throw new CliError(\"usage\", `--used takes at most --limit (${limit}), not ${used}`);\n for (const [flag, max] of [[\"label\", STATUS_CARD_LIMITS.usageLabel], [\"account\", STATUS_CARD_LIMITS.usageLabel], [\"window\", STATUS_CARD_LIMITS.usageWindow]] as const) cardText(`--${flag}`, options[flag], max);\n given(\"also\", options.also, STATUS_CARD_LIMITS.usageWindows);\n cardId(options);\n for (const key of [\"id\", \"left\", \"used\", \"limit\", \"label\", \"account\", \"window\"] as const) if (options[key] !== undefined) fields[key] = options[key];\n const resets = cardTime(options.resets, \"resets\");\n if (resets !== undefined) fields.resetsAt = resets;\n if (Array.isArray(options.also) && options.also.length) fields.windows = (options.also as string[]).map(usageWindowOf);\n return cardBytes(fields, \"--json\");\n}\n\n/** Options `usage send` takes. */\nexport const usageOptions: Record<string, OptionSpec> = {\n left: { type: \"number\", description: \"Percent of the quota left, 0 to 100\" },\n used: { type: \"number\", description: \"How much is used, with --limit (instead of --left; the percent is worked out)\" },\n limit: { type: \"number\", description: \"The quota, with --used\" },\n label: { type: \"string\", description: \"What the quota is of, like Claude (24 characters)\" },\n account: { type: \"string\", description: \"Which of your accounts it is, short (24 characters)\" },\n window: { type: \"string\", description: \"The quota's window, as people say it: \\\"5 h\\\", \\\"week\\\" (16 characters)\" },\n resets: { type: \"string\", description: `When the window starts again, within a year: milliseconds or a date: ${CARD_TIME_FORMS}` },\n also: { type: \"list\", 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)\" },\n id: { type: \"string\", description: \"The card's id (default usage: one card per chat)\" },\n all: { type: \"boolean\", description: \"Every 1:1 chat with a contact, instead of one chat\" },\n json: cardOptions.json,\n text: cardOptions.text,\n force: cardOptions.force,\n};\n","import { CliError } from \"../errors\";\nimport { here, localStat, readInput, type Command } from \"./shared\";\n\n/** The key file a command signs with: always named, never a default, never on the command line itself. */\nfunction keyFile(value: unknown, usage: string): string {\n if (typeof value !== \"string\" || !value) throw new CliError(\"usage\", `--key <file> is needed: ghostly ${usage}`);\n return value;\n}\n\n/**\n * `app serve`'s bundle file, in the API's words (apps.ts) when it is not there or a folder: said before the profile\n * opens. Before, a one-shot went online first (about 12 s with no daemon) to say the file was not there.\n */\nfunction bundleFile(path: string): string {\n if (localStat(path).isDirectory()) throw new CliError(\"bad_request\", `${path} is a folder: name a .ghostlyapp file`);\n return path;\n}\n\n/** `app send`'s message: JSON on the command line, or `-` for stdin. */\nfunction appData(value: string | undefined): unknown {\n if (value === undefined) throw new CliError(\"usage\", \"The message is needed, as JSON or - for stdin: ghostly app send <chat> <ref|name> <json|->\");\n const text = value.trim() === \"-\" ? readInput(0) : value;\n try { return JSON.parse(text) as unknown; } catch { throw new CliError(\"usage\", \"The message is not valid JSON: quote it for the shell, like '{\\\"k\\\":\\\"move\\\"}', or pass - and write it on stdin\"); }\n}\n\nconst key = { type: \"string\", description: \"The key file (made, owner-only, when it is missing)\" } as const;\n\n/**\n * The publisher tools of WISP 1200 (Apps · Publishing): they run here, on files, with no profile or daemon. And the\n * apps a profile serves as a bot (`app serve`, `app served`, `app unserve`), which are the profile's. One entry per\n * command, in alphabetical order (test/commands.test.ts checks).\n */\nexport const commands: Record<string, Command> = {\n \"app close\": {\n method: \"app.close\", usage: \"app close <chat> <ref|name>\",\n summary: \"Close a served app in a chat: the contact's app hears it ended\",\n args: [\"chat\", \"ref\"],\n params: (_, a) => ({ chat: a.chat, ref: a.ref }),\n },\n \"app init\": {\n method: \"app.init\", usage: \"app init <dir> [--name <name>] [--title <title>] [--force]\",\n summary: \"Start an app (WISP 1200): a small working one in <dir>, its ghostly-app.json, an index.html that says hello to the contact and a README, ready for app publish\",\n args: [\"dir\"],\n options: {\n name: { type: \"string\", description: \"The app's name, lowercase letters, digits and hyphens (default: the folder's)\" },\n title: { type: \"string\", description: \"The title people see, up to 40 characters (default: from the name)\" },\n force: { type: \"boolean\", description: \"Replace the three files when they are there\" },\n },\n run: async ({ options }, a) => (await import(\"../apps\")).initApp(a.dir!, { name: options.name as string | undefined, title: options.title as string | undefined, force: options.force === true }),\n },\n \"app open\": {\n method: \"app.open\", usage: \"app open <chat> <ref|name> [--no-card]\",\n summary: \"Open a served app in a chat, as a bot (needs the daemon): the contact gets the app's card, unless their app is open there already, and the two sides can talk once both opened it\",\n args: [\"chat\", \"ref\"],\n options: { \"no-card\": { type: \"boolean\", description: \"Send no app card, only say the app is open\" } },\n params: ({ options }, a) => ({ chat: a.chat, ref: a.ref, noCard: options[\"no-card\"] === true }),\n },\n \"app publish\": {\n method: \"app.publish\", usage: \"app publish <dir> --key <file> [--out <file>] [--sequence n]\",\n summary: \"Bundle and sign an app (WISP 1200): <dir>/ghostly-app.json and every other file in <dir> become one .ghostlyapp, its sequence one more than the bundle at --out (default <dir>/app.ghostlyapp)\",\n args: [\"dir\"],\n options: {\n key: { ...key, description: \"The publisher key file (made, owner-only, on first use; back it up)\" },\n out: { type: \"string\", description: \"Where the bundle goes (default <dir>/app.ghostlyapp); the bundle there is the version this one follows\" },\n sequence: { type: \"number\", description: \"This version's sequence, higher than the bundle at --out's (default: one more than it)\" },\n },\n run: async ({ options }, a) => (await import(\"../apps\")).publishApp(a.dir!, keyFile(options.key, \"app publish <dir> --key <file> [--out <file>] [--sequence n]\"), here(options.out), options.sequence as number | undefined),\n },\n \"app revoke\": {\n method: \"app.revoke\", usage: \"app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]\",\n summary: \"Revoke versions of your app (WISP 1200 · Revocation): a ghostly-revoke/1 statement signed with its publisher key, added to <dir>/ghostly-revoke.json\",\n args: [\"dir\"],\n options: {\n key: { type: \"string\", description: \"The app's publisher key file (never made here)\" },\n digest: { type: \"list\", description: \"A version's digest, base64url as app verify prints it (again for each, up to 64)\" },\n \"up-to\": { type: \"number\", description: \"Every version with this sequence or a lower one\" },\n reason: { type: \"string\", description: \"Why, one line of up to 200 characters, shown to people\" },\n bundle: { type: \"string\", description: \"The bundle naming the app (default <dir>/app.ghostlyapp)\" },\n force: { type: \"boolean\", description: \"Allow --up-to past the bundle's own sequence (versions published from elsewhere), and a --reason that looks like a seed, a key or ecash\" },\n },\n run: async ({ options }, a) => (await import(\"../apps\")).revokeApp(a.dir!, keyFile(options.key, \"app revoke <dir> --key <file> (--digest <digest>... | --up-to <sequence>) [--reason <text>] [--bundle <file>] [--force]\"), {\n digests: options.digest as string[] | undefined, upTo: options[\"up-to\"] as number | undefined,\n reason: options.reason as string | undefined, bundle: here(options.bundle), force: options.force === true,\n }),\n },\n \"app send\": {\n method: \"app.send\", usage: \"app send <chat> <ref|name> <json|->\",\n summary: \"Send one message of a served app's own protocol to the contact's app (needs the daemon, and both sides open): any JSON value up to 32 KiB, or - to read it from stdin; live only, never kept for later\",\n args: [\"chat\", \"ref\", \"data...\"],\n params: (_, a) => ({ chat: a.chat, ref: a.ref, data: appData(a.data) }),\n },\n \"app serve\": {\n method: \"app.serve\", usage: \"app serve <bundle|url> --grant chat [--grant name] [--url <url>]\",\n summary: \"Serve an app as a bot (WISP 1200): its signed .ghostlyapp is checked as a client would, and the profile speaks the app's messages in chats itself; each permission the app asks needs its --grant\",\n args: [\"bundle\"],\n options: {\n grant: { type: \"list\", description: \"A permission the app asks and you allow: chat (talk to the contact's app) or name (your name in that chat); again for each\" },\n url: { type: \"string\", description: \"Where a contact's app reads the bundle, for the card (raw.githubusercontent.com, or cdn.jsdelivr.net at a commit; default: the first of those it was served from or its manifest names)\" },\n },\n params: ({ options }, a) => ({ bundle: /^[a-z][a-z0-9+.-]*:\\/\\//i.test(a.bundle ?? \"\") ? a.bundle : bundleFile(here(a.bundle)!), grant: options.grant, url: options.url }),\n },\n \"app served\": {\n method: \"app.served\", usage: \"app served\",\n summary: \"The apps this profile serves as a bot, and whether apps/1 is offered to contacts now\",\n },\n \"app unserve\": {\n method: \"app.unserve\", usage: \"app unserve <ref|name>\",\n summary: \"Stop serving an app, by its reference or its name\",\n args: [\"ref\"],\n params: (_, a) => ({ ref: a.ref }),\n },\n \"app verify\": {\n method: \"app.verify\", usage: \"app verify <bundle|url>\",\n 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 (for a URL, or beside one of its sources) revokes this version\",\n args: [\"bundle\"],\n run: async (_, a) => (await import(\"../apps\")).verifyApp(a.bundle!),\n },\n \"store sign\": {\n method: \"store.sign\", usage: \"store sign <index> --key <file> [--out <dir>]\",\n summary: \"Sign a store index (WISP 1200 · Stores): writes ghostly-store.json, canonical, and ghostly-store.sig beside it or in --out\",\n args: [\"index\"],\n options: {\n key: { ...key, description: \"The store key file (made, owner-only, when it is missing, the index names no key and no signed index is in the output folder; keep it offline)\" },\n out: { type: \"string\", description: \"The folder to write ghostly-store.json and ghostly-store.sig in (default: the index's)\" },\n },\n run: async ({ options }, a) => (await import(\"../apps\")).signStore(a.index!, keyFile(options.key, \"store sign <index> --key <file> [--out <dir>]\"), here(options.out)),\n },\n};\n","import type { Parsed } from \"../args\";\nimport { CALL_RATES, isCallRate } from \"../calls/pcm\";\nimport { CliError } from \"../errors\";\nimport { type Command, rate, refs } from \"./shared\";\n\n/**\n * `--rate`: one of the rates a call takes, or a usage error (exit 2) that names the flag before the profile opens.\n * Before, the API's own check answered it (\"rate must be …\", exit 1), and `call answer` only once a call rang.\n */\nfunction rateOf(options: Parsed[\"options\"]): number | undefined {\n const value = options.rate;\n if (value !== undefined && !isCallRate(value)) throw new CliError(\"usage\", `--rate takes ${CALL_RATES.slice(0, -1).join(\", \")} or ${CALL_RATES.at(-1)}, not ${JSON.stringify(value)}`);\n return value;\n}\n\n/** Voice calls: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"call answer\": {\n method: \"call.answer\", usage: \"call answer [<chat|call>] [--rate 48000]\", summary: \"Answer a call that rings (the only one, or the one named)\",\n args: [\"call...?\"], options: { rate: rate }, params: ({ options }, a) => ({ call: a.call, rate: rateOf(options) }),\n },\n \"call auto\": {\n method: \"call.auto\", usage: \"call auto [on|off] [--from <chat>]... [--rate 48000]\", summary: \"Answer calls by themselves: from anyone, or the chats named (kept in the profile)\",\n args: [\"mode...?\"], options: { from: { type: \"list\", description: \"Only calls from this chat: its id, its contact's key or a label given here with chat rename (again for more)\" }, rate: rate },\n params: ({ options }, a) => {\n if (a.mode !== undefined && 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]`);\n // Without `on` the chats and the rate would be dropped without a word.\n if (a.mode !== \"on\" && (options.from !== undefined || options.rate !== undefined)) throw new CliError(\"usage\", \"--from and --rate go with on: ghostly call auto on --from <chat>\");\n refs(options.from, \"from\", \"chat\");\n if (a.mode === undefined) return {};\n return a.mode === \"on\" ? { on: true, from: options.from, rate: rateOf(options) } : { on: false };\n },\n },\n \"call flush\": { method: \"call.flush\", usage: \"call flush [<chat|call>]\", summary: \"Drop the audio queued and not played yet (barge-in)\", args: [\"call...?\"], params: (_, a) => ({ call: a.call }) },\n \"call hangup\": { method: \"call.hangup\", usage: \"call hangup [<chat|call>]\", summary: \"Hang up, or decline a call that rings\", args: [\"call...?\"], params: (_, a) => ({ call: a.call }) },\n \"call list\": { method: \"call.list\", usage: \"call list\", summary: \"Calls on now, their audio sockets, and auto-answer\" },\n \"call start\": {\n method: \"call.start\", usage: \"call start <chat> [--rate 48000]\", summary: \"Call a contact (voice); the result names the call's audio socket (daemon)\",\n args: [\"chat\"], options: { rate: rate }, params: ({ options }, a) => ({ chat: a.chat, rate: rateOf(options) }),\n },\n};\n","import { CliError } from \"../errors\";\nimport type { OptionSpec } from \"../args\";\nimport { TRANSPORT_NAMES } from \"../words\";\nimport { type Command, CONNECT_SECONDS, force, groupWait, cursor, HOLD_MINUTES, inRange, LONG_WAIT_SECONDS, needs, pageLimit, prLinked, quota, reaction, refs, routineFields, routineOptions, runOf, secret, showInvite, taskFields, taskOptions, timeout, translate, typingFor, typingKind, usageFields, usageOptions, wait } from \"./shared\";\n\n/** `react` and `pin` in a 1:1 chat: until the contact confirmed it, by default without a daemon (the process leaves). */\nconst confirmWait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"confirmed\"], description: \"none or confirmed: until the contact confirmed it, in a 1:1 chat (default: none with a daemon, confirmed without)\" },\n timeout: groupWait.timeout,\n};\n/** The card commands: in a chat a one-shot stays until the card went out, as `send` (a group has no receipts). */\nconst ONE_SHOT_DEFAULT = (word: string) => `(default: none with a daemon; without one, ${word} in a chat and none in a group)`;\nconst cardWait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"sent\", \"delivered\"], description: `none, sent or delivered; in a group none or sent: until an edge took it ${ONE_SHOT_DEFAULT(\"sent\")}` },\n timeout: groupWait.timeout,\n};\nconst cardUpdateWait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"confirmed\", \"sent\"], description: `none, confirmed (a chat's contact took it) or sent (a group's edge took it) ${ONE_SHOT_DEFAULT(\"confirmed\")}` },\n timeout: groupWait.timeout,\n};\nconst usageWait: Record<string, OptionSpec> = {\n wait: { type: \"string\", choices: [\"none\", \"sent\"], description: `none or sent: until the contact has it in a chat, an edge took it in a group ${ONE_SHOT_DEFAULT(\"sent\")}` },\n timeout: groupWait.timeout,\n};\nconst BUTTON_UPDATE = \"button update <chat|group> <message> [--chosen <button>] [--close] [--text <text>] [--force] [--wait none|confirmed|sent] [--timeout s]\";\n\n/** Invites, chats and messages: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"button press\": {\n method: \"button.press\", usage: \"button press <chat|group> <message> <button> [--wait none|sent|delivered] [--timeout s]\",\n summary: \"Press a button of someone else's message, as a tap in the app does (its id from the message's card)\",\n args: [\"chat\", \"message\", \"button\"],\n options: {\n wait: { type: \"string\", choices: [\"none\", \"sent\", \"delivered\"], description: \"none, sent (a one-shot's default in a chat) or delivered; a group takes none or sent\" },\n timeout: groupWait.timeout,\n },\n params: ({ options }, a) => ({ chat: a.chat, message: a.message, button: a.button, wait: options.wait, timeout: timeout(options) }),\n },\n \"button update\": {\n method: \"button.update\", usage: BUTTON_UPDATE,\n summary: \"Show the answer on a message's buttons (--chosen), close them, or change its text (the messageId send --button gave)\",\n args: [\"chat\", \"message\"],\n options: {\n chosen: { type: \"string\", description: \"The button to show as the answer (its id)\" },\n close: { type: \"boolean\", description: \"Close the buttons: no more presses\" },\n text: { type: \"string\", description: \"A new text for the message (default: the one it has); people see it marked edited\" },\n force,\n wait: { type: \"string\", choices: [\"none\", \"confirmed\", \"sent\"], description: \"none (default), confirmed (a chat's contact took it) or sent (a group's edge took it)\" },\n timeout: groupWait.timeout,\n },\n params: ({ options }, a) => {\n // Empty (an unset variable in a script), --close closed the buttons with no answer shown: a button not there is exit 3.\n if (options.chosen === \"\") throw new CliError(\"usage\", \"--chosen needs a button id\");\n if (!options.chosen && options.close !== true && !options.text) throw new CliError(\"usage\", `Give --chosen, --close or --text: ghostly ${BUTTON_UPDATE}`);\n return { chat: a.chat, message: a.message, chosen: options.chosen, close: options.close === true, text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) };\n },\n },\n \"chat connect\": {\n method: \"chat.connect\", usage: \"chat connect <chat> [--timeout s]\", summary: \"Reconnect a chat now (ends a --hold)\", args: [\"chat\"],\n options: { timeout: { type: \"number\", description: `Seconds to wait for the contact (default and at most ${CONNECT_SECONDS})` } },\n params: ({ options }, { chat }) => ({ chat, timeout: timeout(options, CONNECT_SECONDS) }),\n },\n \"chat disconnect\": {\n method: \"chat.disconnect\", usage: \"chat disconnect <chat> [--hold <minutes>]\", summary: \"Close a chat's live session (the contact may redial; --hold keeps it on the DHT that long, 0 ends it)\", args: [\"chat\"],\n options: { hold: { type: \"number\", description: \"Stay off the direct link this many minutes (up to 10080): DHT only, taken back after\" } },\n params: ({ options }, { chat }) => ({ chat, hold: inRange(options, \"hold\", \"a number of minutes\", 0, HOLD_MINUTES) }),\n },\n \"chat history\": {\n method: \"chat.history\", usage: \"chat history <chat> [--limit n] [--before id|ms] [--after id|ms] [--translate lang]\", summary: \"Messages, oldest first (a page)\",\n args: [\"chat\"],\n options: { limit: { type: \"number\", description: \"Messages per page (default 50)\" }, before: { type: \"string\", description: \"Only before this message id or timestamp\" }, after: { type: \"string\", description: \"Only after this message id or timestamp\" }, translate },\n params: ({ options }, { chat }) => ({ chat, limit: pageLimit(options), before: cursor(options.before, \"before\"), after: cursor(options.after, \"after\") }),\n },\n \"chat list\": { method: \"chat.list\", usage: \"chat list [--show-secret]\", summary: \"Chats, newest first (a pending invite code only with --show-secret)\", options: showInvite, params: ({ options }) => secret(options) },\n \"chat remove\": {\n method: \"chat.remove\", usage: \"chat remove <chat> --yes [--force]\", summary: \"Delete a chat, its keys and history on this device; refused while a message you deleted for everyone has not reached the contact, unless --force\", args: [\"chat\"],\n options: { yes: { type: \"boolean\", description: \"Confirm\" }, force: { type: \"boolean\", description: \"Remove it even if a message you deleted for everyone has not reached the contact yet\" } },\n params: ({ options }, { chat }) => ({ chat, yes: options.yes === true, force: options.force === true }),\n },\n \"chat rename\": { method: \"chat.rename\", usage: \"chat rename <chat> [name...]\", summary: \"Name a chat on this side (empty: the contact's name)\", args: [\"chat\", \"name...?\"], params: (_, { chat, name }) => ({ chat, name: name ?? \"\" }) },\n \"chat show\": { method: \"chat.get\", usage: \"chat show <chat> [--show-secret]\", summary: \"One chat and its connection (its pending invite code only with --show-secret)\", args: [\"chat\"], options: showInvite, params: ({ options }, { chat }) => ({ chat, ...secret(options) }) },\n \"chat transport\": { method: \"chat.transport\", usage: \"chat transport <chat> <auto|dht|webrtc|iroh|hyperdht>\", summary: \"Choose what carries a chat\", args: [\"chat\", \"transport\"], words: { transport: Object.keys(TRANSPORT_NAMES) }, params: (_, a) => ({ chat: a.chat, transport: a.transport }) },\n \"chat verify\": {\n method: \"chat.verify\", usage: \"chat verify <chat> --code <code>\", summary: \"Mark a contact verified after comparing codes\", args: [\"chat\"],\n options: { code: { type: \"string\", description: \"The code the contact reads out\" } }, params: ({ options }, { chat }) => {\n if (typeof options.code !== \"string\" || !options.code.trim()) throw new CliError(\"usage\", \"--code is needed: ghostly chat verify <chat> --code <code>\");\n return { chat, code: options.code };\n },\n },\n \"chat wait\": {\n method: \"chat.wait\", usage: \"chat wait <chat> [--until live|text|paired] [--timeout s]\", summary: \"Wait for a chat to reach a state\", args: [\"chat\"],\n options: { until: { type: \"string\", choices: [\"live\", \"text\", \"paired\"], description: \"live (default), text or paired\" }, timeout: { type: \"number\", description: \"Seconds (default 60)\" } },\n params: ({ options }, { chat }) => ({ chat, until: options.until, timeout: timeout(options, LONG_WAIT_SECONDS) }),\n },\n \"forward\": {\n method: \"chat.forward\", usage: \"forward <chat|group> <message>... --to <chat|group>... [--force] [--wait none|sent] [--timeout s]\",\n summary: \"Forward messages (texts, files from the bytes here) to up to 5 chats and groups, as new messages of yours\",\n args: [\"chat\", \"message...\"],\n options: {\n to: { type: \"list\", description: \"A chat or a group to forward to (id, prefix or name; group:<id> for a group; a dash-leading id as it is); up to 5\" },\n force: { type: \"boolean\", description: \"Forward even if a text looks like a seed, a key or ecash\" },\n wait: { type: \"string\", choices: [\"none\", \"sent\"], description: \"none or sent: each text on its way (in a group, taken by an edge), each file's transfer done (default none; without a daemon a group's waits for an edge)\" },\n timeout: groupWait.timeout,\n },\n params: ({ options }, a) => {\n if (!Array.isArray(options.to) || !options.to.length) throw new CliError(\"usage\", \"Missing --to: ghostly forward <chat|group> <message>... --to <chat|group>... [--force] [--wait none|sent] [--timeout s]\");\n refs(options.to, \"to\", \"chat or group\");\n return { chat: a.chat, messages: (a.message ?? \"\").split(\" \").filter(Boolean), to: options.to, force: options.force === true, wait: options.wait, timeout: timeout(options) };\n },\n },\n \"invite create\": {\n method: \"invite.create\", usage: \"invite create [--label <name>]\", summary: \"A new chat's ghostly1 invite and its link\",\n options: { label: { type: \"string\", description: \"A name for the chat on this side\" } },\n params: ({ options }) => ({ label: options.label }),\n },\n \"invite join\": {\n method: \"invite.join\", usage: \"invite join [<invite-or-link> | -] [--label <name>]\", summary: \"Join a chat from its invite; stdin keeps it out of ps (without a daemon it waits up to 60 s for the inviter)\",\n args: [\"invite?\"], options: { label: { type: \"string\", description: \"A name for the chat on this side\" } },\n params: ({ options }, { invite }) => ({ invite, label: options.label }),\n },\n \"message delete\": {\n method: \"chat.delete\", usage: \"message delete <chat|group> <message> [--everyone [--wait none|confirmed|sent] [--timeout s]] [--purge]\",\n summary: \"Forget a message on this device (the contact keeps theirs; a waiting text of yours is cancelled, or deleted for everyone if a relay may have it); --everyone deletes one of yours, in a chat or a group, from every member's device\",\n args: [\"chat\", \"message\"],\n options: {\n everyone: { type: \"boolean\", description: \"Delete a message of yours for everyone (a chat or a group)\" },\n wait: { type: \"string\", choices: [\"none\", \"confirmed\", \"sent\"], description: \"With --everyone: in a chat none or confirmed, until the contact has it; in a group none or sent, until a member's edge took it (default: none with a daemon, confirmed or sent without)\" },\n timeout: wait.timeout,\n purge: { type: \"boolean\", description: \"Take what it said out of the profile's folder now (the store folds at once), not within the hour: for a secret pasted into a chat\" },\n },\n params: ({ options }, a) => {\n for (const flag of [\"wait\", \"timeout\"]) if (options[flag] !== undefined && options.everyone !== true) throw new CliError(\"usage\", `--${flag} goes with --everyone`);\n return { chat: a.chat, message: a.message, everyone: options.everyone === true, wait: options.wait, timeout: timeout(options), ...(options.purge === true && { purge: true }) };\n },\n },\n \"message details\": { method: \"chat.details\", usage: \"message details <chat|group> <message>\", summary: \"How a message travelled\", args: [\"chat\", \"message\"], params: (_, a) => ({ chat: a.chat, message: a.message }) },\n \"message retry\": { method: \"chat.retry\", usage: \"message retry <chat> <message>\", summary: \"Send a failed message again\", args: [\"chat\", \"message\"], params: (_, a) => ({ chat: a.chat, message: a.message }) },\n \"pin\": {\n method: \"chat.pin\", usage: \"pin <chat|group> <message> | --remove [--wait none|confirmed|sent] [--timeout s]\", summary: \"Pin a message at the top of a chat or group (one per chat: it replaces the pinned one); --remove unpins\",\n args: [\"chat\", \"message...?\"],\n options: {\n remove: { type: \"boolean\", description: \"Unpin the chat's pinned message (it names no message)\" },\n wait: { type: \"string\", choices: [\"none\", \"confirmed\", \"sent\"], description: \"In a 1:1 chat none or confirmed, until the contact confirmed it; in a group none or sent, until a member's edge took it (default: none with a daemon, confirmed or sent without)\" },\n timeout: groupWait.timeout,\n },\n params: ({ options }, a) => {\n // --remove names no message: the chat has one pin. One given beside it is taken as before, and not read. One given\n // as \"\" (an unset variable in a script) is missing too, as for `react`: before, a one-shot went online to refuse it.\n if (!a.message && options.remove !== true) throw new CliError(\"usage\", \"Missing <message>: ghostly pin <chat|group> <message> | --remove\");\n if (a.message?.includes(\" \")) throw new CliError(\"usage\", \"Too many arguments: ghostly pin <chat|group> <message> | --remove\");\n return { chat: a.chat, message: a.message, remove: options.remove === true, wait: options.wait, timeout: timeout(options) };\n },\n },\n \"react\": {\n method: \"chat.react\", usage: \"react <chat> <message> <emoji> [--remove] [--wait none|confirmed] [--timeout s]\", summary: \"React to a message with one emoji (it replaces yours); --remove takes yours back\",\n args: [\"chat\", \"message\", \"emoji...?\"], options: { remove: { type: \"boolean\", description: \"Take your reaction back\" }, ...confirmWait },\n params: ({ options }, a) => ({ chat: a.chat, message: a.message, emoji: reaction(options, a.emoji), remove: options.remove === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"routine send\": {\n method: \"routine.send\", usage: \"routine send <chat|group> --name <name> --schedule \\\"every day 01:00\\\" [--cron \\\"0 1 * * *\\\"] [--state active|paused] [--next <time>] [--run ok|failed|skipped[:summary]] [--link url]... [--id id] [--text <text>] [--json json|-|file] [--force] [--wait none|sent|delivered] [--timeout s]\",\n summary: \"Send a routine card (something a bot runs on a schedule: its last run and the next) to a chat or group\",\n args: [\"chat\"],\n options: { id: { type: \"string\", description: \"The routine's id, kept across updates (default: made up)\" }, ...routineOptions, ...cardWait },\n params: ({ options }, { chat }) => ({ chat, card: needs(routineFields(options), [[\"name\", \"name\"], [\"schedule\", \"schedule\"]], \"routine send <chat|group> --name <name> --schedule \\\"every day 01:00\\\"\"), run: runOf(options.run), text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"routine update\": {\n method: \"routine.update\", usage: \"routine update <chat|group> <routine> [--run ok|failed|skipped[:summary]] [--next <time>] [--state active|paused] [--name <name>] [--schedule ...] [--cron ...] [--link url]... [--text <text>] [--json json|-|file] [--force] [--wait none|confirmed|sent] [--timeout s]\",\n summary: \"Update a routine card you sent: record a run, the next one, a pause (at most one update per 2.5 s; sooner ones merge)\",\n args: [\"chat\", \"routine\"],\n options: { ...routineOptions, ...cardUpdateWait },\n params: ({ options }, a) => ({ chat: a.chat, routine: a.routine, card: routineFields(options), run: runOf(options.run), text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"saved add\": { method: \"saved.add\", usage: \"saved add <chat|group> <message>\", summary: \"Save a message on this device, to find it again in `saved list` (nothing is sent)\", args: [\"chat\", \"message\"], params: (_, a) => ({ chat: a.chat, message: a.message }) },\n \"saved list\": { method: \"saved.list\", usage: \"saved list\", summary: \"Saved messages of every chat and group, the last saved first\" },\n \"saved remove\": { method: \"saved.remove\", usage: \"saved remove <chat|group> <message>\", summary: \"Unsave a message\", args: [\"chat\", \"message\"], params: (_, a) => ({ chat: a.chat, message: a.message }) },\n \"task send\": {\n method: \"task.send\", usage: \"task send <chat|group> --title <title> [--status s] [--progress n | --steps a/b] [--step \\\"...\\\"] [--item state:text]... [--pr-url url --pr-number n --additions n --deletions n --files n --pr-state s --pr-checks c] [--branch b] [--tag label]... [--parent task] [--link url]... [--id id] [--text <text>] [--json json|-|file] [--force] [--wait none|sent|delivered] [--timeout s]\",\n summary: \"Send a task card (a bot's work: status, progress, its PR) to a chat or group; prints its id and message\",\n args: [\"chat\"],\n options: { id: { type: \"string\", description: \"The task's id, kept across updates (default: made up)\" }, ...taskOptions, ...cardWait },\n params: ({ options }, { chat }) => ({ chat, card: prLinked(needs(taskFields(options), [[\"title\", \"title\"]], \"task send <chat|group> --title <title>\"), options, \"task send <chat|group> --title <title> --pr-url <url>\"), text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"task update\": {\n method: \"task.update\", usage: \"task update <chat|group> <task> [--title <title>] [--status s] [--progress n | --steps a/b] [--step \\\"...\\\"] [--item state:text]... [--pr-url url] [--pr-number n] [--additions n] [--deletions n] [--files n] [--pr-state s] [--pr-checks c] [--branch b] [--tag label]... [--parent task] [--link url]... [--text <text>] [--json json|-|file] [--force] [--wait none|confirmed|sent] [--timeout s]\",\n summary: \"Update a task card you sent: the fields given, merged over it (at most one update per 2.5 s; sooner ones merge)\",\n args: [\"chat\", \"task\"],\n options: { ...taskOptions, ...cardUpdateWait },\n params: ({ options }, a) => ({ chat: a.chat, task: a.task, card: taskFields(options), text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"typing\": {\n method: \"chat.typing\", usage: \"typing <chat> [--kind typing|recording|thinking] [--status \\\"<text>\\\"] [--for s] [--stop]\",\n summary: \"Show the contact you are writing, recording or thinking (live chats; it fades after 6 s unless said again, or kept with --for; a send or --stop ends it)\", args: [\"chat\"],\n options: {\n stop: { type: \"boolean\", description: \"Say you stopped\" },\n kind: typingKind,\n status: { type: \"string\", description: \"A short line shown instead, e.g. \\\"Transcribing your audio…\\\" (40 characters, no links)\" },\n for: { type: \"number\", description: \"Keep saying it for this many seconds (up to 600), until a send or --stop\" },\n },\n params: ({ options }, { chat }) => ({ chat, stop: options.stop === true, kind: options.kind, status: options.status, for: typingFor(options) }),\n },\n \"usage send\": {\n method: \"usage.send\", usage: \"usage send [<chat|group>] [--all] --left <percent> [--window \\\"5 h\\\"] [--resets <time>] [--label Claude] [--account <name>] [--also week=80@<time>]... [--used n --limit n] [--id id] [--text <text>] [--json json|-|file] [--force] [--wait none|sent] [--timeout s]\",\n summary: \"Say how much of your quota is left (a bot's usage card, one per chat, updated in place); --all for every 1:1 chat\",\n args: [\"chat?\"],\n options: { ...usageOptions, ...usageWait },\n params: ({ options }, { chat }) => {\n if (!chat && options.all !== true) throw new CliError(\"usage\", \"Name a chat or group, or give --all: ghostly usage send <chat|--all> --left <percent>\");\n 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>\");\n return { chat, all: options.all === true, card: quota(usageFields(options), \"usage send <chat|--all> --left <percent>\"), text: options.text, force: options.force === true, wait: options.wait, timeout: timeout(options) };\n },\n },\n};\n","import { sep } from \"node:path\";\nimport { GROUP_FILE_LIMITS } from \"@ghostly/core/groupFiles\";\nimport { VOICE_LIMITS } from \"@ghostly/core/voice\";\nimport type { Parsed } from \"../args\";\nimport { CliError } from \"../errors\";\nimport { type Command, here, localStat, LONG_WAIT_SECONDS, reply, timeout } from \"./shared\";\n\n/**\n * `--voice [ms]` and `--peaks`: a length and a waveform a voice note takes, or a usage error (exit 2) that names the flag\n * before the profile opens. Before, the API answered them once it had opened (\"voice must be a number from 1 to\n * 9007199254740991\", or one sentence for every case), and `--peaks` without `--voice` was dropped without a word.\n */\nfunction voiceOf(options: Parsed[\"options\"]): { voice?: number | true; peaks?: string[] } {\n const { voice, peaks } = options;\n if (typeof voice === \"number\" && !(Number.isInteger(voice) && voice >= 1 && voice <= VOICE_LIMITS.maxDurationMs)) {\n throw new CliError(\"usage\", `--voice takes a length in milliseconds from 1 to ${VOICE_LIMITS.maxDurationMs} (${VOICE_LIMITS.maxDurationMs / 60_000} minutes), not ${voice}`);\n }\n if (typeof peaks !== \"string\") return { voice: voice as number | true | undefined, peaks: undefined };\n if (voice === undefined) throw new CliError(\"usage\", \"--peaks is a voice note's waveform: not without --voice\");\n const bars = peaks.split(\",\");\n if (bars.length > VOICE_LIMITS.maxBars || !bars.every((bar) => /^\\d{1,3}$/.test(bar.trim()) && Number(bar) <= 255)) {\n throw new CliError(\"usage\", `--peaks takes up to ${VOICE_LIMITS.maxBars} numbers from 0 to 255, comma-separated, not ${JSON.stringify(peaks)}`);\n }\n return { voice: voice as number | true, peaks: bars };\n}\n\n/** The file `file send` sends, in the API's words (files.ts) when it is not there or not a file. */\nfunction sendable(path: string): string {\n if (!localStat(path, `No file ${path}`).isFile()) throw new CliError(\"bad_request\", `${path} is not a file`);\n return path;\n}\n\n/** Files: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"file accept\": { method: \"file.action\", usage: \"file accept [<chat>] <file>\", summary: \"Take a file the contact offers, or download a group's file that did not come by itself (<chat> may be the group)\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"accept\" }) },\n \"file cancel\": { method: \"file.action\", usage: \"file cancel [<chat>] <file>\", summary: \"Cancel a transfer\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"cancel\" }) },\n \"file decline\": { method: \"file.action\", usage: \"file decline [<chat>] <file>\", summary: \"Refuse a file the contact offers\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"decline\" }) },\n \"file list\": { method: \"file.list\", usage: \"file list <chat|group>\", summary: \"A chat's or a group's files and their transfers\", args: [\"chat\"], params: (_, { chat }) => ({ chat }) },\n \"file pause\": { method: \"file.action\", usage: \"file pause [<chat>] <file>\", summary: \"Pause a transfer\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"pause\" }) },\n \"file request\": { method: \"file.action\", usage: \"file request [<chat>] <file>\", summary: \"Ask again for a file that stopped arriving: it goes on from what is here (a group's file: asked of whoever holds it)\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"request\" }) },\n \"file resend\": { method: \"file.action\", usage: \"file resend [<chat>] <file>\", summary: \"Send again a file that stopped moving or failed: it goes on from what the contact holds\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"resend\" }) },\n \"file resume\": { method: \"file.action\", usage: \"file resume [<chat>] <file>\", summary: \"Resume a transfer\", args: [\"chat?\", \"file\"], params: (_, a) => ({ chat: a.chat, file: a.file, action: \"resume\" }) },\n \"file save\": {\n method: \"file.save\", usage: \"file save [<chat>] <file> [--dir d | --path p] [--force] [--wait [--timeout s]]\", summary: \"Write a received file to disk (never over a file without --force; --wait: once it is all here)\",\n args: [\"chat?\", \"file\"],\n options: {\n dir: { type: \"string\", description: \"Into this folder, under its own name (a voice message: the name Ghostly makes for it, \\\"(2)\\\" when taken)\" }, path: { type: \"string\", description: \"To this path\" }, force: { type: \"boolean\", description: \"Replace a file there\" },\n wait: { type: \"boolean\", description: \"Wait for the transfer to finish first\" }, timeout: { type: \"number\", description: \"Seconds --wait waits (default 300)\" },\n },\n params: ({ options }, a) => {\n // Empty (an unset variable in a script), it was the current folder: --path \"\" asked to replace it.\n if (options.path === \"\") throw new CliError(\"usage\", \"--path needs a file\");\n if (options.dir === \"\") throw new CliError(\"usage\", \"--dir needs a folder\");\n if (options.dir !== undefined && options.path !== undefined) throw new CliError(\"usage\", \"--path names the file: not with --dir\");\n if (options.timeout !== undefined && options.wait !== true) throw new CliError(\"usage\", \"--timeout is how long --wait waits: not without --wait\");\n // A separator at its end names a folder: kept for the daemon to refuse, as resolving the path drops it.\n const path = here(options.path), folder = typeof options.path === \"string\" && (options.path.endsWith(\"/\") || options.path.endsWith(sep)) && !path!.endsWith(sep);\n return {\n chat: a.chat, file: a.file, dir: options.path === undefined ? here(options.dir ?? \".\") : undefined, path: folder ? `${path}${sep}` : path, force: options.force === true,\n wait: options.wait === true ? true : undefined, timeout: timeout(options, LONG_WAIT_SECONDS),\n };\n },\n },\n \"file send\": {\n method: \"file.send\", usage: \"file send <chat|group> <path> [--name n] [--mime t] [--voice [ms] [--peaks 0,40,…]] [--reply <message>] [--force] [--wait none|sent] [--timeout s]\", summary: `Send a file (or, with --voice, a voice note), as a reply with --reply; to a group, every member's app fetches it (up to ${GROUP_FILE_LIMITS.maxBytes / 1024 / 1024} MiB)`,\n args: [\"chat\", \"path\"],\n options: {\n name: { type: \"string\", description: \"The name the contact (or the group) sees\" }, mime: { type: \"string\", description: \"Its type (default: from the extension)\" }, voice: { type: \"number\", optionalValue: true, takes: \"a length in milliseconds\", description: \"A voice note; its length in milliseconds (default: measured from the sound)\" }, peaks: { type: \"string\", description: \"Loudness bars 0-255, comma-separated (default: measured from the sound)\" }, reply,\n wait: { type: \"string\", choices: [\"none\", \"sent\"], description: \"none or sent: until the contact has the whole file, in a 1:1 chat (default: none with a daemon, sent without; a group: none)\" },\n timeout: { type: \"number\", description: \"Seconds --wait sent waits (default 300)\" },\n force: { type: \"boolean\", description: \"Send even if --name looks like a seed, a key or ecash\" },\n },\n // The flags first: a usage error (exit 2) is said before the file is looked at.\n params: ({ options }, a) => {\n // Empty (an unset variable in a script), it sent the file as no reply: an id the chat lacks is exit 3.\n if (options.reply === \"\") throw new CliError(\"usage\", \"--reply needs a message id\");\n const voice = voiceOf(options), seconds = timeout(options, LONG_WAIT_SECONDS);\n return { chat: a.chat, path: sendable(here(a.path)!), name: options.name, mime: options.mime, ...voice, reply: options.reply, force: options.force === true, wait: options.wait, timeout: seconds };\n },\n },\n \"file wait\": {\n method: \"file.wait\", usage: \"file wait [<chat>] <file> [--timeout s]\", summary: \"Wait until a transfer is done (exit 0) or failed (exit 1, with its error); exit 4 on timeout, 5 at once when a received file waits for file accept\",\n args: [\"chat?\", \"file\"], options: { timeout: { type: \"number\", description: \"Seconds (default 300)\" } },\n params: ({ options }, a) => ({ chat: a.chat, file: a.file, timeout: timeout(options, LONG_WAIT_SECONDS) }),\n },\n};\n","import { STATUS_AVAILABILITIES } from \"@ghostly/core\";\nimport { STATUS_CARD_LIMITS } from \"@ghostly/core/statusCards\";\nimport { CliError } from \"../errors\";\nimport { checkOwnStatus } from \"../ownStatus\";\nimport { type Command, CARD_TIME_FORMS, cardTime, force, here, picture, since, translate } from \"./shared\";\n\n/** `--until 30m`, `2h`, `1d`: that long from now. */\nconst DURATION = /^(\\d+)(m|h|d)$/;\nconst UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000 } as const;\n\n/**\n * `status set --until`: a time to come, as long from now (30m, 2h, 1d) or as a card's time is written (milliseconds or a\n * date, local time when it names no zone), within a year. A time past is refused: the engine would take it as no status.\n * One it cannot read names the three forms, as its help does: `--until 2y` named only milliseconds and dates.\n */\nfunction statusUntil(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n const text = String(value).trim(), duration = DURATION.exec(text);\n const ms = duration ? Date.now() + Number(duration[1]) * UNIT_MS[duration[2] as keyof typeof UNIT_MS] : cardTime(text, \"until\", `30m, 2h or 1d from now (whole minutes, hours or days), milliseconds or a date: ${CARD_TIME_FORMS}`)!;\n if (duration && !(ms <= Date.now() + STATUS_CARD_LIMITS.nextRunMs)) throw new CliError(\"usage\", `--until takes a time within a year from now, not ${JSON.stringify(value)}`);\n if (ms <= Date.now()) throw new CliError(\"usage\", `--until takes a time to come, not ${JSON.stringify(value)}: a status that ended is none`);\n return ms;\n}\n\n/** The profile's status, its picture, the event journal: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"events\": {\n method: \"events.replay\", usage: \"events [--since seq] [--translate lang]\", summary: \"Events the journal holds, without following\",\n options: { since: { type: \"number\", description: \"Only events after this seq\" }, translate }, params: ({ options }) => ({ since: since(options) ?? 0 }),\n },\n \"profile picture\": {\n method: \"profile.picture\", usage: \"profile picture <jpeg> | --clear\", summary: \"The picture contacts see (a square JPEG, 128 px is what the app sends)\", args: [\"path...?\"],\n options: { clear: { type: \"boolean\", description: \"Remove the picture\" } },\n params: ({ options }, a) => {\n if (!a.path && options.clear !== true) throw new CliError(\"usage\", \"Missing <jpeg>: ghostly profile picture <jpeg> | --clear\");\n if (a.path && options.clear === true) throw new CliError(\"usage\", \"--clear removes the picture: not with a <jpeg>\");\n return { path: picture(here(a.path || undefined)), clear: options.clear === true };\n },\n },\n \"status\": { method: \"status\", usage: \"status\", summary: \"The profile, its chats and whether a daemon runs it\" },\n \"status clear\": { method: \"status.clear\", usage: \"status clear\", summary: \"Take back the status contacts see (status set)\" },\n \"status set\": {\n method: \"status.set\", usage: `status set [text...] [--emoji <emoji>] [--availability ${STATUS_AVAILABILITIES.join(\"|\")}] [--until <time>] [--force]`,\n summary: \"The status paired contacts see: a short text, one emoji, available, busy, away or dnd (Do not disturb), until a time; it replaces the one before\",\n args: [\"text...?\"],\n options: {\n emoji: { type: \"string\", description: \"One emoji, shown before the text\" },\n availability: { type: \"string\", choices: STATUS_AVAILABILITIES, description: \"available, busy, away or dnd (Do not disturb)\" },\n until: { type: \"string\", description: `When it ends by itself, within a year: 30m, 2h or 1d from now, or milliseconds or a date: ${CARD_TIME_FORMS}` },\n force: { ...force, description: \"Set a text that looks like a seed, a key or ecash\" },\n },\n // Checked here, before the profile opens, as the engine keeps it: a usage error that names the option.\n params: ({ options }, a) => {\n const input = { text: a.text, emoji: options.emoji as string | undefined, availability: options.availability as string | undefined, until: statusUntil(options.until) };\n const status = checkOwnStatus(input, (field) => (field === \"text\" ? \"<text>\" : `--${field}`), \"usage\");\n return { ...status, ...(options.force === true && { force: true }) };\n },\n },\n \"status show\": { method: \"status.get\", usage: \"status show\", summary: \"This profile's status (status set), or null when it has none\" },\n};\n","import { CliError } from \"../errors\";\nimport { type Command, groupWait, here, picture, refs, showSecret, secret, cursor, pageLimit, reaction, timeout, typingFor, typingKind } from \"./shared\";\n\nconst nameForce = { type: \"boolean\", description: \"Use the name even if it looks like a seed, a key or ecash\" } as const;\nconst forced = (options: Record<string, unknown>) => (options.force === true ? { force: true } : {});\n\n/** Groups: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"group accept\": { method: \"group.accept\", usage: \"group accept <group>\", summary: \"Accept an invitation to a group\", args: [\"group\"], params: (_, { group }) => ({ group }) },\n \"group admin\": {\n method: \"group.admin\", usage: \"group admin <group> <member> [--show-secret]\", summary: \"Make a member the admin (admin)\", args: [\"group\", \"member\"],\n options: showSecret, params: ({ options }, a) => ({ group: a.group, member: a.member, ...secret(options) }),\n },\n \"group auto\": {\n method: \"group.auto\", usage: \"group auto [on|off] [--from <chat>]...\", summary: \"Accept group invitations by themselves, only from the chats named (kept in the profile; the daemon accepts)\",\n args: [\"mode...?\"], options: { from: { type: \"list\", description: \"Invitations from this chat: its id, its contact's key or a label given here with chat rename (again for more: a new on replaces the list)\" } },\n params: ({ options }, a) => {\n if (a.mode !== undefined && a.mode !== \"on\" && a.mode !== \"off\") throw new CliError(\"usage\", `group auto takes on or off, not ${JSON.stringify(a.mode)}: ghostly group auto [on|off] [--from <chat>]...`);\n // Never from anyone: on names its chats. Without on, the chats would be dropped without a word.\n if (a.mode === \"on\" && options.from === undefined) throw new CliError(\"usage\", \"group auto on needs the chats whose invitations it accepts: ghostly group auto on --from <chat>\");\n if (a.mode !== \"on\" && options.from !== undefined) throw new CliError(\"usage\", \"--from goes with on: ghostly group auto on --from <chat>\");\n refs(options.from, \"from\", \"chat\");\n if (a.mode === undefined) return {};\n return a.mode === \"on\" ? { on: true, from: options.from } : { on: false };\n },\n },\n \"group call\": {\n method: \"group.call\", usage: \"group call <group> --sfu <https origin> [--e2ee | --no-e2ee] | --e2ee | --no-e2ee | --clear [--show-secret]\",\n summary: \"Name the node a community group's calls go through, turn sealed call media on or off, or --clear (admin)\", args: [\"group\"],\n options: {\n ...showSecret, sfu: { type: \"string\", description: \"The node's https origin, e.g. https://call.example.com\" },\n e2ee: { type: \"boolean\", eitherWay: true, description: \"Seal the call media end to end (--no-e2ee: off); left out, the group keeps what it had\" },\n clear: { type: \"boolean\", description: \"The group has no calls\" },\n },\n params: ({ options }, a) => {\n // Every form the usage line takes: before, only --sfu and --clear, though `--e2ee` alone seals the node set already.\n if (options.sfu === undefined && options.clear !== true && options.e2ee === undefined) throw new CliError(\"usage\", \"Missing --sfu, --e2ee, --no-e2ee or --clear: ghostly group call <group> --sfu <https origin> [--e2ee | --no-e2ee] | --e2ee | --no-e2ee | --clear\");\n if (options.sfu !== undefined && options.clear === true) throw new CliError(\"usage\", \"--clear removes the call node: not with --sfu\");\n if (options.e2ee !== undefined && options.clear === true) throw new CliError(\"usage\", \"--clear removes the call node: not with --e2ee or --no-e2ee\");\n return { group: a.group, ...(options.clear === true ? { clear: true } : options.sfu !== undefined ? { sfu: options.sfu } : {}), ...(options.e2ee !== undefined && { e2ee: options.e2ee === true }), ...secret(options) };\n },\n },\n \"group create\": {\n method: \"group.create\", usage: \"group create <name...> [--mesh] [--force]\", summary: \"A community (a link anyone can open) or, with --mesh, a private group of up to 32\",\n args: [\"name...\"], options: { mesh: { type: \"boolean\", description: \"A private mesh of contacts instead of a community\" }, force: nameForce },\n params: ({ options }, { name }) => ({ name, profile: options.mesh ? \"mesh\" : \"community\", ...forced(options) }),\n },\n \"group decline\": { method: \"group.decline\", usage: \"group decline <group>\", summary: \"Decline an invitation to a group\", args: [\"group\"], params: (_, { group }) => ({ group }) },\n \"group forget\": {\n method: \"group.forget\", usage: \"group forget <group> --yes\", summary: \"Leave and delete a group's history here\", args: [\"group\"],\n options: { yes: { type: \"boolean\", description: \"Confirm\" } }, params: ({ options }, { group }) => ({ group, yes: options.yes === true }),\n },\n \"group history\": {\n method: \"group.history\", usage: \"group history <group> [--limit n] [--before id|ms] [--after id|ms]\", summary: \"A group's messages (a page)\", args: [\"group\"],\n options: { limit: { type: \"number\", description: \"Messages per page (default 50)\" }, before: { type: \"string\", description: \"Only before this message id or timestamp\" }, after: { type: \"string\", description: \"Only after this message id or timestamp\" } },\n params: ({ options }, { group }) => ({ group, limit: pageLimit(options), before: cursor(options.before, \"before\"), after: cursor(options.after, \"after\") }),\n },\n \"group hub\": {\n method: \"group.hub\", usage: \"group hub <group> <member> [--pin | --exclude | --auto] [--show-secret]\",\n summary: \"Pin a member as a hub of a private group past 16 members, exclude one, or leave it to their app (admin)\", args: [\"group\", \"member\"],\n options: { ...showSecret, pin: { type: \"boolean\", description: \"Always a hub while online\" }, exclude: { type: \"boolean\", description: \"Never a hub\" }, auto: { type: \"boolean\", description: \"A hub if their app stays online (the default)\" } },\n params: ({ options }, a) => {\n const roles = ([\"pin\", \"exclude\", \"auto\"] as const).filter((role) => options[role] === true);\n if (roles.length > 1) throw new CliError(\"usage\", \"--pin, --exclude or --auto: one of them\");\n return { group: a.group, member: a.member, role: roles[0] ?? \"auto\", ...secret(options) };\n },\n },\n \"group invite\": {\n method: \"group.invite\", usage: \"group invite <group> <chat> [--show-secret]\", summary: \"Invite a contact into a group you administer\", args: [\"group\", \"chat\"],\n options: showSecret, params: ({ options }, a) => ({ group: a.group, chat: a.chat, ...secret(options) }),\n },\n \"group join\": { method: \"group.join\", usage: \"group join [<link> | -]\", summary: \"Join a group by its link; the link on stdin keeps it out of ps (without a daemon it waits up to 60 s to be let in)\", args: [\"link?\"], params: (_, { link }) => ({ link }) },\n \"group leave\": {\n method: \"group.leave\", usage: \"group leave <group> --yes\", summary: \"Leave a group; its history and files go from this device\", args: [\"group\"],\n options: { yes: { type: \"boolean\", description: \"Confirm\" } }, params: ({ options }, { group }) => ({ group, yes: options.yes === true }),\n },\n \"group link\": {\n method: \"group.link\", usage: \"group link <group> [--off] [--reset]\", summary: \"Turn the group's link on (--reset: a new one), or --off\", args: [\"group\"],\n options: { off: { type: \"boolean\", description: \"Turn the link off\" }, reset: { type: \"boolean\", description: \"Replace it: the old link stops working\" } },\n params: ({ options }, a) => {\n if (options.off === true && options.reset === true) throw new CliError(\"usage\", \"--off turns the link off: not with --reset\");\n return { group: a.group, on: options.off !== true, reset: options.reset === true };\n },\n },\n \"group list\": { method: \"group.list\", usage: \"group list [--show-secret]\", summary: \"Groups, invitations and auto-join\", options: showSecret, params: ({ options }) => secret(options) },\n \"group picture\": {\n method: \"group.picture\", usage: \"group picture <group> <jpeg> | --clear\", summary: \"Set or clear the group's picture (admin; a square JPEG)\", args: [\"group\", \"path...?\"],\n options: { clear: { type: \"boolean\", description: \"Remove the picture\" } },\n params: ({ options }, a) => {\n if (!a.path && options.clear !== true) throw new CliError(\"usage\", \"Missing <jpeg>: ghostly group picture <group> <jpeg> | --clear\");\n if (a.path && options.clear === true) throw new CliError(\"usage\", \"--clear removes the picture: not with a <jpeg>\");\n return { group: a.group, path: picture(here(a.path || undefined)), clear: options.clear === true };\n },\n },\n \"group react\": {\n method: \"group.react\", usage: \"group react <group> <message> <emoji> [--remove] [--wait none|sent] [--timeout s]\", summary: \"React to a group's message with one emoji; --remove takes yours back\",\n args: [\"group\", \"message\", \"emoji...?\"],\n options: {\n remove: { type: \"boolean\", description: \"Take your reaction back\" },\n wait: { ...groupWait.wait, description: \"none or sent: until an edge took it (default: none with a daemon, sent without)\" }, timeout: groupWait.timeout,\n },\n params: ({ options }, a) => ({ group: a.group, message: a.message, emoji: reaction(options, a.emoji), remove: options.remove === true, wait: options.wait, timeout: timeout(options) }),\n },\n \"group remove\": {\n method: \"group.remove\", usage: \"group remove <group> <member> [--show-secret]\", summary: \"Remove a member (admin)\", args: [\"group\", \"member\"],\n options: showSecret, params: ({ options }, a) => ({ group: a.group, member: a.member, ...secret(options) }),\n },\n \"group rename\": {\n method: \"group.rename\", usage: \"group rename <group> <name...> [--force] [--show-secret]\", summary: \"Rename the group (admin; the picture stays)\", args: [\"group\", \"name...\"],\n options: { ...showSecret, force: nameForce }, params: ({ options }, a) => ({ group: a.group, name: a.name, ...forced(options), ...secret(options) }),\n },\n \"group rotate\": {\n method: \"group.rotate\", usage: \"group rotate <group> [--show-secret]\", summary: \"A fresh group secret, members unchanged (admin)\", args: [\"group\"],\n options: showSecret, params: ({ options }, a) => ({ group: a.group, ...secret(options) }),\n },\n \"group show\": {\n method: \"group.get\", usage: \"group show <group> [--show-secret]\", summary: \"A group and its members (its entry link only with --show-secret)\", args: [\"group\"],\n options: showSecret, params: ({ options }, { group }) => ({ group, ...secret(options) }),\n },\n \"group typing\": {\n method: \"group.typing\", usage: \"group typing <group> [--kind typing|recording|thinking] [--status \\\"<text>\\\"] [--for s] [--stop]\",\n summary: \"Show the members you are writing, recording or thinking (private groups; it fades after 6 s unless said again, or kept with --for; a send or --stop ends it)\", args: [\"group\"],\n options: {\n stop: { type: \"boolean\", description: \"Say you stopped\" },\n kind: typingKind,\n status: { type: \"string\", description: \"A short line shown instead, e.g. \\\"Reading the thread…\\\" (40 characters, no links)\" },\n for: { type: \"number\", description: \"Keep saying it for this many seconds (up to 600), until a send or --stop\" },\n },\n params: ({ options }, { group }) => ({ group, stop: options.stop === true, kind: options.kind, status: options.status, for: typingFor(options) }),\n },\n};\n","import { CliError } from \"../errors\";\nimport { type Command, here, secret } from \"./shared\";\n\n/** Identity proofs and x401 credentials: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"identity cancel\": { method: \"identity.cancel\", usage: \"identity cancel <draft>\", summary: \"Drop a proof not finished\", args: [\"draft\"], params: (_, a) => ({ draft: a.draft }) },\n \"identity complete\": {\n method: \"identity.complete\", usage: \"identity complete <draft> [--evidence-file f | --stdin]\", summary: \"Finish a proof: what the tool printed, or nothing for a published record\",\n args: [\"draft\"], options: { \"evidence-file\": { type: \"string\", description: \"The tool's output, from this file (- for stdin)\" }, stdin: { type: \"boolean\", description: \"The tool's output, from stdin (piped to it without the flag is read too)\" } },\n params: ({ options }, a) => {\n if (options[\"evidence-file\"] !== undefined && options.stdin === true) throw new CliError(\"usage\", \"--evidence-file or --stdin, not both\");\n // `-` is stdin, as for every other file the CLI reads.\n const piped = options[\"evidence-file\"] === \"-\";\n return { draft: a.draft, evidenceFile: piped ? undefined : here(options[\"evidence-file\"]), stdin: piped || options.stdin === true };\n },\n },\n \"identity contact\": { method: \"identity.contact\", usage: \"identity contact <chat>\", summary: \"What a contact shared, as this device checked it\", args: [\"chat\"], params: (_, a) => ({ chat: a.chat }) },\n \"identity list\": { method: \"identity.list\", usage: \"identity list\", summary: \"This profile's identity proofs\" },\n \"identity providers\": { method: \"identity.providers\", usage: \"identity providers\", summary: \"Kinds of identity proof, and which signers work here\" },\n \"identity recheck\": { method: \"identity.recheck\", usage: \"identity recheck <chat> <id>\", summary: \"Check a contact's proof again\", args: [\"chat\", \"id\"], params: (_, a) => ({ chat: a.chat, id: a.id }) },\n \"identity remove\": { method: \"identity.remove\", usage: \"identity remove <id>\", summary: \"Remove a proof: withdrawn from every chat, revoked\", args: [\"id\"], params: (_, a) => ({ id: a.id }) },\n \"identity share\": { method: \"identity.share\", usage: \"identity share <chat> <id>\", summary: \"Show a proof to a contact\", args: [\"chat\", \"id\"], params: (_, a) => ({ chat: a.chat, id: a.id }) },\n \"identity withdraw\": { method: \"identity.withdraw\", usage: \"identity withdraw <chat> <id>\", summary: \"Withdraw a proof from a contact\", args: [\"chat\", \"id\"], params: (_, a) => ({ chat: a.chat, id: a.id }) },\n \"x401 credential add\": {\n method: \"x401.credential.add\", usage: \"x401 credential add <file|-> [--label <name>]\", summary: \"Keep an issued SD-JWT VC bound to a key from x401 key new (a file, or - for stdin)\",\n args: [\"path\"], options: { label: { type: \"string\", description: \"Your name for it, up to 80 characters on one line (default: its type)\" } },\n params: ({ options }, a) => ({ file: a.path === \"-\" ? \"-\" : here(a.path), label: options.label }),\n },\n \"x401 credential list\": {\n method: \"x401.credential.list\", usage: \"x401 credential list [--show-secret]\", summary: \"This profile's x401 credentials: issuer, type, claim paths\",\n options: { \"show-secret\": { type: \"boolean\", description: \"Print the claims' values too (a name, a document number...)\" } }, params: ({ options }) => secret(options),\n },\n \"x401 credential remove\": { method: \"x401.credential.remove\", usage: \"x401 credential remove <id>\", summary: \"Remove a credential and its holder key\", args: [\"id\"], params: (_, a) => ({ id: a.id }) },\n \"x401 key new\": { method: \"x401.key.new\", usage: \"x401 key new\", summary: \"A fresh P-256 holder key: its public JWK goes to the issuer (the 8 newest wait for a credential; past them, the oldest is dropped)\" },\n};\n","import { type Command, net, card, memo, confirmReal, force, sats, pageLimit, pairs } from \"./shared\";\nimport { ADDRESS_TYPES, CHAT_METHODS, PAY_METHODS, WALLET_TYPES } from \"../words\";\nimport { CliError } from \"../errors\";\n\n/**\n * `chat accept`'s --networks: mainnet and/or testnet, comma-separated; any other word, or none (an unset variable), is a\n * usage error before the profile opens, as a word --network does not take is. Before, the API refused it after a\n * one-shot had opened the profile: bad_request, exit 1.\n */\nfunction networkList(value: string): string[] {\n const networks = value.split(\",\").map((n) => n.trim()).filter(Boolean);\n if (!networks.length) throw new CliError(\"usage\", `--networks takes mainnet, testnet or mainnet,testnet (to stop taking it: --off), not ${JSON.stringify(value)}`);\n if (!networks.every((n) => n === \"mainnet\" || n === \"testnet\")) throw new CliError(\"usage\", `--networks takes mainnet, testnet or mainnet,testnet, not ${JSON.stringify(value)}`);\n return networks;\n}\n\n/**\n * `chat request`'s amount: whole sats, or with --method usdt USDT as the app's composer reads it (5 is 5 USDT, 0.25 a\n * quarter), passed on as its text for the API to turn into base units with the wallet's decimals.\n */\nfunction requestAmount(value: string | undefined, method: unknown): number | string {\n if (method !== \"usdt\") return sats(value);\n if (!/^\\d+(\\.\\d+)?$/.test(value ?? \"\") || !/[1-9]/.test(value!)) throw new CliError(\"usage\", `<amount> with --method usdt takes USDT above 0 (5 or 0.25), not ${JSON.stringify(value)}`);\n return value!;\n}\n\n/** Wallets and payments: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"chat accept\": {\n method: \"chat.accept\", usage: \"chat accept <chat> [<method> [--off] [--networks mainnet,testnet]]\", summary: \"Which ways of paying a chat takes (no method: the ones it takes now)\",\n args: [\"chat\", \"method?\"], words: { method: CHAT_METHODS }, options: { off: { type: \"boolean\", description: \"Stop taking it\" }, networks: { type: \"string\", description: \"Comma-separated networks it is taken on\" } },\n params: ({ options }, a) => {\n // Without a method it only answers what the chat takes: --off or --networks would be dropped without a word.\n if (a.method === undefined && (options.off !== undefined || options.networks !== undefined)) throw new CliError(\"usage\", \"--off and --networks change one method: ghostly chat accept <chat> <method> [--off] [--networks mainnet,testnet]\");\n if (a.method === undefined) return { chat: a.chat };\n return { chat: a.chat, method: a.method, on: options.off !== true, networks: typeof options.networks === \"string\" ? networkList(options.networks) : undefined };\n },\n },\n \"chat pay\": {\n method: \"chat.pay\", usage: \"chat pay <chat> <sats> [--memo t] [--network testnet] [--confirm-real] [--force]\", summary: \"Send ecash to a contact (Mainnet needs --confirm-real)\",\n args: [\"chat\", \"amount\"], options: { memo, network: net, \"confirm-real\": confirmReal, force },\n params: ({ options }, a) => ({ chat: a.chat, amount: sats(a.amount), memo: options.memo, network: options.network, confirmReal: options[\"confirm-real\"] === true, force: options.force === true }),\n },\n \"chat pay-request\": {\n method: \"chat.payRequest\", usage: \"chat pay-request <chat> <payment> [--via lightning] [--max-fee sats] [--card <id>] [--confirm-real]\", summary: \"Pay a contact's request\",\n args: [\"chat\", \"payment\"], options: { via: { type: \"string\", choices: [\"lightning\"], description: \"lightning: pay its invoice instead of ecash\" }, \"max-fee\": { type: \"number\", description: \"Refuse a fee above this\" }, card, \"confirm-real\": confirmReal },\n params: ({ options }, a) => ({ chat: a.chat, payment: a.payment, via: options.via, maxFee: options[\"max-fee\"], card: options.card, confirmReal: options[\"confirm-real\"] === true }),\n },\n \"chat request\": {\n method: \"chat.request\", usage: \"chat request <chat> <sats> [--memo t] [--method m] [--rail cashu|lightning] [--network testnet] [--card <id>] [--force]\", summary: \"Ask a contact to pay (with --method usdt the amount is in USDT: 5 is 5 USDT)\",\n args: [\"chat\", \"amount\"], options: { memo, method: { type: \"string\", choices: PAY_METHODS, description: \"cashu, arkade, usdt (amount in USDT), bitcoin, spark, …\" }, rail: { type: \"string\", choices: [\"cashu\", \"lightning\"], description: \"cashu or lightning\" }, network: net, card, force },\n params: ({ options }, a) => ({ chat: a.chat, amount: requestAmount(a.amount, options.method), memo: options.memo, method: options.method, rail: options.rail, network: options.network, card: options.card, force: options.force === true }),\n },\n \"lightning default\": { method: \"lightning.default\", usage: \"lightning default <card> [--network testnet]\", summary: \"The Lightning card that receives by default\", args: [\"card\"], options: { network: net }, params: ({ options }, { card: c }) => ({ card: c, network: options.network }) },\n \"lightning rename\": { method: \"lightning.rename\", usage: \"lightning rename <card> <name...> [--network testnet]\", summary: \"Name a Lightning card\", args: [\"card\", \"name...\"], options: { network: net }, params: ({ options }, a) => ({ card: a.card, name: a.name, network: options.network }) },\n \"pay\": {\n method: \"pay\", usage: \"pay <invoice|lightning-address|lnurl> [--amount sats] [--network n] [--max-fee sats] [--card <id>] [--comment t] [--chat <chat>] [--confirm-real] [--force]\", summary: \"Pay over Lightning from Testnet, or --network mainnet with --confirm-real\",\n args: [\"target\"], options: { amount: { type: \"number\", description: \"Sats, for an address or LNURL; with an invoice, refuse it unless it asks exactly this\" }, network: net, \"max-fee\": { type: \"number\", description: \"Refuse a fee above this\" }, card, comment: { type: \"string\", description: \"For the address's owner\" }, chat: { type: \"string\", description: \"The chat the invoice came from: on Testnet its contact is told it was paid\" }, \"confirm-real\": confirmReal, force },\n params: ({ options }, { target }) => ({ target, amount: options.amount, network: options.network, maxFee: options[\"max-fee\"], card: options.card, comment: options.comment, chat: options.chat, confirmReal: options[\"confirm-real\"] === true, force: options.force === true }),\n },\n \"payment check\": { method: \"payment.check\", usage: \"payment check <chat> <payment>\", summary: \"Paid from another wallet: the contact's app looks now\", args: [\"chat\", \"payment\"], params: (_, a) => ({ chat: a.chat, payment: a.payment }) },\n \"payment list\": {\n method: \"payment.list\", usage: \"payment list [--chat <chat>]\", summary: \"Payments and requests, newest first\",\n options: { chat: { type: \"string\", description: \"Only this chat's\" } },\n // `--chat \"$CHAT\"` with CHAT unset: before, `bad_request` (exit 1), a one-shot online first.\n params: ({ options }) => {\n if (options.chat === \"\") throw new CliError(\"usage\", \"--chat needs a chat\");\n return { chat: options.chat };\n },\n },\n \"payment reclaim\": { method: \"payment.reclaim\", usage: \"payment reclaim <payment>\", summary: \"Take back ecash the contact has not taken\", args: [\"payment\"], params: (_, a) => ({ payment: a.payment }) },\n \"wallet add-mint\": {\n method: \"wallet.mint.add\", usage: \"wallet add-mint <url> [--primary]\", summary: \"Add a Cashu mint (a local or test mint is Testnet's)\",\n args: [\"url\"], options: { primary: { type: \"boolean\", description: \"Make it the one invoices are created at\" } }, params: ({ options }, { url }) => ({ url, primary: options.primary === true }),\n },\n \"wallet address\": {\n method: \"wallet.address\", usage: \"wallet address <bitcoin|arkade|spark|usdt> [--network testnet]\", summary: \"An address to be paid on\",\n args: [\"type\"], words: { type: ADDRESS_TYPES }, options: { network: net }, params: ({ options }, { type }) => ({ type, network: options.network }),\n },\n \"wallet create\": {\n method: \"wallet.create\", usage: \"wallet create <type> [--network testnet] [--provider <id>] [--value name=value]... [--stdin] [--invite <code>] [--api-key <key>]\", summary: \"A wallet: cashu, lightning, arkade, spark, bitcoin, fedimint, usdt (bark: app only)\",\n args: [\"type\"], words: { type: WALLET_TYPES }, options: { network: net, provider: { type: \"string\", description: \"Lightning or on-chain source (wallet list shows them)\" }, value: { type: \"list\", description: \"A field of the source's form, name=value\" }, stdin: { type: \"boolean\", description: \"Secret fields as name=value lines on stdin (api-key=… for the API key), kept out of ps\" }, invite: { type: \"string\", description: \"Fedimint: the federation's invite\" }, \"api-key\": { type: \"string\", description: \"Spark on Mainnet: your Breez API key (better on stdin: --stdin)\" } },\n params: ({ options }, { type }) => ({ type, network: options.network, provider: options.provider, invite: options.invite, apiKey: options[\"api-key\"], values: pairs(options.value), stdin: options.stdin === true ? true : undefined }),\n },\n \"wallet faucet\": {\n method: \"wallet.faucet\", usage: \"wallet faucet <type> [--card <id>]\", summary: \"Test coins from a Testnet wallet's faucet\",\n args: [\"type\"], words: { type: WALLET_TYPES }, options: { card }, params: ({ options }, { type }) => ({ type, network: \"testnet\", card: options.card }),\n },\n \"wallet history\": {\n method: \"wallet.history\", usage: \"wallet history [--network testnet] [--limit n]\", summary: \"A network's wallet history, newest first\",\n options: { network: net, limit: { type: \"number\", description: \"Entries (default 50)\" } }, params: ({ options }) => ({ network: options.network, limit: pageLimit(options) }),\n },\n \"wallet list\": {\n method: \"wallet.list\", usage: \"wallet list [--network mainnet|testnet]\", summary: \"Wallets with their balances, and what New can make\",\n options: { network: net }, params: ({ options }) => ({ network: options.network }),\n },\n \"wallet receive\": {\n method: \"wallet.receive\", usage: \"wallet receive <sats> [--network testnet] [--card <id>]\", summary: \"A Lightning invoice to be paid\",\n args: [\"amount\"], options: { network: net, card }, params: ({ options }, { amount }) => ({ amount: sats(amount), network: options.network, card: options.card }),\n },\n \"wallet redeem\": { method: \"wallet.redeem\", usage: \"wallet redeem [<cashu-token> | -]\", summary: \"Take the ecash of a Cashu token (its mint must be one of yours); the token on stdin keeps it out of ps\", args: [\"token?\"], params: (_, { token }) => ({ token }) },\n \"wallet remove\": {\n method: \"wallet.remove\", usage: \"wallet remove <type> [--network testnet] [--card <id>] [--accept-loss]\", summary: \"Remove a wallet; refused while it holds money or waits for some, unless --accept-loss\",\n args: [\"type\"], words: { type: WALLET_TYPES }, options: { network: net, card: card, \"accept-loss\": { type: \"boolean\", description: \"What it holds on this device is lost without its backup\" } },\n params: ({ options }, { type }) => ({ type, network: options.network, card: options.card, acceptLoss: options[\"accept-loss\"] === true }),\n },\n};\n","import { type Command, inRange } from \"./shared\";\n\n/** Shared local services: one entry per command, in alphabetical order (test/commands.test.ts checks). */\nexport const commands: Record<string, Command> = {\n \"service add\": { method: \"service.add\", usage: \"service add <name> <http://127.0.0.1:port>\", summary: \"A web app on this machine that contacts may be given\", args: [\"name\", \"target\"], params: (_, a) => ({ name: a.name, target: a.target }) },\n \"service close\": { method: \"service.close\", usage: \"service close <chat> <service>\", summary: \"Close a contact's app opened here\", args: [\"chat\", \"service\"], params: (_, a) => ({ chat: a.chat, service: a.service }) },\n \"service enable\": { method: \"service.enable\", usage: \"service enable <service> [--off]\", summary: \"Turn a shared app on or off\", args: [\"service\"], options: { off: { type: \"boolean\", description: \"Turn it off\" } }, params: ({ options }, a) => ({ service: a.service, off: options.off === true }) },\n \"service list\": { method: \"service.list\", usage: \"service list\", summary: \"Web apps this profile shares\" },\n \"service open\": { method: \"service.open\", usage: \"service open <chat> <service> [--port p]\", summary: \"A contact's app on a loopback port here (daemon)\", args: [\"chat\", \"service\"], options: { port: { type: \"number\", description: \"Local port (default: any free one)\" } }, params: ({ options }, a) => ({ chat: a.chat, service: a.service, port: inRange(options, \"port\", \"a whole number\", 0, 65535, true) }) },\n \"service peer\": { method: \"service.peer\", usage: \"service peer <chat>\", summary: \"What a contact shares with you\", args: [\"chat\"], params: (_, a) => ({ chat: a.chat }) },\n \"service remove\": { method: \"service.remove\", usage: \"service remove <service>\", summary: \"Stop sharing a web app with anyone\", args: [\"service\"], params: (_, a) => ({ service: a.service }) },\n \"service share\": { method: \"service.share\", usage: \"service share <service> <chat> [--off]\", summary: \"Give (or take back) a contact access to a web app\", args: [\"service\", \"chat\"], options: { off: { type: \"boolean\", description: \"Take it back\" } }, params: ({ options }, a) => ({ service: a.service, chat: a.chat, off: options.off === true }) },\n};\n","import { CliError } from \"../errors\";\nimport { commands as apps } from \"./apps\";\nimport { commands as calls } from \"./calls\";\nimport { commands as chats } from \"./chats\";\nimport { commands as files } from \"./files\";\nimport { commands as general } from \"./general\";\nimport { commands as groups } from \"./groups\";\nimport { commands as identities } from \"./identities\";\nimport { commands as payments } from \"./payments\";\nimport { commands as services } from \"./services\";\nimport { type Command, wait, groupWait, force, reply, buttonOptions, listed } from \"./shared\";\nimport { strayValue, type OptionSpec } from \"../args\";\n\nexport type { Command };\n\n/**\n * The commands that are one API method each, one file per area of the app, each in alphabetical order. A new\n * command goes in its area's file at its place; a new area is a new file and its two lines here. The order here\n * is the order `ghostly help` lists them in.\n */\nexport const COMMANDS: Record<string, Command> = {\n ...general,\n ...chats,\n ...groups,\n ...files,\n ...payments,\n ...identities,\n ...services,\n ...calls,\n ...apps,\n};\n\n/** Commands that take text (argument or stdin), with the secret guard and delivery waits. */\nexport const TEXT_COMMANDS: Record<string, { method: string; target: \"chat\" | \"group\"; message?: true; usage: string; summary: string; args: string[]; options: Record<string, OptionSpec> }> = {\n \"send\": {\n method: \"chat.send\", target: \"chat\", args: [\"chat\", \"text...?\"], usage: \"send <chat> [text...] [--reply <message>] [--button id:Label]... [--style id=primary|neutral|danger]... [--once] [--id id] [--stdin] [--force] [--wait none|sent|delivered] [--timeout s]\", summary: \"Send a message (text from arguments or stdin); --button puts buttons under it, each label its own (case aside)\",\n options: { stdin: { type: \"boolean\", description: \"Read the text from stdin\" }, force, reply, ...buttonOptions, ...wait },\n },\n \"edit\": {\n method: \"chat.edit\", target: \"chat\", message: true, args: [\"chat\", \"message\", \"text...?\"], usage: \"edit <chat> <message> [text... | --text <text> | --stdin] [--force] [--wait none|confirmed] [--timeout s]\", summary: \"Replace the text of a message you sent (the id send gave; in a group, group edit)\",\n options: { stdin: { type: \"boolean\", description: \"Read the new text from stdin\" }, text: { type: \"string\", description: \"The new text, as one argument\" }, force, wait: { type: \"string\", choices: [\"none\", \"confirmed\"], description: \"none or confirmed (default: none with a daemon, confirmed without)\" }, timeout: wait.timeout },\n },\n \"group send\": {\n method: \"group.send\", target: \"group\", args: [\"group\", \"text...?\"], usage: \"group send <group> [text...] [--mention <member>]... [--reply <message>] [--button id:Label]... [--style id=primary|neutral|danger]... [--once] [--id id] [--stdin] [--force] [--wait none|sent] [--timeout s]\", summary: \"Send to a group; mention members written as @name in the text; --button puts buttons under it\",\n options: { stdin: { type: \"boolean\", description: \"Read the text from stdin\" }, force, reply, mention: { type: \"list\", description: \"A member (key, key prefix, name or everyone) named as @name in the text\" }, ...buttonOptions, ...groupWait },\n },\n \"group edit\": {\n method: \"group.edit\", target: \"group\", message: true, args: [\"group\", \"message\", \"text...?\"], usage: \"group edit <group> <message> [text... | --text <text> | --stdin] [--mention <member>]... [--force] [--wait none|sent] [--timeout s]\", summary: \"Replace the text of a message you sent to a group (the id group send gave)\",\n options: { stdin: { type: \"boolean\", description: \"Read the new text from stdin\" }, text: { type: \"string\", description: \"The new text, as one argument\" }, force, mention: { type: \"list\", description: \"A member newly named as @name in the text (those the message named stay)\" }, ...groupWait },\n },\n};\n\n\n/**\n * Positionals that name something by its id (a chat or a group also by a prefix or its name). The ids are the\n * engine's and the contacts', and drafts, payments and groups are base64url, which starts with `-` one time in 64:\n * in these a word that starts with a dash is the value. A mistyped flag there names nothing and fails as not found;\n * text, names and paths stay strict.\n */\nconst ID_ARGS = new Set([\"chat\", \"message\", \"group\", \"member\", \"payment\", \"file\", \"draft\", \"id\", \"card\", \"service\", \"call\"]);\n\n/**\n * The positionals that may be left out ahead of a required one (`chat?` in `[<chat>] <file>`): left out, they shift the\n * others. One with no required one after it (`<chat> [<method>]`, `text...?`) is simply missing at the end: it shifts nothing.\n */\nconst leadingOptionals = (names: readonly string[]) => names.filter((name, i) => name.endsWith(\"?\") && !name.endsWith(\"...?\") && names.slice(i + 1).some((after) => !after.endsWith(\"?\")));\n\n/**\n * Which of a command's positionals take an id, by index (a trailing `...` one covers the rest). An optional `name?`\n * shifts the others, so it counts only where it and what may come in its place are all ids.\n */\nexport function idSlot(command: { args?: string[] }): (index: number) => boolean {\n const names = (command.args ?? []).map((name) => name.replace(/\\?$/, \"\"));\n const shift = leadingOptionals(command.args ?? []).length;\n const rest = names.findIndex((name) => name.endsWith(\"...\"));\n const at = (index: number) => {\n const name = rest !== -1 && index >= rest ? names[rest].slice(0, -3) : names[index];\n return name !== undefined && ID_ARGS.has(name);\n };\n return (index) => at(index) && (shift === 0 || index + shift >= names.length || at(index + shift));\n}\n\n/** Positionals that take a number (`<sats>`): there `-5` is that number, refused as one, not an unknown option. */\nconst NUMBER_ARGS = new Set([\"amount\"]);\n\n/** Which of a command's positionals take a number, by index; a leading `name?` shifts them as it does in `idSlot`. */\nexport function numberSlot(command: { args?: string[] }): (index: number) => boolean {\n const names = (command.args ?? []).map((name) => name.replace(/\\?$/, \"\"));\n const shift = leadingOptionals(command.args ?? []).length;\n const at = (index: number) => NUMBER_ARGS.has(names[index] ?? \"\");\n return (index) => at(index) && (shift === 0 || index + shift >= names.length || at(index + shift));\n}\n\n/** Whether a command's last positional takes the rest of the line as words, not ids: a text, a name, a path, emoji. */\nexport function takesText(command: { args?: string[] }): boolean {\n const last = command.args?.at(-1)?.replace(/\\?$/, \"\");\n return !!last?.endsWith(\"...\") && !ID_ARGS.has(last.slice(0, -3));\n}\n\n/**\n * The placeholders a usage line shows for its positionals, in order: `chat pay <chat> <sats> [--memo t]` →\n * [\"chat\", \"sats\"]. One that is not a plain `<x>` (`[text... | --text <text>]`) is undefined; the flags end them.\n */\nfunction usageNames(usage: string): (string | undefined)[] {\n const words = usage.split(/\\s+/);\n const first = words.findIndex((word) => word.startsWith(\"<\") || word.startsWith(\"[\"));\n const out: (string | undefined)[] = [];\n for (const word of first === -1 ? [] : words.slice(first)) {\n if (/^\\[?-|^\\|/.test(word)) break;\n out.push(/^\\[?<([^>]+?)(?:\\.\\.\\.)?>(?:\\.\\.\\.)?\\]?$/.exec(word)?.[1]);\n }\n return out;\n}\n\n/**\n * The positionals of a command, by name; missing required ones are a usage error, and so are ones given as \"\" (an\n * unset variable in a script), before the profile opens. A leading `name?` is optional: it is given only when every\n * required one is there too (`file accept [<chat>] <file>`). A trailing `name...` takes the rest and needs at least\n * one word that is not \"\"; `name...?` may take none (text from stdin, `chat rename`'s name back to the contact's).\n * One that takes a few words (`words`) is refused any other the same way, named as the usage shows it (`<type>`).\n */\nexport function positionals(command: { usage: string; args?: string[]; words?: Record<string, readonly string[]> }, values: readonly string[]): Record<string, string | undefined> {\n let names = command.args ?? [];\n const optional = leadingOptionals(names);\n let skip = 0;\n if (optional.length) {\n skip = Math.max(0, optional.length - Math.max(0, values.length - (names.length - optional.length)));\n names = [...optional.slice(skip).map((name) => name.slice(0, -1)), ...names.filter((name) => !optional.includes(name))];\n }\n // Named as the usage line shows it (`<sats>`, not the parameter's `amount`).\n const shown = usageNames(command.usage);\n const missing = (i: number, name: string) => new CliError(\"usage\", `Missing <${shown[i + skip] ?? name}>: ghostly ${command.usage}`);\n const out: Record<string, string | undefined> = {};\n for (let i = 0; i < names.length; i++) {\n const name = names[i].replace(/\\?$/, \"\");\n if (name.endsWith(\"...\")) {\n const rest = values.slice(i);\n if (rest.every((word) => word === \"\") && !names[i].endsWith(\"?\")) throw missing(i, name.slice(0, -3));\n out[name.slice(0, -3)] = rest.length ? rest.join(\" \") : undefined;\n return out;\n }\n if (values[i] === undefined && names[i].endsWith(\"?\")) continue;\n if (values[i] === undefined || values[i] === \"\") throw missing(i, name);\n const words = command.words?.[name];\n if (words && !words.includes(values[i])) {\n // A usage that spells the words out (`<auto|dht|...>`) names the argument by its own name.\n const placeholder = shown[i + skip] && !shown[i + skip]!.includes(\"|\") ? shown[i + skip] : name;\n throw new CliError(\"usage\", `<${placeholder}> takes ${listed(words)}, not ${JSON.stringify(values[i])}`);\n }\n out[name] = values[i];\n }\n noMoreThan(names.length, values, command.usage);\n return out;\n}\n\n/**\n * Words past a usage's arguments are refused, never dropped: `profile use my bot` would select `my`. One of them right\n * after an option that stood alone (`file send bob v.wav --voice 2s`) is refused as that option's value.\n */\nexport function noMoreThan(count: number, values: readonly string[], usage: string): void {\n if (values.length > count) throw strayValue(values) ?? new CliError(\"usage\", `Too many arguments: ghostly ${usage}`);\n}\n","import { spawn } from \"node:child_process\";\nimport { accessSync, constants, existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { contactKeyOf, nameKey, namedByThem } from \"./apiKit\";\nimport { childEnv } from \"./childEnv\";\nimport { connectDaemon, type DaemonAddress, type DaemonClient } from \"./client\";\nimport { CliError, localFileError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport type { GhostlyEvent } from \"./events\";\nimport { jsonOut } from \"./jsonOut\";\nimport { turnRef } from \"./turnRefs\";\n\n/**\n * What `ghostly listen` does with each event: print it as a JSON line, run a command with it on stdin, or POST it to\n * a local bridge. Events are handled one at a time, in order; a cursor file acknowledges each one handled, so a\n * restarted listener resumes after the last.\n */\nexport interface ListenOptions {\n types: string[];\n exec?: string;\n webhook?: string;\n cursor?: string;\n print: boolean;\n /** `false` (as `stream.write` says it): the output wants a drain, and the next event waits for `drained`. */\n write: (line: string) => unknown;\n /** Resolves once the output takes more (its 'drain'), or is gone. */\n drained?: () => Promise<void>;\n /** `--from` and `--group`: events of anyone else stop here (they stay in the chat). */\n allow?: Allowlist;\n /** `--turns`: only agent turns, as `agent.turn` events. */\n turns?: boolean;\n /** `--translate`: the event with its received message's `translation` (translate.ts), before a turn is made of it. */\n translate?: (event: GhostlyEvent) => Promise<GhostlyEvent>;\n /** The first wait before a webhook is tried again (500 ms), doubled each time up to a minute. */\n retryMs?: number;\n /**\n * The cursor could not be written (a full disk): the listener stops. Run on, each event was said on stderr and the\n * cursor stayed where it was, so a restart handed every event since then again (agents#1710). Without it, said on\n * stderr per event as before.\n */\n cursorFailed?: (error: unknown) => void;\n /** `EXEC_SLOW_MS` and `EXEC_STOP_MS`, shorter in tests. */\n execSlowMs?: number;\n stopMs?: number;\n /**\n * The folder and profile the listen runs on, set as `GHOSTLY_HOME` and `GHOSTLY_PROFILE` in an --exec hook's\n * environment: its own `ghostly send` answers from them. Before, a listen given `--profile` or `--home` ran its hook\n * on the environment's, and the answer went to the current profile (\"No chat …\", or another identity's chat).\n */\n profile?: { home: string; name: string };\n}\n\n/** The cursor's own write failed, not the event's handling. */\nclass CursorError extends Error {\n constructor(readonly error: unknown) { super(error instanceof Error ? error.message : String(error)); }\n}\n\n/**\n * Who `listen` passes on, checked before any hook or output: chats by id (a contact key is matched to its chat as\n * events come, so a chat made after the start counts too), groups by id. An event of a chat or group not on it is\n * dropped; one that names neither (`daemon.started`, `events.gap`, `identity.approval`) is this profile's own and\n * passes.\n */\nexport class Allowlist {\n private readonly peers = new Map<string, string>();\n\n /** `peerOf`: a chat's contact key (null when it has none yet, or the chat is gone). */\n constructor(private readonly chats: ReadonlySet<string>, private readonly keys: ReadonlySet<string>, private readonly groups: ReadonlySet<string>, private readonly peerOf: (chat: string) => Promise<string | null>) {}\n\n async allows(event: GhostlyEvent): Promise<boolean> {\n if (\"group\" in event) return typeof event.group === \"string\" && this.groups.has(event.group);\n // A group's payment names a link (`group:<id>`, a community's `cpay:…`, a member's), never the group: its group says.\n const group = (event.payment as { group?: unknown } | undefined)?.group;\n if (group !== undefined) return typeof group === \"string\" && this.groups.has(group);\n if (!(\"chat\" in event)) return true;\n const chat = event.chat;\n if (typeof chat !== \"string\") return false;\n if (this.chats.has(chat)) return true;\n if (!this.keys.size) return false;\n // A removal carries the key: the chat is gone, so its lookup fails, and a replay holds no earlier event of it.\n if (event.type === \"chat.removed\" && typeof event.peer === \"string\") return this.keys.has(event.peer);\n // Kept once known: a chat's contact key does not change. One not paired yet is asked again next time.\n let key = this.peers.get(chat);\n if (!key) { key = (await this.peerOf(chat).catch(() => null)) || undefined; if (key) this.peers.set(chat, key); }\n return !!key && this.keys.has(key);\n }\n}\n\n/**\n * `--from` and `--group` as ids, resolved once at start: a contact key as that key (whatever any chat is named), else a\n * chat by its id or a label this side gave it, as `call auto on --from` (`findOwnNamedChat`): a prefix of its id or the\n * name its contact gave itself is refused, since another contact could call itself that; a group by id, prefix or name.\n * A name that later changes (or a contact who renames themselves) moves nothing.\n */\nexport async function allowlist(from: readonly string[], groups: readonly string[], call: (method: string, params: Record<string, unknown>) => Promise<unknown>, peerOf: (chat: string) => Promise<string | null>): Promise<Allowlist> {\n const chats = new Set<string>(), keys = new Set<string>(), groupIds = new Set<string>();\n for (const ref of from) {\n const key = contactKeyOf(ref);\n if (key !== undefined) { keys.add(key); continue; }\n chats.add(await fromChat(ref, call));\n }\n for (const ref of groups) groupIds.add(((await otherFlag(call(\"group.get\", { group: ref }), ref, \"--group\", call)) as { id: string }).id);\n return new Allowlist(chats, keys, groupIds, peerOf);\n}\n\n/** The chat `--from <ref>` names (not a contact key): its id, or `namedByThem` when only its contact chose `ref`. */\nasync function fromChat(ref: string, call: (method: string, params: Record<string, unknown>) => Promise<unknown>): Promise<string> {\n const chat = (await otherFlag(call(\"chat.get\", { chat: ref }), ref, \"--from\", call)) as { id: string; label?: string | null; peerName?: string | null; peer?: string };\n // A label compared as the lookup compares it (`nameKey`): the string given to `chat rename` names its chat.\n if (chat.id !== ref && (!nameKey(ref) || nameKey(chat.label) !== nameKey(ref))) throw namedByThem(ref, { chat: chat.id, name: chat.peerName ?? null, contact: chat.peer });\n return chat.id;\n}\n\n/**\n * A `--from` that names a group, or a `--group` a chat: said with the flag that takes it. The lookup's own hint named\n * `ghostly group show` (or `chat show`), which lists nothing. A chat is named by its id: `--from` refuses a prefix of it\n * or the name its contact chose, which `--group`'s lookup took, so a `--group` that found its chat only so is refused\n * as `--from` refuses it, with no `--from` to paste.\n */\nasync function otherFlag(lookup: Promise<unknown>, ref: string, flag: \"--from\" | \"--group\", call: (method: string, params: Record<string, unknown>) => Promise<unknown>): Promise<unknown> {\n try { return await lookup; } catch (error) {\n const other = flag === \"--from\" ? \"group\" : \"chat\";\n if (!(error instanceof CliError) || error.code !== \"not_found\" || typeof error.details?.[other] !== \"string\") throw error;\n if (other === \"chat\" && contactKeyOf(ref) === undefined) await fromChat(ref, call);\n const named = other === \"chat\" ? error.details.chat as string : ref;\n const shown = shellWord(named, error.details[other] as string);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a ${other}, not a ${flag === \"--from\" ? \"chat\" : \"group\"}: ghostly listen ${flag === \"--from\" ? \"--group\" : \"--from\"} ${shown}`, error.details);\n }\n}\n\n/**\n * One agent turn (docs/CLI.md § Agent turns): a message a contact sent in a chat, or a group message that mentions\n * this profile or presses a button of its question. What the sender controls (the text, their name, a quoted snippet, a file's name, the id their message\n * is stored under) is under `untrusted` and nowhere else: an agent reads it as data, never as its instructions. `seq` is\n * the source event's, so `--cursor` and `--since` work as for any event; `id` is stable for the message (dedupe on it).\n */\nexport interface AgentTurn extends GhostlyEvent {\n type: \"agent.turn\";\n source: \"message.received\" | \"group.message\" | \"group.mentioned\" | \"button.pressed\";\n chat?: string;\n group?: string;\n /** A group's author (their key). */\n member?: string;\n /** What `send --reply` (or `group send --reply`) takes to answer it: an id made here (`turnRef`), never the sender's. */\n messageId: string;\n timestamp: number;\n /**\n * The message pressed a button of a question this profile sent (WISP 406 · Message Buttons), as this side's engine\n * matched it: the question's id, the button's id and its label, all this profile's own words, and who pressed (`by`:\n * the chat, or the member's key in a group; null when the group message names none).\n */\n press?: { messageId: string; button: string; label: string; inferred?: true; by: string | null };\n /** `translation`: `listen --translate`'s, made of the sender's text, so theirs as much. */\n untrusted: { text: string; name: string | null; messageId: string; replyTo?: { id: string; snippet: string }; file?: { id: string; name: string; size: number; mime: string; voice: boolean }; translation?: { from: string; text: string } };\n}\n\ninterface TurnMessage { id: string; text: string; timestamp: number; nick: string | null; member?: string; mentioned?: boolean; replyTo?: { id: string; snippet: string }; press?: Omit<NonNullable<AgentTurn[\"press\"]>, \"by\">; file?: { id: string; name: string; size: number; mime: string; voice?: unknown }; translation?: { from: string; text: string } }\n\n/**\n * Whether a group message is meant for this profile: it mentions it, or it presses a button of a question this profile\n * sent (`press` is set only on a press of mine, `buttonPress`). A press on another member's question is theirs to answer.\n */\nconst forMe = (message: TurnMessage): boolean => !!message.mentioned || !!message.press;\n\n/**\n * The turn an event starts, or null: only a contact's message, and a group message that mentions this profile or\n * presses a button of its question (or the `group.mentioned`, `button.pressed` that says so later).\n */\nexport function toTurn(event: GhostlyEvent): AgentTurn | null {\n const message = event.message as TurnMessage | undefined;\n if (!message || typeof message.text !== \"string\") return null;\n if (event.type === \"message.received\" && typeof event.chat === \"string\") return turn(event, \"message.received\", { chat: event.chat }, message);\n if (event.type === \"group.message\" && typeof event.group === \"string\" && forMe(message)) return turn(event, \"group.message\", { group: event.group, ...(message.member ? { member: message.member } : {}) }, message);\n // A mention learned after its message was reported (its `group.message` named nobody): the turn it did not start then.\n if (event.type === \"group.mentioned\" && typeof event.group === \"string\" && message.mentioned) return turn(event, \"group.mentioned\", { group: event.group, ...(message.member ? { member: message.member } : {}) }, message);\n // A press learned after its reply was reported (that `group.message` pressed nothing): the turn it did not start then.\n // Only such a `button.pressed` carries the reply.\n if (event.type === \"button.pressed\" && typeof event.group === \"string\" && message.press) return turn(event, \"button.pressed\", { group: event.group, ...(message.member ? { member: message.member } : {}) }, message);\n return null;\n}\n\nfunction turn(event: GhostlyEvent, source: AgentTurn[\"source\"], where: Pick<AgentTurn, \"chat\" | \"group\" | \"member\">, message: TurnMessage): AgentTurn {\n const file = message.file;\n // The source event's id ends in the stored id, the sender's: this one is made of the same parts with the id made here.\n const place = where.chat ?? where.group ?? \"\", messageId = turnRef(place, message.id);\n return {\n seq: event.seq, id: `agent.turn:${source}:${place}:${messageId}`, type: \"agent.turn\", at: event.at, source, ...where, messageId, timestamp: message.timestamp,\n // Who pressed, as `button.pressed` says it: the chat, or the member's key in a group.\n ...(message.press ? { press: { ...message.press, by: where.chat ?? where.member ?? null } } : {}),\n untrusted: {\n text: message.text, name: message.nick ?? null, messageId: message.id,\n ...(message.replyTo ? { replyTo: { id: message.replyTo.id, snippet: message.replyTo.snippet } } : {}),\n ...(file ? { file: { id: file.id, name: file.name, size: file.size, mime: file.mime, voice: !!file.voice } } : {}),\n ...(message.translation ? { translation: { from: message.translation.from, text: message.translation.text } } : {}),\n },\n };\n}\n\n/**\n * Only loopback: events carry message text, and a webhook is a local bridge (WISP 1100 § Security). `from` names where\n * the URL came from; what is not a URL is not repeated: a bridge's token is in it.\n */\nexport function checkWebhook(url: string, from = \"--webhook\"): URL {\n let parsed: URL;\n try { parsed = new URL(url); } catch { throw new CliError(\"usage\", `${from} is not a URL`); }\n if (![\"http:\", \"https:\"].includes(parsed.protocol)) throw new CliError(\"usage\", \"The webhook must be http:// or https://\");\n if (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(parsed.hostname)) throw new CliError(\"usage\", \"The webhook must be on this machine (127.0.0.1, localhost or [::1])\");\n // fetch refuses a URL with credentials: every event was held as \"not answering\" for good, the password on stderr.\n 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, the URL in GHOSTLY_WEBHOOK\");\n return parsed;\n}\n\n/**\n * The event number a cursor file holds, or undefined when there is no file (a first start: live events). A file that is\n * there and holds no whole number (empty, half-written, edited by hand) is refused, naming the file and what it holds:\n * taken as no cursor, the listener started at the journal's end and skipped every event since the last one handled,\n * without a word, and its next write replaced the file.\n */\nexport function readCursor(path: string | undefined): number | undefined {\n if (!path || !existsSync(path)) return undefined;\n let text: string;\n try { text = readFileSync(path, \"utf8\"); } catch (error) { throw localFileError(error, path) ?? error; }\n const trimmed = text.trim();\n const value = trimmed === \"\" ? NaN : Number(trimmed);\n if (Number.isSafeInteger(value) && value >= 0 && /^\\d+$/.test(trimmed)) return value;\n const shown = trimmed === \"\" ? \"nothing\" : JSON.stringify(trimmed.length > 32 ? `${trimmed.slice(0, 32)}…` : trimmed);\n throw new CliError(\"bad_request\", `${path} holds no event number (${shown}): fix or remove it, or give --since`);\n}\n\n/**\n * Where listen starts: after the event number the cursor file holds, else after `since` (--since: the first start's\n * place). Before, --since won without a word, and a unit with `--since 0 --cursor f` ran every handled event's hook\n * again at each restart. A cursor file that holds no number is refused unless --since is given, which starts it.\n * `known`, once the journal's last event is: says on stderr where it starts. A cursor past it (a profile restored from a\n * backup, a journal reset, a cursor copied from another profile) starts with new events; before, stderr said \"starting\n * after it\" (or nothing, without --since) and the next event wrote a lower number over the file.\n */\nexport function startAt(since: number | undefined, cursor: string | undefined, say: (line: string) => void): { from: number | undefined; known(lastSeq: number): void } {\n let kept: number | undefined;\n if (since === undefined) kept = readCursor(cursor);\n else try { kept = readCursor(cursor); } catch { /* --since starts it */ }\n return {\n from: kept ?? since,\n known: (lastSeq) => {\n if (kept === undefined) return;\n if (kept > lastSeq) say(`ghostly: ${cursor} holds event ${kept}, past this profile's last event (${lastSeq}): starting with new events`);\n else if (since !== undefined && kept !== since) say(`ghostly: ${cursor} holds event ${kept}: starting after it, not after --since ${since}`);\n },\n };\n}\n\n/**\n * Whether a cursor can be kept at `path`, asked before anything starts: its folder is there and takes a file. Before, a\n * folder that was not there was found at the first event: the listener ran, said \"event N failed: ENOENT\" for each one\n * and never wrote the cursor, so the next start began at the journal's end and skipped what came while it was down.\n * Throws what the file system says (`asCliError` names the path and the code: not_found, refused).\n */\nexport function checkCursor(path: string | undefined): void {\n if (!path) return;\n const folder = dirname(resolve(path));\n if (!statSync(folder).isDirectory()) throw new CliError(\"not_found\", `No such file or folder: ${folder}`);\n accessSync(folder, constants.W_OK | constants.X_OK);\n}\n\nfunction writeCursor(path: string, seq: number): void {\n // A new file each time (`wx`): a link left where the temporary file goes is removed, never written through.\n rmSync(path + \".tmp\", { force: true });\n writeFileSync(path + \".tmp\", String(seq) + \"\\n\", { mode: 0o600, flag: \"wx\" });\n renameSync(path + \".tmp\", path);\n}\n\n/**\n * `--type`: one type (`message.received`, exactly: `group.message` is not its `group.message.edited`), or a family, a\n * word with no \".\" (`message`, `chat`) or one ending in \".\" or \"*\" (`group.typing.`). Before, a family needed its \".\" and\n * `--type chat` let nothing through. A family is whole words: `message` is not `messages.x`.\n */\nexport function matches(event: GhostlyEvent, types: readonly string[]): boolean {\n if (!types.length) return true;\n return types.some((type) => {\n if (type === \"*\") return true;\n const family = /[.*]$/.test(type) ? type.replace(/\\.?\\*$/, \"\").replace(/\\.$/, \"\") : type.includes(\".\") ? null : type;\n return event.type === type || (family !== null && event.type.startsWith(family + \".\"));\n });\n}\n\n/**\n * Every event type a daemon of this version emits (events.ts, appEvents.ts, holds.ts, identities.ts, calls/manager.ts,\n * main.ts) and `--turns`' own. A test reads them back from the source: a type added there and not here fails it.\n */\nexport const EVENT_TYPES: readonly string[] = [\n \"agent.turn\",\n \"app.closed\", \"app.message\", \"app.opened\",\n \"button.pressed\",\n \"call.connected\", \"call.ended\", \"call.incoming\", \"call.outgoing\", \"call.resumed\", \"call.stalled\",\n \"chat.announced\", \"chat.connection\", \"chat.created\", \"chat.held\", \"chat.joined\", \"chat.pairing\", \"chat.pinned\", \"chat.released\", \"chat.removed\", \"chat.renamed\",\n \"daemon.started\",\n \"events.gap\",\n \"file.done\", \"file.failed\", \"file.offered\", \"file.stage\",\n \"group.created\", \"group.deleted\", \"group.event\", \"group.members\", \"group.mentioned\", \"group.message\", \"group.message.edited\", \"group.pinned\", \"group.reaction\",\n \"group.removed\", \"group.sent\", \"group.status\", \"group.typing.started\", \"group.typing.stopped\",\n \"identity.approval\", \"identity.progress\", \"identity.received\", \"identity.status\",\n \"message.deleted\", \"message.delivery\", \"message.edited\", \"message.reaction\", \"message.received\", \"message.sent\",\n \"payment.created\", \"payment.updated\",\n \"typing.started\", \"typing.stopped\",\n];\n\n/** The families, the first word of each type: what a `--type` must start with. */\nexport const EVENT_FAMILIES: readonly string[] = [...new Set(EVENT_TYPES.map((type) => type.split(\".\")[0]))];\n\n/**\n * Checks each `--type` before anything starts. Before, `--type bogus` (or a typo such as `message.recieved`) was taken\n * and the listener stayed silent for good. A first word that is no family is a usage error naming them; a type, or a\n * family below the first word, that no event has is said on stderr (`warn`) and kept: a newer daemon may emit it.\n */\nexport function checkTypes(types: readonly string[], warn: (line: string) => void): void {\n for (const type of types) {\n if (type === \"*\") continue;\n const family = type.split(/[.*]/)[0];\n if (!EVENT_FAMILIES.includes(family)) throw new CliError(\"usage\", `No event is of type ${type}: --type takes a type, or a family (${EVENT_FAMILIES.join(\", \")})`);\n // Turns are made from the events --type keeps, and --turns is refused beside it: a --type that keeps only\n // agent.turn kept nothing, and the listener stayed silent for good without a word.\n const known = EVENT_TYPES.filter((each) => matches({ seq: 0, id: \"\", type: each, at: 0 }, [type]));\n if (known.length === 1 && known[0] === \"agent.turn\") throw new CliError(\"usage\", `No event is of type ${type} without --turns: ghostly listen --turns gives agent.turn events, in the place of --type`);\n if (!EVENT_TYPES.some((known) => matches({ seq: 0, id: \"\", type: known, at: 0 }, [type]))) warn(`ghostly: no event is of type ${type}; the ${family} family has ${EVENT_TYPES.filter((known) => known.startsWith(family + \".\")).join(\", \")}`);\n }\n}\n\n/** The environment a hook runs in: this one's, less the backup passphrase (a hook, and what it runs, never needs it). */\nexport function hookEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n return childEnv(env);\n}\n\n/** How a hook ended: its exit code, or the signal that killed it (`code` null then). */\ninterface HookEnd { code: number | null; signal: NodeJS.Signals | null }\n\n/** How long a hook's stdout is still waited for once the hook exited: a process it left running may hold it open. */\nconst HOOK_OUTPUT_GRACE_MS = 1000;\n/** How long a hook runs before stderr says, once, that the events after it wait for it. */\nexport const EXEC_SLOW_MS = 60_000;\n/** A stop gives a running hook this long to end on its own, then as long again after SIGTERM before SIGKILL. */\nexport const EXEC_STOP_MS = 5_000;\n\n/** A hook at work: how it ended, and a signal sent to it and what it started. */\ninterface Hook { event: GhostlyEvent; ended: Promise<HookEnd>; signal(name: NodeJS.Signals): void; stopped?: boolean }\n\n/**\n * Runs `command` through the shell with the event on stdin (never in its arguments).\n * `toStderr` (with `--print`, whose stdout is the JSON stream): the hook's stdout is streamed to listen's stderr, so a\n * hook that echoes never puts a line that is not an event into the stream. Piped as it comes, never held in memory.\n */\nfunction runExec(command: string, event: GhostlyEvent, toStderr: boolean, profile?: ListenOptions[\"profile\"]): Hook {\n // Its own process group (not on Windows, where that opens a console), so a stop ends the hook and what it started.\n const group = process.platform !== \"win32\";\n const child = spawn(command, {\n shell: true,\n detached: group,\n stdio: [\"pipe\", toStderr ? \"pipe\" : \"inherit\", \"inherit\"],\n env: { ...hookEnv(process.env), ...(profile ? { GHOSTLY_HOME: profile.home, GHOSTLY_PROFILE: profile.name } : {}), GHOSTLY_EVENT_TYPE: event.type, GHOSTLY_EVENT_ID: event.id, GHOSTLY_EVENT_SEQ: String(event.seq) },\n });\n const signal = (name: NodeJS.Signals) => {\n try { if (group && child.pid) process.kill(-child.pid, name); else child.kill(name); } catch { /* gone already */ }\n };\n // A listen that leaves anyway (a second signal, a stop past its bound, a cursor it cannot write) takes its hook with\n // it. Before, the hook ran on as an orphan, and the restarted listen ran the same event's hook again alongside it.\n const orphaned = () => signal(\"SIGKILL\");\n process.on(\"exit\", orphaned);\n const ended = new Promise<HookEnd>((resolve) => {\n let done = false;\n const finish = (end: HookEnd) => { if (!done) { done = true; resolve(end); } };\n child.on(\"error\", () => finish({ code: 127, signal: null }));\n // `exit`, not `close`: a process the hook left running (`… &`) may hold its stdout for long; the hook is done when\n // it exits. Its output is still waited for a moment, so the stderr note comes after it; whatever comes later is\n // still streamed.\n child.on(\"exit\", (code, name) => {\n const end = { code, signal: name };\n const output = child.stdout;\n if (!output || output.readableEnded || output.destroyed) return finish(end);\n const timer = setTimeout(() => finish(end), HOOK_OUTPUT_GRACE_MS);\n output.once(\"close\", () => { clearTimeout(timer); finish(end); });\n });\n }).finally(() => process.off(\"exit\", orphaned));\n child.stdout?.pipe(process.stderr, { end: false });\n child.stdin?.on(\"error\", () => {});\n child.stdin?.end(JSON.stringify(event) + \"\\n\");\n return { event, ended, signal };\n}\n\n/** The longest wait between two tries of a webhook that is not answering. */\nconst RETRY_MAX_MS = 60_000;\n\n/**\n * Posts one event; resolves true once the bridge took it, or the status it refused it with (a 4xx or a redirect, posted\n * once: before, three times with backoff, three refusals in the bridge's log for an event stderr said was not tried again).\n * A bridge that is not there (refused connection, timeout, 5xx, 408, 429) has not handled the event: it is tried again,\n * waiting up to a minute between tries, for as long as it takes, so the cursor never moves past it. Before, three tries\n * in 3.5 s and the cursor moved on: a bridge restarting for longer lost every event of the time it was down, for good.\n */\nasync function post(url: URL, event: GhostlyEvent, retryMs: number): Promise<true | number> {\n let wait = retryMs, holding = false;\n for (let attempt = 0; ; attempt++) {\n let down = true, status = 0;\n try {\n // A redirect is not followed: it would post the event to wherever it points, off this machine too. stderr names the\n // bridge by its origin only: its token is in the path or query (no user:password@, `checkWebhook`).\n const response = await fetch(url, { method: \"POST\", redirect: \"manual\", headers: { \"content-type\": \"application/json\", \"x-ghostly-event\": event.type, \"x-ghostly-seq\": String(event.seq) }, body: JSON.stringify(event), signal: AbortSignal.timeout(10_000) });\n void response.body?.cancel().catch(() => {});\n if (response.ok) {\n if (holding) process.stderr.write(`ghostly: the webhook at ${url.origin} answers again: event ${event.seq} taken\\n`);\n return true;\n }\n status = response.status;\n down = status >= 500 || status === 408 || status === 429;\n } catch { /* not there: tried again */ }\n if (!down) return status;\n if (down && attempt >= 2 && !holding) {\n holding = true;\n process.stderr.write(`ghostly: the webhook at ${url.origin} is not answering: holding event ${event.seq} (${event.type}) until it does\\n`);\n }\n await new Promise((resolve) => setTimeout(resolve, wait));\n wait = Math.min(wait * 2, RETRY_MAX_MS);\n }\n}\n\n/** Events given to a handler and not handled yet: what `listen` holds in memory. */\nexport interface EventHandler {\n (event: GhostlyEvent): void;\n /** How many events are given and not handled yet. */\n behind(): number;\n /** Resolves when every event given is handled. */\n idle(): Promise<void>;\n /**\n * Takes no more events and resolves once no hook runs: one at work gets `EXEC_STOP_MS` to end on its own (the cursor\n * then moves past its event), else it and what it started are sent SIGTERM, then SIGKILL, and the cursor stays before\n * its event, handed again at the next start. Before, a stop left the hook running on its own, and the restarted listen\n * ran that event's hook a second time alongside it.\n */\n stop(): Promise<void>;\n}\n\n/**\n * A handler that takes events in order, one at a time. A step that throws (the output closed, the allowlist's lookup,\n * the cursor's disk) is said on stderr and passed: the cursor moves on and the next event is handled.\n */\nexport function eventHandler(options: ListenOptions): EventHandler {\n const webhook = options.webhook ? checkWebhook(options.webhook) : null;\n let chain = Promise.resolve();\n let behind = 0;\n let stopped = false;\n /** The hook at work, if any. */\n let running: Hook | null = null;\n const slowMs = options.execSlowMs ?? EXEC_SLOW_MS, stopMs = options.stopMs ?? EXEC_STOP_MS;\n /** The last event the cursor says, and the last one `--type` dropped while others were still being handled. */\n let kept = -1, dropped = -1;\n const keep = (seq: number) => {\n if (!options.cursor) return;\n try { writeCursor(options.cursor, seq); } catch (error) { throw new CursorError(error); }\n kept = Math.max(kept, seq);\n };\n /** The cursor past events dropped meanwhile, once nothing before them is left to handle. */\n const keepDropped = () => {\n // Once stopped, never past an event whose hook the stop ended.\n if (stopped || behind > 0 || dropped <= kept) return;\n try { keep(dropped); } catch (failed) {\n if (!(failed instanceof CursorError) || !options.cursorFailed) return;\n stopped = true;\n options.cursorFailed(failed.error);\n }\n };\n const handle = (event: GhostlyEvent) => {\n const seq = event.seq, type = event.type;\n if (stopped) return;\n // A type it was not asked for is dropped as it comes: not held behind a webhook or an --exec still at work, not\n // counted toward MAX_BEHIND, not kept. An app's frames at 48 a second, each 32 KiB, filled the bound in 21 s behind\n // a bridge that was down, ~32 MiB held to be dropped, and the feed paused with the one wanted event pending\n // (agents#1597). The cursor passes it once the events before it are handled.\n // `events.gap` passes every `--type` and `--turns`, as it passes the allowlist: a bot on `message.received` is told\n // that messages were lost across a crash or a trim. Before, it was dropped and the cursor moved past it.\n const gap = type === \"events.gap\";\n if (!gap && !matches(event, options.types)) { dropped = Math.max(dropped, seq); keepDropped(); return; }\n behind++;\n chain = chain.then(async () => {\n if (stopped) return;\n const skip = () => keep(event.seq);\n if (options.allow && !(await options.allow.allows(event))) return skip();\n // What --turns drops is dropped before the translation: a contact's edits and a group's messages that name nobody\n // went through the model one by one, 16 KiB each, every turn behind them waiting, to be thrown away.\n if (options.turns && !gap && !toTurn(event)) return skip();\n if (options.translate) event = await options.translate(event);\n if (options.turns && !gap) event = toTurn(event)!;\n const full = options.print && options.write(jsonOut(event)) === false;\n if (options.exec) {\n const hook = running = runExec(options.exec, event, options.print, options.profile);\n // Once, as the webhook's \"not answering\": a hook that never ends held every later event without a word.\n const slow = setTimeout(() => process.stderr.write(`ghostly: --exec still runs on event ${hook.event.seq} (${hook.event.type}) after ${Math.round(slowMs / 1000)} s: the events after it wait for it\\n`), slowMs);\n const { code, signal } = await hook.ended.finally(() => { clearTimeout(slow); running = null; });\n // Ended by the stop: the cursor stays before the event.\n if (hook.stopped) return;\n // A hook killed by a signal (the OOM killer, a timeout wrapper) is said as such, not as an exit 1.\n if (signal) process.stderr.write(`ghostly: --exec was killed by ${signal} on event ${event.seq} (${event.type})\\n`);\n else if (code !== 0) process.stderr.write(`ghostly: --exec exited ${code ?? 1} on event ${event.seq} (${event.type})\\n`);\n }\n // A refusal passes the event for good: said with what the bridge answered, so a wrong path (404) or a missing\n // token (401) is seen in the log, not only as messages that never came.\n const answered = webhook ? await post(webhook, event, options.retryMs ?? 500) : true;\n if (webhook && answered !== true) process.stderr.write(`ghostly: the webhook at ${webhook.origin} answered ${answered}: event ${event.seq} (${event.type}) passed, not taken (a 4xx or a redirect is not tried again)\\n`);\n // An output whose reader stopped holds the next event here, not one more line in its buffer per event.\n if (full) await options.drained?.();\n // A failed hook (an --exec exiting non-zero, an event the webhook refused) still moves the cursor: one poisonous\n // event must not stop the stream. The failure is on stderr. A webhook not answering never gets here (`post`).\n keep(event.seq);\n }).catch((error: unknown) => {\n try {\n if (!(error instanceof CursorError)) {\n process.stderr.write(`ghostly: event ${seq} (${type}) failed: ${error instanceof Error ? error.message : String(error)}\\n`);\n keep(seq);\n } else throw error;\n } catch (failed) {\n if (!(failed instanceof CursorError) || !options.cursorFailed) return; // the next event moves the cursor\n stopped = true;\n options.cursorFailed(failed.error);\n }\n }).finally(() => { behind--; keepDropped(); });\n };\n const within = (promise: Promise<unknown>, ms: number) => Promise.race([promise.then(() => true), new Promise<boolean>((resolve) => setTimeout(() => resolve(false), ms).unref())]);\n const stop = async () => {\n stopped = true;\n const hook = running;\n if (!hook) return;\n if (await within(hook.ended, stopMs)) {\n // It ended on its own: its event's cursor is written in a moment (not waited for past the bound: a webhook down).\n await within(chain, stopMs);\n return;\n }\n hook.stopped = true;\n process.stderr.write(`ghostly: stopped while --exec ran on event ${hook.event.seq} (${hook.event.type}): ended it, and the event is handed again at the next start\\n`);\n hook.signal(\"SIGTERM\");\n if (!(await within(hook.ended, stopMs))) { hook.signal(\"SIGKILL\"); await hook.ended; }\n };\n return Object.assign(handle, { behind: () => behind, idle: () => chain, stop });\n}\n\n/** Events a listener takes ahead of its output and hooks before it stops taking more (a few MB at most). */\nexport const MAX_BEHIND = 1_000;\n\n/**\n * Bounds what a listener holds when its output or hooks fall behind (a stdout reader that hung, a slow --exec): past\n * `MAX_BEHIND` events not handled it stops taking events (`pause`: the subscription stops reading) and drops what still\n * arrives; once every event taken is handled, `resume` opens it again after the last one taken. The daemon's journal\n * keeps what came meanwhile (and says `events.gap` past what it keeps), so a consumer that hangs for a day does not\n * grow the listener by the day's traffic.\n */\nexport class Feed {\n private held = false;\n\n /** `since`: the last event taken (or, before one, the daemon's last seq when it subscribed), where a new subscription starts. */\n constructor(private readonly handle: EventHandler, public since: number | undefined, private readonly pause: () => void, private readonly resume: (since: number | undefined) => void) {}\n\n get paused(): boolean { return this.held; }\n\n readonly take = (event: GhostlyEvent): void => {\n if (this.held) return;\n this.since = event.seq;\n this.handle(event);\n if (this.handle.behind() < MAX_BEHIND) return;\n this.held = true;\n this.pause();\n void this.handle.idle().then(() => { this.held = false; this.resume(this.since); });\n };\n}\n\n/** How long a feed that fell behind keeps its connection to the daemon open, unread, while its hooks take no event (`followDaemon`). */\nexport const PAUSE_HOLD_MS = 60_000;\n\n/**\n * Follows a daemon's events into `handle` until `close`; a daemon that restarts is picked up again after the last event\n * seen. A feed that falls behind stops reading the connection, not closes it: what the daemon sent meanwhile (a replay\n * written whole) is read on resume, so a catch-up reads the journal once, not once per pause. A connection the daemon\n * ended meanwhile (past what it lets a client leave unread) is opened again after the last event taken.\n * A feed whose hooks take no event for `holdMs` (`PAUSE_HOLD_MS`: a hook that hung) ends the connection, as a full one\n * does, so the daemon does not keep a replay and what came live for it while it hangs; resume opens it again after the\n * last event taken.\n * `subscribed`: the first subscription's answer (a journal that cannot be replayed rejects it).\n * `profile`: a daemon gone longer than a restart takes (`daemon stop`) is said once on stderr, and so is the one that\n * answers again: the listen waits for it, it does not go silent.\n */\nexport function followDaemon(address: DaemonAddress, client: DaemonClient, handle: EventHandler, since: number | undefined, holdMs = PAUSE_HOLD_MS, profile?: string): { subscribed: Promise<unknown>; close(): void } {\n let current: DaemonClient | null = client, missedSince = 0, missing = false;\n let holding: ReturnType<typeof setTimeout> | undefined;\n const reconnect = (wait: number) => void (async () => {\n while (!current && !feed.paused) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n wait = 1000;\n if (current || feed.paused) return;\n const next = await connectDaemon(address, 1000);\n if (next) {\n missedSince = 0;\n if (missing) { missing = false; process.stderr.write(`ghostly: the daemon of profile ${profile} answers again\\n`); }\n current = next;\n await follow(next).catch(() => { if (current === next) current = null; });\n } else if (profile === undefined) continue;\n else if (!missedSince) missedSince = Date.now();\n else if (!missing && Date.now() - missedSince >= 3000) {\n missing = true;\n process.stderr.write(`ghostly: the daemon of profile ${profile} stopped; waiting for it to start again (ghostly daemon --detach)\\n`);\n }\n }\n })();\n // A hook still taking events (a slow --exec) keeps the connection; one that took none for `holdMs` lets it go.\n const hold = (behind: number) => {\n holding = setTimeout(() => {\n if (handle.behind() < behind) return hold(handle.behind());\n const c = current; current = null; c?.destroy();\n }, holdMs);\n };\n const feed = new Feed(handle, since, () => {\n current?.pause();\n hold(handle.behind());\n }, () => {\n clearTimeout(holding);\n if (current) current.resume(); else reconnect(0);\n });\n // A feed that took no event yet goes on after the last seq the daemon had when it subscribed: one that restarts\n // otherwise subscribes it from its own now, past what it journaled before the reconnect (its daemon.started). So does\n // one started past the daemon's last event (a cursor from a backup, `startAt`): it waited at the cursor's number, and\n // the daemon replays nothing up to it. Not once it took an event since: that is where it is.\n const follow = (c: DaemonClient) => {\n const asked = feed.since;\n return c.subscribe(asked, feed.take, () => {\n if (current !== c) return;\n current = null;\n reconnect(1000);\n }).then((answer) => {\n if (typeof answer?.lastSeq === \"number\" && feed.since === asked && (asked === undefined || asked > answer.lastSeq)) feed.since = answer.lastSeq;\n return answer;\n });\n };\n return { subscribed: follow(client), close: () => { clearTimeout(holding); current?.close(); } };\n}\n","import { CliError } from \"./errors\";\n\n/**\n * Secrets a command takes (a Cashu token, an API key, a card's form) come on stdin: on the command line they show in\n * `ps` to every user of the machine while the command runs, and stay in the shell's history. Still taken there, with\n * a warning. Fills `params` in place; the warning to print on stderr, if any. `tty`: stdin is a terminal, where a\n * read would wait on the keyboard without a word.\n */\nconst JOINS: Record<string, { param: string; arg: string; command: string; what: string }> = {\n \"group.join\": { param: \"link\", arg: \"<link>\", command: \"group join\", what: \"A group's link\" },\n \"invite.join\": { param: \"invite\", arg: \"<invite-or-link>\", command: \"invite join\", what: \"An invite\" },\n};\n\n/**\n * A join given no invite, a redeem given no token and a send given no text read stdin, but a pipe nobody writes or closes (what Node's exec and most harnesses give a\n * child) would hold it for ever without a word: a note once nothing has come for a while, the usage error once nothing\n * has come at all. A producer that started writing is waited for to the end; `-` asked for stdin and waits as long.\n */\nexport const STDIN_NOTE_MS = 2_000;\nexport const STDIN_GIVE_UP_MS = 60_000;\n\n/** `read`'s `onData`: called at the first chunk, once something is coming. */\nexport type StdinRead = (onData?: () => void) => Promise<string>;\n\nexport async function secretsFromStdin(method: string, params: Record<string, unknown>, read: StdinRead, tty = false, note: (text: string) => void = () => {}): Promise<string | undefined> {\n const warning = (what: string) => `${what} on the command line shows in ps and the shell's history: give it on stdin instead`;\n if (method === \"wallet.redeem\") {\n if (params.token !== undefined && params.token !== \"-\") return warning(\"A token\");\n const missing = () => new CliError(\"usage\", \"Missing <cashu-token>: give it as an argument or on stdin (… | ghostly wallet redeem)\");\n if (tty) throw missing();\n const token = (params.token === \"-\" ? await read() : await readUnasked(read, note, { what: \"a Cashu token\", missing: \"Missing <cashu-token>\", command: \"wallet redeem\", as: \"an argument\" })).trim();\n if (!token) throw missing();\n params.token = token;\n return undefined;\n }\n // A group's link and a chat's invite are secrets everywhere else (hidden in `group show`, in no event): the same here.\n const join = JOINS[method];\n if (join) {\n if (params[join.param] !== undefined && params[join.param] !== \"-\") return warning(join.what);\n const missing = () => new CliError(\"usage\", `Missing ${join.arg}: give it on stdin (… | ghostly ${join.command}) or as an argument`);\n if (tty) throw missing();\n const value = (params[join.param] === \"-\" ? await read() : await readUnasked(read, note, { what: join.what.toLowerCase(), missing: `Missing ${join.arg}`, command: join.command, as: \"an argument\" })).trim();\n if (!value) throw missing();\n params[join.param] = value;\n return undefined;\n }\n if (method === \"wallet.create\") {\n // A form's fields are often plain (a network, a script type): the API key here, the secret fields by\n // `secretValuesWarning` once the source's form is known.\n const onLine = params.apiKey !== undefined;\n if (params.stdin === true) {\n if (tty) throw new CliError(\"usage\", \"--stdin takes the values as name=value lines piped to it (… | ghostly wallet create <type> --stdin), not a terminal\");\n const values = { ...(params.values as Record<string, string> | undefined) };\n for (const line of (await read()).split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const eq = line.indexOf(\"=\");\n if (eq < 1) throw new CliError(\"usage\", \"--stdin takes name=value lines (api-key=… for the API key)\");\n const name = line.slice(0, eq).trim(), value = line.slice(eq + 1);\n if (name === \"api-key\") params.apiKey = value;\n else values[name] = value;\n }\n if (Object.keys(values).length) params.values = values;\n }\n delete params.stdin;\n return onLine ? warning(\"An API key\") : undefined;\n }\n return undefined;\n}\n\n/**\n * `x401 credential add -`: the SD-JWT VC from stdin. Nothing there, or a terminal (a read that would wait on the\n * keyboard without a word), is the usage error a join gives.\n */\nexport async function credentialFromStdin(read: StdinRead, tty = false): Promise<string> {\n const missing = () => new CliError(\"usage\", \"Missing <file|->: give the SD-JWT VC on stdin (… | ghostly x401 credential add -) or as a file\");\n if (tty) throw missing();\n const credential = await read();\n if (!credential) throw missing();\n return credential;\n}\n\n/**\n * `send`, `edit`, `group send` and `group edit` with no text words read it from stdin the same way: `command` is the\n * command line as given (`send bob`). `asked`: `--stdin`, which waits as long as it takes.\n */\nexport async function textFromStdin(read: StdinRead, command: string, asked: boolean, note: (text: string) => void): Promise<string> {\n const text = asked ? await read() : await readUnasked(read, note, { what: \"the text\", missing: \"No text\", command, as: \"arguments\" });\n return text.replace(/\\n$/, \"\");\n}\n\n/**\n * `identity complete <draft> --stdin` (or `--evidence-file -`): what the tool printed, from stdin. A terminal (a read\n * that would wait on the keyboard without a word) is a usage error, as identity add --stdin's is.\n */\nexport async function evidenceFromStdin(read: StdinRead, draft: string, tty = false): Promise<string> {\n if (tty) throw new CliError(\"usage\", `Missing what the tool printed: stdin is a terminal; pipe it in (… | ghostly identity complete ${draft}) or give --evidence-file f`);\n return read();\n}\n\n/**\n * `identity complete <draft>` with neither --evidence-file nor --stdin, stdin not a terminal: asked with nothing first,\n * since a published record takes none; a draft that answers it takes a tool's output (`details.needs`) is asked again\n * with what was piped, read as a send reads its text.\n */\nexport async function completeWithPipedEvidence(call: (params: Record<string, unknown>) => Promise<unknown>, params: Record<string, unknown>, read: StdinRead, note: (text: string) => void): Promise<unknown> {\n try { return await call(params); } catch (error) {\n if (!(error instanceof CliError) || error.details?.needs !== \"evidence\") throw error;\n }\n const evidence = await readUnasked(read, note, { what: \"what the tool printed\", missing: \"Missing what the tool printed\", command: `identity complete ${String(params.draft)}`, as: \"--evidence-file f\" });\n return call({ ...params, evidence });\n}\n\n/**\n * `settings set <key> <json-value>`'s value: from stdin when it is `-`, or when none is given and stdin is not a\n * terminal (a pipe nobody writes: the note, then the usage error, as for a join). A TURN password (`iceServers` with a\n * `credential`) given on the command line still goes, with the ps/history warning: `settings get` hides it as a secret.\n */\nexport async function settingValue(key: string, value: string | undefined, read: StdinRead, tty = false, note: (text: string) => void = () => {}): Promise<{ value: string; warning?: string }> {\n // No value at all: the usage error every command gives (reason, then the usage line); an empty stdin after `-` says how.\n const usage = \"Missing <json-value>: ghostly settings set <key> <json-value> [--force]\";\n if (value !== undefined && value !== \"-\") return { value, ...(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} -)` }) };\n if (value === undefined && tty) throw new CliError(\"usage\", usage);\n const text = (value === \"-\" ? await read() : await readUnasked(read, note, { what: \"the value\", missing: \"Missing <json-value>\", command: `settings set ${key}`, as: \"an argument\" })).replace(/\\r?\\n$/, \"\");\n if (!text.trim()) throw new CliError(\"usage\", value === \"-\" ? `Missing <json-value> on stdin: … | ghostly settings set ${key} -` : usage);\n return { value: text };\n}\n\n/** Whether an `iceServers` value as typed holds a TURN password: an entry with a `credential` that is not empty. */\nfunction hasCredential(value: string): boolean {\n let servers: unknown;\n try { servers = JSON.parse(value); } catch { return false; }\n return Array.isArray(servers) && servers.some((server) => !!server && typeof server === \"object\" && typeof (server as { credential?: unknown }).credential === \"string\" && (server as { credential: string }).credential !== \"\");\n}\n\n/** What `readUnasked` says: `what` is waited for, `missing` is the usage error's title, `as` the other way to give it. */\ninterface Unasked { what: string; missing: string; command: string; as: string }\n\nasync function readUnasked(read: StdinRead, note: (text: string) => void, ask: Unasked): Promise<string> {\n let noteTimer: ReturnType<typeof setTimeout> | undefined, giveUpTimer: ReturnType<typeof setTimeout> | undefined;\n const stop = () => { clearTimeout(noteTimer); clearTimeout(giveUpTimer); };\n const nothingCame = new Promise<never>((_, reject) => {\n noteTimer = setTimeout(() => note(`Waiting for ${ask.what} on stdin (… | ghostly ${ask.command}): give it there or as ${ask.as}`), STDIN_NOTE_MS);\n giveUpTimer = setTimeout(() => reject(new CliError(\"usage\", `${ask.missing}: nothing came on stdin in ${STDIN_GIVE_UP_MS / 1000} s; give it there (… | ghostly ${ask.command}) or as ${ask.as}`)), STDIN_GIVE_UP_MS);\n });\n try { return await Promise.race([read(stop), nothingCame]); }\n finally { stop(); }\n}\n\n/**\n * `identity add`'s fields: each `--field name=value`, then with `--stdin` the `name=value` lines piped to it (a NIP-46\n * signer's bunker:// link holds the signer's secret). `secret`: the names the signer's form marks `kind: \"secret\"`\n * (`identitySecretFields`); one given as a `--field` still goes, with the warning. Neither error repeats a value.\n */\nexport async function identityFields(items: string[], stdin: boolean, secret: string[], read: StdinRead, tty = false): Promise<{ fields: Record<string, string>; warning?: string }> {\n const fields: Record<string, string> = {};\n for (const item of items) {\n const eq = item.indexOf(\"=\");\n if (eq < 1) throw new CliError(\"usage\", \"--field takes name=value, and one has no name or no =\");\n fields[item.slice(0, eq)] = item.slice(eq + 1);\n }\n const onLine = secret.filter((name) => fields[name] !== undefined);\n if (stdin) {\n 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\");\n for (const line of (await read()).split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const eq = line.indexOf(\"=\");\n if (eq < 1) throw new CliError(\"usage\", \"--stdin takes name=value lines, and one has no name or no =\");\n fields[line.slice(0, eq).trim()] = line.slice(eq + 1);\n }\n }\n if (!onLine.length) return { fields };\n return { fields, 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)` };\n}\n\n/** The fields a provider's signer marks `kind: \"secret\"`: the one `--signer` names, or any of its signers when none is. */\nexport function identitySecretFields(provider: { signers: readonly { id: string; fields?: readonly { name: string; kind?: string }[] }[] } | undefined, signer?: string): string[] {\n const signers = (provider?.signers ?? []).filter((s) => signer === undefined || s.id === signer);\n return [...new Set(signers.flatMap((s) => (s.fields ?? []).filter((f) => f.kind === \"secret\").map((f) => f.name)))];\n}\n\n/**\n * `wallet create --value`: the names given on the command line that the chosen source's form marks `kind: \"secret\"`\n * (an NWC URI, a macaroon, a rune, an RPC password), as a warning. `list`: a `wallet.list` answer, where the forms are.\n */\nexport function secretValuesWarning(list: unknown, type: unknown, provider: unknown, names: string[]): string | undefined {\n if (!names.length) return undefined;\n const id = provider ?? (type === \"bitcoin\" ? \"bdk\" : undefined);\n const offers = (list as { offers?: { type?: string; providers?: { id: string; fields?: { name: string; kind?: string }[] }[] }[] } | undefined)?.offers ?? [];\n const fields = offers.find((o) => o.type === type && o.providers)?.providers?.find((p) => p.id === id)?.fields ?? [];\n const secret = names.filter((name) => fields.some((f) => f.name === name && f.kind === \"secret\"));\n if (!secret.length) return undefined;\n return `${secret.map((name) => `--value ${name}`).join(\", \")} on the command line shows in ps and the shell's history: give ${secret.length > 1 ? \"them\" : \"it\"} on stdin instead (--stdin, name=value lines)`;\n}\n","import { spawn } from \"node:child_process\";\nimport { connect } from \"node:net\";\nimport { closeSync, fstatSync, openSync, readFileSync, readSync, rmSync } from \"node:fs\";\nimport { dirname, sep } from \"node:path\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { checkSettingKey, checkSettingValue, GLOBAL_OPTIONS, globalOption, liftGlobals, nearest, parseArgs, unknownGlobalOption, type OptionSpec, type Parsed } from \"./args\";\nimport { connectDaemon, DaemonClient, endedUnanswered, endedUnsent, isNotTheDaemon, notTheDaemon } from \"./client\";\nimport { childEnv, dropSecretEnv } from \"./childEnv\";\nimport { COMMANDS, idSlot, noMoreThan, numberSlot, positionals, takesText, TEXT_COMMANDS } from \"./commands\";\nimport { here, inRange, INPUT_BYTES, localStat, readInput, since as sinceOf, STDIN_TOO_BIG, timeout, translate } from \"./commands/shared\";\nimport { ENGINE_METHODS, ENGINE_PARAMS, ENGINE_READS, READ_PARAMS, SECRET_RESULTS, hideSecretFields } from \"./engineMethods\";\nimport { asCliError, CliError, type ErrorCode, EXIT, localFileError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport type { Host } from \"./host\";\nimport { jsonOut } from \"./jsonOut\";\nimport { ownProfile } from \"./privateFolder\";\nimport { shellWord } from \"./shellWord\";\nimport { waitNotice, waitsFor, type WaitNotice } from \"./waitNotice\";\nimport type { RuntimeOptions } from \"./runtime/engine\";\nimport { allowlist, checkCursor, checkTypes, checkWebhook, eventHandler, Feed, followDaemon, PAUSE_HOLD_MS, startAt } from \"./listen\";\nimport { format } from \"node:util\";\nimport { completeWithPipedEvidence, credentialFromStdin, evidenceFromStdin, identityFields, identitySecretFields, secretsFromStdin, secretValuesWarning, settingValue, textFromStdin } from \"./secretInput\";\nimport type { Translator } from \"./translate\";\nimport {\n checkProfileName, checkShownNameOption, createProfile, currentProfile, currentProfileOrNone, DEFAULT_PROFILE, ghostlyHome, listProfiles, lockOwner, noProfile, profileExists, profilePaths, selectProfile,\n claimForDaemon, daemonClaim, startingDaemon,\n type ProfilePaths,\n} from \"./profiles\";\n\nconst VERSION = packageJson.version;\n\n/**\n * The engine's modules (the API, the host, the backup, the buttons) are loaded only where a command needs them here: a\n * command a running daemon answers loads none of them, and starts about as fast as Node does. Statically imported, they\n * cost every command ~100 ms before its socket was opened.\n */\nconst engineApi = () => import(\"./api\");\nconst engineHost = () => import(\"./host\");\n\n/**\n * `--translate <lang>`'s translator, or null (not asked; or the runtime is not there, said on stderr). Loaded only when\n * asked: the app's message parser it reads costs every other command nothing.\n */\nasync function translatorFor(value: unknown, home: string): Promise<Translator | null> {\n if (value === undefined) return null;\n const { loadDetector, openTranslator, translateTarget } = await import(\"./translate\");\n const to = translateTarget(value)!;\n return openTranslator({ home, to, detect: await loadDetector(), warn: (line) => process.stderr.write(line + \"\\n\") });\n}\n\ninterface Globals { home: string; profile: string; paths: ProfilePaths; pretty: boolean }\n\nlet pretty = false;\nfunction print(value: unknown): void {\n process.stdout.write(jsonOut(value, pretty ? 2 : undefined) + \"\\n\");\n}\n\n/**\n * Where `run` writes a failure: stdout, unless stdout is the call's audio (`call pipe`). There the error was played as\n * a click (`call pipe | aplay …`) and the terminal said nothing.\n */\nlet failures: NodeJS.WriteStream = process.stdout;\n\n/** Done, with something to know (a voice note sent without its waveform): said on stderr, the JSON stays the answer. */\nfunction printAnswer(result: Record<string, unknown>): void {\n if (typeof result?.warning === \"string\") {\n process.stderr.write(`ghostly: ${result.warning}\\n`);\n delete result.warning;\n }\n print(result);\n}\n\n/** `ownProfile`: the command names its profile, or none (`profile create`, `use`): a bad `<home>/current` is not read. */\nfunction globals(parsed: Parsed, { ownProfile = false } = {}): Globals {\n const home = ghostlyHome(parsed.options.home as string | undefined);\n const option = parsed.options.profile as string | undefined;\n const profile = ownProfile ? currentProfileOrNone(home, option) ?? DEFAULT_PROFILE : currentProfile(home, option);\n return { home, profile, paths: profilePaths(home, profile), pretty: parsed.options.pretty === true };\n}\n\n/** The profile must exist; `default` is made on first use, any other with `profile create`. */\nfunction requireProfile(g: Globals): void {\n if (profileExists(g.home, g.profile)) return;\n if (g.profile === DEFAULT_PROFILE) { createProfile(g.home, g.profile); return; }\n throw noProfile(g.profile);\n}\n\n/** For a command that only reads: a mistyped profile is named as one, and `default` is not made by asking about it. */\nfunction knownProfile(g: Globals): void {\n if (g.profile !== DEFAULT_PROFILE && !profileExists(g.home, g.profile)) throw noProfile(g.profile);\n}\n\n/**\n * A way to call the API: the daemon's socket when one runs the profile, else the profile in this process. `abort` is\n * Ctrl-C's way out: the daemon's connection dropped at once, a one-shot's profile closed (its lock released).\n */\ninterface Session { mode: \"daemon\" | \"one-shot\"; call(method: string, params?: unknown): Promise<unknown>; close(): Promise<void>; abort(): Promise<void> }\n\n/** `1.2.3`, with an optional `v`, an optional `-beta.1` prerelease and an optional `+build` that never orders. */\nconst RELEASE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\n\n/** Semver order: negative when `a` is the older release, positive when it is the newer, 0 the same; null when either is not one. */\nexport function compareReleases(a: string, b: string): number | null {\n const left = RELEASE.exec(a.trim()), right = RELEASE.exec(b.trim());\n if (!left || !right) return null;\n for (let i = 1; i <= 3; i++) {\n const order = Number(left[i]) - Number(right[i]);\n if (order !== 0) return order;\n }\n // A prerelease is older than its release; two of one release go field by field, numbers by value and before words.\n if (left[4] === undefined || right[4] === undefined) return (left[4] === undefined ? 1 : 0) - (right[4] === undefined ? 1 : 0);\n const l = left[4].split(\".\"), r = right[4].split(\".\");\n for (let i = 0; i < Math.min(l.length, r.length); i++) {\n if (l[i] === r[i]) continue;\n const ln = /^\\d+$/.test(l[i]), rn = /^\\d+$/.test(r[i]);\n if (ln && rn) return Number(l[i]) - Number(r[i]);\n if (ln !== rn) return ln ? -1 : 1;\n return l[i] < r[i] ? -1 : 1;\n }\n return l.length - r.length;\n}\n\n/**\n * Said on stderr when the daemon runs another release than this command. An older daemon started before an upgrade:\n * `daemon restart` runs this release. A newer one means this command is the old one (a second install, a project's\n * pinned copy): a restart from it would start the older release, so it is told to upgrade instead.\n */\nexport function versionWarning(daemon: unknown, cli: string): string | null {\n if (typeof daemon !== \"string\" || daemon === cli) return null;\n const order = compareReleases(daemon, cli);\n if (order === 0) return null;\n const both = `ghostly: the daemon runs ${daemon} and this command is ${cli}`;\n if (order === null) return `${both}: \\`ghostly daemon restart\\` runs this command's release`;\n if (order > 0) return `${both}, older than the daemon: upgrade the CLI (\\`npm install -g @ghostlytools/cli\\`)`;\n return `${both}: \\`ghostly daemon restart\\` runs the new code`;\n}\n\n/** Said on stderr when `daemon restart` stopped a newer release than the one it started (an older CLI ran it). */\nexport function restartWarning(before: unknown, version: string): string | null {\n if (typeof before !== \"string\" || !((compareReleases(before, version) ?? 0) > 0)) return null;\n return `ghostly: the daemon ran ${before} and this restart started ${version}, an older release: upgrade the CLI (\\`npm install -g @ghostlytools/cli\\`) and run \\`ghostly daemon restart\\` again to go back`;\n}\n\n/**\n * Never fails, and has no deadline of its own: a daemon that does not answer is the command's own call to find out,\n * at the command's deadline, which closes the connection and ends this check with it. A deadline here ended every\n * command on a wedged daemon at 15 s with `unavailable` (\"The daemon went away\"), whatever its own `--timeout` said.\n * A command with no deadline of its own waits for this check instead (15 s, session()), before it is sent.\n */\nasync function warnVersion(client: DaemonClient): Promise<void> {\n const status = await client.call(\"status\").catch(() => null) as { version?: unknown } | null;\n const warning = versionWarning(status?.version, VERSION);\n if (warning) process.stderr.write(warning + \"\\n\");\n}\n\n/** Whether `promise` settles within `ms` (the timer keeps no process alive). */\nfunction settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), ms);\n timer.unref?.();\n const settled = () => { clearTimeout(timer); resolve(true); };\n promise.then(settled, settled);\n });\n}\n\n/**\n * A command about one 1:1 chat: a one-shot for it leaves the groups' sessions unstarted. A fresh process starts an edge\n * per group member, and their first polls spent the relays' 30 requests a minute in seconds: the chat's message then\n * waited for the next minute (60 s and more instead of 3 to 5).\n */\nexport function chatOnly(method: string, params: Record<string, unknown>): boolean {\n // A usage report to every 1:1 chat (`--all`) needs no group.\n if (method === \"usage.send\") return params.all === true;\n if (chatOrGroup(method, params)) return false;\n return method.startsWith(\"chat.\") || (params.chat !== undefined && params.group === undefined && !method.startsWith(\"group.\"));\n}\n\n/** A command whose `chat` may name a group as well: a one-shot for it starts the groups' sessions. */\nfunction chatOrGroup(method: string, params: Record<string, unknown>): boolean {\n // A status card's or a button's (WISP 405 · Status Cards), and a usage report's to a named chat.\n if (method.startsWith(\"task.\") || method.startsWith(\"routine.\") || method.startsWith(\"button.\") || method === \"usage.send\") return true;\n // So may `message delete --everyone`'s: a group's removal goes over its members' edges, which a one-shot that left\n // the groups unstarted never opened (it waited its whole timeout, and the members kept the message).\n if (method === \"chat.delete\" && params.everyone === true) return true;\n // So may a group's file's `file wait`, `save --wait`, `accept` and `request` (its id starts `group-`, groupFiles.ts):\n // it comes over the group's edges only, and with the groups unstarted the wait ran out with no byte here.\n if (method.startsWith(\"file.\") && typeof params.file === \"string\" && params.file.startsWith(\"group-\")) return true;\n // And `pin`'s and `forward --to`'s: a group's pin or forwarded copy goes over the same edges (the pin never went,\n // and a forward's wait could only time out).\n return method === \"chat.pin\" || method === \"chat.forward\";\n}\n\n/**\n * A command that makes a new chat and needs no other: a one-shot for it leaves the saved chats and the groups unstarted.\n * Started, each saved chat put its records and its leave packet on the relays: from about ten that was the relays' 30\n * requests a minute, and the new chat's waited behind them. A new invite took 21 s instead of under one, unpublished;\n * a join waited its whole 60 s and left unpaired. A join of a saved chat starts that chat (the engine's `joinLink`).\n */\nexport function newChatOnly(method: string): boolean {\n return method === \"invite.create\" || method === \"invite.join\";\n}\n\n/**\n * A command about the 1:1 chat it names, or one that makes or joins a new chat (`newChatOnly`): a one-shot for it leaves\n * the other saved chats unstarted too, and starts only the chat a call names (`startNamedChats`). Started, each saved\n * chat put its records and its leave packet on the relays: with 12 invites saved one `send` took the relays' 30\n * requests a minute, and a text to a contact who is away, or the next one-shot, waited behind them. So does a command\n * whose chat may name a group (`chatOrGroup`: a bot's `task send`): the groups start for it, the other 1:1 chats do not.\n */\nexport function oneChatOnly(method: string, params: Record<string, unknown>): boolean {\n return newChatOnly(method) || ((chatOnly(method, params) || chatOrGroup(method, params)) && typeof params.chat === \"string\");\n}\n\n/**\n * What a member says in one group, over that group's own edges: no 1:1 chat carries any of it. The admin's name,\n * picture, call node, hubs and fresh secret too (the group's metadata or a commit). Not `group.remove` (the one removed hears it\n * over the chat that invited them) nor `group.admin` (the new admin takes back the invitations still out).\n */\nconst GROUP_EDGES_ONLY: ReadonlySet<string> = new Set([\"group.send\", \"group.edit\", \"group.react\", \"group.typing\", \"group.rename\", \"group.picture\", \"group.call\", \"group.hub\", \"group.rotate\"]);\n\n/**\n * A command about one group that goes over its edges only (`GROUP_EDGES_ONLY`): a one-shot for it leaves the saved 1:1\n * chats and the other groups' edges unstarted (`deferChats`), and starts the group's own (`startNamedChats`). Started,\n * each saved chat put its records and its leave packet on the relays: with 12 invites saved, one `group send` asked the\n * relay 32 times (3 with none), its whole minute, and a text to an away contact, or the next one-shot, waited behind\n * them. Each other group's edges did the same: with six more groups shared with one member, 31 to 47 times.\n */\nexport function oneGroupOnly(method: string): boolean {\n return GROUP_EDGES_ONLY.has(method);\n}\n\n/**\n * Reads that need nothing of a chat's history: a one-shot for one leaves every saved chat unstarted too (`deferChats`),\n * so its start reads each chat's newest row (its place in `chat list`) and no history. It read every 1:1 chat whole:\n * `profile show` took 0.8 s and 243 MB instead of 0.45 s and 162 MB with 53,800 messages in the profile, and\n * `group list` 0.89 s and 220 MB instead of 0.42 s and 154 MB with 50,000. A group's own reads need its history only,\n * which its start reads whatever this says. The wallet's reads come from its own stores (proofs, wallet history,\n * payments), none from a chat's history: `wallet list` took 1.3 s and 239 MB instead of 0.48 s and 146 MB with 50,000\n * messages; `payment list --chat` starts the chat it names. `identity providers` reads nothing of the profile, and\n * `call auto` and `group auto` with no on|off what it keeps: each took 1.6 s and 211 MB instead of 0.8 s and 152 MB\n * with 50,000.\n */\nconst NO_HISTORY_READS: ReadonlySet<string> = new Set([\n \"status\", \"profile.get\", \"settings.get\", \"status.get\", \"chat.list\", \"group.list\", \"group.get\", \"group.history\",\n \"call.list\", \"service.list\", \"identity.list\", \"x401.credential.list\", \"app.served\", \"wallet.list\", \"wallet.history\",\n \"payment.list\", \"identity.providers\",\n]);\n\n/**\n * Changes kept outside any chat (this profile's status, which each chat says on its next session; x401 keys and\n * credentials; a service; a draft; a served app), and `call answer` and `call flush`, which a one-shot refuses whatever\n * the chats say: a one-shot for one leaves every saved chat unstarted too. Each read every 1:1 chat whole first: with\n * 30,000 messages in the profile, about 0.95 s and 200 MB instead of 0.45 s and 140 MB.\n */\nconst NO_HISTORY_WRITES: ReadonlySet<string> = new Set([\n \"status.set\", \"status.clear\", \"x401.key.new\", \"x401.credential.add\", \"x401.credential.remove\", \"service.add\", \"identity.cancel\",\n \"app.serve\", \"app.unserve\", \"call.answer\", \"call.flush\",\n]);\n\n/** Whether a one-shot for this call leaves every saved chat unstarted, its history unread (`NO_HISTORY_READS`, `NO_HISTORY_WRITES`). */\nexport function readsNoHistory(method: string, params: Record<string, unknown> = {}): boolean {\n if (method === \"call.auto\" || method === \"group.auto\") return params.on === undefined;\n return NO_HISTORY_READS.has(method) || NO_HISTORY_WRITES.has(method);\n}\n\n/**\n * Calls that only read what the profile stores: a one-shot for one opens it offline (`RuntimeOptions.offline`).\n * Opened online, `status` or `chat list` started every chat, put the profile's records on the relays again and waited\n * for its leave packet to be taken: 0.25 s became 3.3 s with a relay that takes 1.5 s, and 10 s with one that does not\n * answer, and each read spent ~5 relay requests per chat of the relays' per-address budget.\n */\nconst READS: ReadonlySet<string> = new Set([\n \"status\", \"profile.get\", \"settings.get\", \"events.replay\", \"chat.list\", \"chat.get\", \"chat.history\", \"chat.details\",\n \"group.list\", \"group.get\", \"group.history\", \"file.list\", \"wallet.list\", \"wallet.history\", \"payment.list\", \"identity.list\", \"identity.providers\",\n \"identity.contact\", \"service.list\", \"service.peer\", \"call.list\", \"app.served\", \"x401.credential.list\", \"saved.list\", \"status.get\",\n]);\n\n/** Whether a one-shot for this call opens the profile offline; test/readOnlyCommands.test.ts names every table command. */\nexport function readOnly(method: string, params: Record<string, unknown>): boolean {\n if (method === \"engine.call\") return typeof params.method === \"string\" && ENGINE_READS.includes(params.method);\n // `call auto` with no on|off says what auto-answer is.\n if (method === \"call.auto\") return params.on === undefined;\n // `group auto` with no on|off says what auto-join is.\n if (method === \"group.auto\") return params.on === undefined;\n // `chat accept <chat>` with no method says what the chat takes.\n if (method === \"chat.accept\") return params.method === undefined;\n return READS.has(method);\n}\n\n/**\n * Calls whose change stays on this device: a chat's name here, a chat removed (nothing goes to the contact), auto-answer\n * (calls.json), auto-join (groups.json: a one-shot accepts nothing itself, the daemon does), a proof dropped, a web app added (shared with no one yet), a message saved or unsaved, an x401 key or credential (WISP 3xx: never\n * shared with a contact), an app served or unserved (served.json: an engine reads it as it starts). Opened online, each put the profile's records on the relays and waited for them (6 PUT + 4\n * GET, 3.3 s with a relay that takes 1.5 s), and the contacts' apps saw this device come online. `message delete` stays\n * online: it settles a file offer already on the DHT.\n */\nconst LOCAL_WRITES: ReadonlySet<string> = new Set([\n \"chat.rename\", \"chat.remove\", \"call.auto\", \"group.auto\", \"identity.cancel\", \"service.add\", \"x401.key.new\", \"x401.credential.add\", \"x401.credential.remove\",\n \"saved.add\", \"saved.remove\", \"app.serve\", \"app.unserve\",\n // This profile's status: kept here, and said only on a live session (WISP 401 § Presence and status), never on a\n // relay. A one-shot waits for no session, so online it would only show this device to the contacts for a moment; the\n // daemon says it at once, and any process that runs the profile online says it on each chat's next session.\n \"status.set\", \"status.clear\",\n]);\n\n/**\n * Settings of this device only: no contact and no relay hears of them (nick, avatar and the relays' do). A one-shot\n * says no presence (`daemonPresence`): only a daemon does, from its start or at once when it is the one that sets it.\n */\nexport const LOCAL_SETTINGS: ReadonlySet<string> = new Set([\"sendTyping\", \"autoDownloads\", \"serveFiles\", \"daemonPresence\"]);\n\n/**\n * Said on a live session only (WISP 401 § Typing, WISP 902 · Group Mesh § Typing). A one-shot starts the chat or group\n * as it says it, so nothing is live yet and it reached nobody; online it then waited for the link's records on the\n * relays (3.4 s with a relay that takes 1.5 s, 10 s with one that does not answer). With `--for` it waits for the chat\n * to be live (`keepOneShot`), so that one stays online.\n */\nconst LIVE_ONLY: ReadonlySet<string> = new Set([\"chat.typing\", \"group.typing\"]);\n\n/**\n * Done only by a daemon (a call placed, a contact's app opened on a port, a served app open in a chat): a one-shot\n * refuses them whatever the network says. Online, it said \"start `ghostly daemon --detach`\" only once its leave packet\n * was taken: 3.4 s with a relay that takes 1.5 s, 10 s with one that does not answer. A one-shot answers no call, queues\n * no audio to flush and has no service open to close: those said \"not found\" after 6-12 s online. `call hangup` stays\n * online: a call may ring while a one-shot runs, and be declined.\n */\nconst DAEMON_ONLY: ReadonlySet<string> = new Set([\"call.start\", \"call.answer\", \"call.flush\", \"service.open\", \"service.close\", \"app.open\", \"app.close\", \"app.send\"]);\n\n/** Whether a one-shot for this call opens the profile offline: a read, a change that stays on this device, typing, or what only a daemon does. */\nexport function offlineCall(method: string, params: Record<string, unknown>): boolean {\n return readOnly(method, params) || LOCAL_WRITES.has(method) || DAEMON_ONLY.has(method) || (LIVE_ONLY.has(method) && params.for === undefined);\n}\n\n/** How long a daemon gets to answer before a command gives up: a read is in memory (15 s); a call that waits for the\n * contact carries its own `--timeout` (or the daemon's default for it), plus a margin; anything else may take as long\n * as it takes, once the daemon has answered the version check sent ahead of it (session()). */\nconst ANSWER_MS = 15_000;\nexport function answerWithin(method: string, params: Record<string, unknown>): number | undefined {\n // A `--timeout` outside the daemon's range (1 to 3600 s, 86 400 for `chat wait` and `file wait`) is refused by the\n // daemon at once (bad_request); the deadline only has to be a timer Node takes (-10 s fired at once, 1e12 after 1 ms).\n const waits = typeof params.timeout === \"number\" ? Math.min(Math.max(params.timeout, 1), 86_400) : waitsFor(method, params);\n if (waits !== undefined) return (waits + 10) * 1000;\n if (readOnly(method, params)) return ANSWER_MS;\n return undefined;\n}\n\n/** `again`: whether a read the daemon left unanswered as it stopped is asked once more (`throughDaemon`). */\nasync function session(g: Globals, options: RuntimeOptions, again = true): Promise<Session> {\n requireProfile(g);\n const anew = again ? () => session(g, options, false) : undefined;\n const client = await connectDaemon(g.paths);\n if (client) return throughDaemon(client, anew);\n const [, { callApi, startNamedChats }] = await Promise.all([engineHost(), engineApi()]);\n const host = await openOneShot(g, options);\n if (host instanceof DaemonClient) return throughDaemon(host, anew);\n const call = async (m: string, p?: unknown) => {\n if (options.deferChats && p && typeof p === \"object\") await startNamedChats(host.ctx, p as Record<string, unknown>);\n return callApi(host.ctx, m, p ?? {});\n };\n return { mode: \"one-shot\", call, close: () => host.close(), abort: () => host.close() };\n}\n\n/**\n * Waits that change nothing (`chat wait`, `file wait`): one a daemon that stopped left unanswered is asked once more,\n * as a read is (`throughDaemon`), for the time it had left. They failed as a timeout told to check `ghostly chat\n * history` for a message (exit 4) when a restart came while they waited.\n */\nconst READ_WAITS: ReadonlySet<string> = new Set([\"chat.wait\", \"file.wait\"]);\n\n/** `params` with the `timeout` (its own, or the daemon's default for `method`) less the `spentMs` already waited. */\nfunction waitLeft(method: string, params: Record<string, unknown>, spentMs: number): Record<string, unknown> {\n const seconds = typeof params.timeout === \"number\" ? params.timeout : waitsFor(method, params);\n return seconds === undefined ? params : { ...params, timeout: Math.max(1, Math.ceil(seconds - spentMs / 1000)) };\n}\n\n/**\n * `again`: a session of its own, for a read (`readOnly`, or one of `READ_WAITS`) whose connection ended unanswered\n * (`endedUnanswered`): the daemon stopped or restarted under it. The read is asked once more there, through the daemon\n * that answers now or on the profile itself, and so is every call after it. It failed as a timeout told to check\n * `ghostly chat history` for a message that was never sent (exit 4), as \"The daemon went away\" (exit 1), or refused as\n * a daemon of an older release (exit 1), while a command started a moment later answered. So is any call whose\n * connection ended before it was written (`endedUnsent`): nothing reached the daemon, and a bot's `typing` or `send`\n * that met a `daemon restart` failed as \"The daemon went away\" while the new daemon came up.\n */\nfunction throughDaemon(client: DaemonClient, again?: () => Promise<Session>): Session {\n // The version check goes on the same connection as the command, ahead of it, not before it, and with no deadline\n // of its own: a daemon that does not answer costs the command its own deadline and nothing else (a read gave up\n // after 30 s, not 15; then every command gave up at the check's 15 s, whatever its own). `close` waits for the\n // check's answer: a daemon that answered the command answered the check sent before it.\n const warned = warnVersion(client);\n let next: Promise<Session> | null = null, aborted = false;\n const first = async (m: string, p?: unknown): Promise<unknown> => {\n const timeoutMs = answerWithin(m, (p ?? {}) as Record<string, unknown>);\n // A call with no deadline of its own (a send, a rename, an invite) goes only once the check is answered: a daemon\n // that has not answered `status` in 15 s does not answer, and the call, never written, cannot happen when it\n // wakes (a daemon stopped with Ctrl+Z reads its socket again on SIGCONT). It used to wait for ever with no word.\n if (timeoutMs === undefined && !await settlesWithin(warned, ANSWER_MS)) {\n client.destroy();\n throw new CliError(\"timeout\", `The daemon did not answer in ${ANSWER_MS / 1000} s; nothing was done: \\`ghostly daemon restart\\` starts a fresh one`, { method: m });\n }\n return client.call(m, p, { timeoutMs });\n };\n const call = async (m: string, p?: unknown): Promise<unknown> => {\n if (next) return (await next).call(m, p);\n const from = performance.now();\n try { return await first(m, p); }\n catch (error) {\n const params = (p ?? {}) as Record<string, unknown>, read = readOnly(m, params) || READ_WAITS.has(m);\n if (!again || aborted || !endedUnanswered(error) || !(read || endedUnsent(error))) throw error;\n next ??= again();\n try { return await (await next).call(m, READ_WAITS.has(m) ? waitLeft(m, params, performance.now() - from) : p); }\n catch (failure) {\n // The daemon asked once more went away as well: a read changed nothing, so it says so, and not to check a chat.\n // A listener refused again is one that does not prove itself, and is named so.\n if (read && endedUnanswered(failure) && !isNotTheDaemon(failure)) throw new CliError(\"unavailable\", `The daemon went away before it answered ${m}, twice; a read changes nothing: run it again`, { method: m });\n throw failure;\n }\n }\n };\n const settled = async (then: (s: Session) => Promise<void>) => { if (next) await next.then(then, () => {}); };\n return {\n mode: \"daemon\",\n call,\n close: async () => { await warned; client.close(); await settled((s) => s.close()); },\n abort: async () => { aborted = true; client.destroy(); await settled((s) => s.abort()); },\n };\n}\n\n/** How long a one-shot waits for another process to let go of the profile: a one-shot leaves in well under a second. */\nconst HOLDER_WAIT_MS = 5_000;\n/** How long it waits for the profile's daemon that is starting (`startingDaemon`): its engine takes seconds on a large profile. */\nconst STARTING_WAIT_MS = 30_000;\n/**\n * The longest a one-shot waits for the profile in all, while it passes from one process to the next (each holder is\n * waited for on its own, above): commands that keep taking it in turn do not keep this one waiting for ever.\n */\nconst TURNS_WAIT_MS = 60_000;\n\n/**\n * Opens the profile in this process for a one-shot command. Another one that holds it (a script's `&`, a second\n * terminal) is waited for: both used to fail at once, and a backgrounded send was lost unless the script checked its\n * exit code. One still holding it after HOLDER_WAIT_MS is answered with the next step. Each process that takes the\n * profile in turn is waited for that long of its own, up to TURNS_WAIT_MS in all: counted from the first look, the\n * wait failed busy while the profile was only passing from one process to the next (the last of six reads started at\n * once, behind five others that each held it for a second on a busy machine). A daemon takes the profile before its\n * socket listens (its engine starts in between, seconds on a large profile): once one answers there, the command\n * goes through it, its client the answer. Only the lock was looked at again, and a command run while the daemon started\n * failed busy, told to start the daemon that was running. A daemon that marked its start is waited for up to\n * STARTING_WAIT_MS, and named as the holder. So is a profile a `daemon restart` or `daemon --detach` keeps for the daemon\n * it starts (`daemonClaim`): the commands that took the profile in turn in the gap kept that daemon from ever starting.\n * A `listen` with no daemon opens it the same way, as the daemon (`mode`). A wait that goes on past WAIT_NOTICE_MS says\n * on a terminal what it waits for, once per kind of holder: it said nothing for up to 30 s (60 s behind commands in turn).\n */\nasync function openOneShot(g: Globals, options: RuntimeOptions = {}, mode: Host[\"ctx\"][\"mode\"] = \"one-shot\"): Promise<Host | DaemonClient> {\n const { openHost } = await engineHost();\n const from = performance.now();\n // The process that holds the profile, as last seen, and since when; the kind of holder the terminal was told of.\n let holder: unknown, since = from, told: string | undefined;\n for (;;) {\n try { return await openHost(g.paths, mode, VERSION, options); }\n catch (error) {\n if (!(error instanceof CliError) || error.code !== \"busy\") throw error;\n // Read before the socket is tried: a daemon whose socket listens in between is found by the try.\n const starting = startingDaemon(g.paths), claimed = starting === null ? daemonClaim(g.paths) : null;\n const client = await connectDaemon(g.paths);\n if (client) return client;\n const pid = error.details?.pid;\n if (pid !== holder) { holder = pid; since = performance.now(); }\n const now = performance.now();\n const left = Math.min(since + (starting === null && claimed === null ? HOLDER_WAIT_MS : STARTING_WAIT_MS), from + TURNS_WAIT_MS) - now;\n if (left <= 0) {\n if (claimed !== null) throw new CliError(\"busy\", `Profile ${g.profile} is kept for the daemon that process ${claimed} (ghostly daemon) starts, still not up after ${Math.round((now - since) / 1000)} s: ghostly daemon status shows when it is up`, { pid: claimed });\n if (starting !== null) throw new CliError(\"busy\", `Profile ${g.profile} is in use by its daemon (process ${starting}), which was still starting after ${Math.round((now - since) / 1000)} s: ghostly daemon status shows when it is up`, { pid: starting });\n const held = now - since >= HOLDER_WAIT_MS ? `was not free after ${HOLDER_WAIT_MS / 1000} s` : `was taken by one process after another for ${TURNS_WAIT_MS / 1000} s`;\n throw new CliError(\"busy\", `Profile ${g.profile} is in use by ${pid ? `process ${pid}, another ghostly command,` : \"another ghostly command\"} and ${held}: run the commands one after another, or start \\`ghostly daemon --detach\\` so they can run at once`, error.details);\n }\n const kind = claimed !== null ? \"claimed\" : starting !== null ? \"starting\" : \"command\";\n if (process.stderr.isTTY && now - from >= WAIT_NOTICE_MS && told !== kind) {\n told = kind;\n const line = claimed !== null ? `profile ${g.profile} is kept for the daemon that process ${claimed} (ghostly daemon) starts: waiting for it (up to ${STARTING_WAIT_MS / 1000} s`\n : starting !== null ? `profile ${g.profile}'s daemon (process ${starting}) is starting: waiting for it (up to ${STARTING_WAIT_MS / 1000} s`\n : `profile ${g.profile} is in use by ${pid ? `process ${pid}, another ghostly command` : \"another ghostly command\"}: waiting for it to let go (up to ${HOLDER_WAIT_MS / 1000} s`;\n process.stderr.write(`ghostly: ${line}; Ctrl-C stops waiting)\\n`);\n }\n await new Promise((resolve) => setTimeout(resolve, Math.min(50 + Math.random() * 50, left)));\n }\n }\n}\n\n/**\n * How a one-shot opens the profile: `deferGroups` when the command is about one 1:1 chat (`chatOnly`) and needs\n * nothing of the groups, `deferChats` too when it names that chat or makes or joins a new one (`oneChatOnly`), `offline`\n * when it only reads or changes only this device (`offlineCall`).\n */\nasync function withSession<T>(g: Globals, work: (s: Session) => Promise<T>, options: RuntimeOptions = {}): Promise<T> {\n const s = await session(g, options);\n const stops = interruptible(s);\n try { return await stops.run(work); } finally { await s.close(); stops.off(); }\n}\n\n/** How long a wait goes on before a terminal is told what it waits for: a command done by then says nothing. */\nexport const WAIT_NOTICE_MS = 1_000;\n/** How long Ctrl-C gives the profile to close before the command leaves anyway (a second Ctrl-C leaves at once). */\nconst INTERRUPT_CLOSE_MS = 10_000;\n\n/**\n * Ctrl-C while a session's command runs (agents#2354): the command stops where it is, a one-shot's profile closes (its\n * lock released, as `daemon` does in `stopper`), one line on stderr says what became of what it waited on, stdout has\n * the `interrupted` error, and the exit is 130. Killed by SIGINT, it said nothing, left `daemon.lock` behind, and the\n * person did not learn that the message still goes (and sent it again). Ctrl-C once the work is done (the profile\n * closing) only lets the answer out. A wait that goes on past WAIT_NOTICE_MS says what it waits for, on a terminal only:\n * stderr of a bot's pipe stays clean.\n */\nfunction interruptible(s: Session): { run<T>(work: (s: Session) => Promise<T>): Promise<T>; off(): void } {\n let interrupted = false, done = false, left = false;\n const pending = new Set<{ method: string; notice: WaitNotice | null }>();\n const onSignal = () => {\n if (interrupted) process.exit(EXIT.interrupted);\n interrupted = true;\n if (done) return;\n const [first] = pending, waiting = [...pending].find((call) => call.notice)?.notice;\n const words = waiting ? `stopped waiting (Ctrl-C): ${waiting.stopped}` : \"stopped (Ctrl-C) before the command answered\";\n const leave = () => {\n if (left) return;\n left = true;\n process.stderr.write(`ghostly: ${words}\\n`);\n print({ error: new CliError(\"interrupted\", words[0].toUpperCase() + words.slice(1), first ? { method: first.method } : undefined).toJSON() });\n exit(EXIT.interrupted);\n };\n setTimeout(leave, INTERRUPT_CLOSE_MS).unref();\n void s.abort().catch(() => {}).then(leave);\n };\n process.on(\"SIGINT\", onSignal);\n // Once interrupted, what the work answers late is nobody's: the command leaves with its own answer.\n const held = <T>(promise: Promise<T>): Promise<T> => new Promise<T>((resolve, reject) => {\n promise.then((value) => { if (!interrupted || done) resolve(value); }, (error: unknown) => { if (!interrupted || done) reject(error); });\n });\n const call = (method: string, params?: unknown): Promise<unknown> => {\n const entry = { method, notice: waitNotice(method, (params ?? {}) as Record<string, unknown>, s.mode) };\n pending.add(entry);\n const notice = entry.notice;\n const timer = notice && process.stderr.isTTY ? setTimeout(() => process.stderr.write(`ghostly: ${notice.waiting}\\n`), WAIT_NOTICE_MS) : undefined;\n return held(s.call(method, params).finally(() => { clearTimeout(timer); pending.delete(entry); }));\n };\n return {\n run: (work) => held(work({ ...s, call }).finally(() => { if (!interrupted) done = true; })),\n off: () => { process.off(\"SIGINT\", onSignal); },\n };\n}\n\n/**\n * 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\n * not paired yet comes with the next step, since nothing pairs once the command has left.\n */\nexport async function oneShotJoinWait(s: Pick<Session, \"call\">, result: Record<string, unknown>, label?: string): Promise<{ answer: Record<string, unknown>; note?: string }> {\n const view = await s.call(\"chat.wait\", { chat: result.chat, until: \"paired\", timeout: 60 }).then((v) => ({ paired: true, chat: v }), () => null)\n ?? await s.call(\"chat.get\", { chat: result.chat }).then((v) => ({ paired: false, chat: v }), () => ({ paired: false, chat: null }));\n const stage = (view.chat as { stage?: unknown } | null)?.stage ?? null;\n const answer = { ...result, paired: view.paired, stage };\n if (view.paired) return { answer };\n // The label only when a shell reads it as typed: `O'Brien` waited for a closing quote, `$work` named no chat. And only\n // when it names this chat alone: a second join with the same `--label` was told a name that names two chats.\n const typed = label?.trim();\n const named = !!typed && shellWord(typed, \"\") === typed\n && await s.call(\"chat.get\", { chat: typed }).then((chat) => (chat as { id?: unknown } | null)?.id === result.chat, () => false);\n const ref = named ? typed : String(result.chat);\n return { answer, note: `Not paired yet: the inviter's app is offline. It pairs when both are online: keep this profile running (ghostly daemon --detach), then ghostly chat wait ${ref} --until paired` };\n}\n\n/**\n * Stdin up to `INPUT_BYTES` (commands/shared.ts, as `readInput` reads it where a command reads it at once); more is refused as it comes. It was read to its end first: `send bob --stdin < big.log`\n * with 1 GiB took 3 GB and answered V8's \"Cannot create a string longer than 0x1fffffe8 characters\", 128 MiB to\n * `settings set nick -` ran the CLI out of memory, an endless pipe never ended, and past 16 MiB a daemon cut the line,\n * answered \"The daemon went away\".\n */\nasync function readStdin(onData?: () => void): Promise<string> {\n const chunks: Buffer[] = [];\n let bytes = 0;\n for await (const chunk of process.stdin) {\n onData?.();\n bytes += (chunk as Buffer).length;\n if (bytes > INPUT_BYTES) throw new CliError(\"bad_request\", STDIN_TOO_BIG);\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\n// ---------- help ----------\n\nconst o = (type: OptionSpec[\"type\"], description: string): OptionSpec => ({ type, description });\n\n/** Commands with their own flow (main.ts), as help shows them. */\nexport const SPECIAL: [usage: string, summary: string, options?: Record<string, OptionSpec>][] = [\n [\"profile create <name> [--use] [--name <shown name>] [--force]\", \"Make a profile (its own keys, chats and wallets)\", { use: o(\"boolean\", \"Make it the current profile\"), name: o(\"string\", \"The name contacts see\"), force: o(\"boolean\", \"Use --name even if it looks like a seed, a key or ecash\") }],\n [\"profile list\", \"Profiles, and which one is current\"],\n [\"profile use <name>\", \"Make a profile the current one\"],\n [\"profile show\", \"The name contacts see, and whether it is shared\"],\n [\"profile set [--name <name>] [--share-profile | --no-share-profile] [--force]\", \"Change the name contacts see\", { name: o(\"string\", \"The name contacts see\"), \"share-profile\": o(\"boolean\", \"Share the name and picture with contacts (--no-share-profile: do not)\"), force: o(\"boolean\", \"Use --name even if it looks like a seed, a key or ecash\") }],\n [\"profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light]\", \"A backup of the profile, encrypted with a passphrase (from a file or GHOSTLY_BACKUP_PASSPHRASE); --no-passphrase makes one anyone can read\", { out: o(\"string\", \"The backup file to write\"), \"passphrase-file\": o(\"string\", \"The passphrase, from this file, or stdin for - (else GHOSTLY_BACKUP_PASSPHRASE). One line break at its end is left out; any other space or line break at an end is refused\"), passphrase: { ...o(\"boolean\", \"Do not encrypt. The file then holds the profile's keys and wallet secrets in the clear\"), negatedOnly: true }, light: o(\"boolean\", \"Leave out files over 1 MB (voice messages over 4 MB); their messages stay\") }],\n [\"profile restore <file> <new profile> [--passphrase-file f] [--use]\", \"A backup into a new profile (a backup made with --no-passphrase needs none)\", { \"passphrase-file\": o(\"string\", \"The passphrase, from this file, or stdin for - (else GHOSTLY_BACKUP_PASSPHRASE). One line break at its end is left out\"), use: o(\"boolean\", \"Make it the current profile\") }],\n [\"daemon [--detach] [--timeout s]\", \"Keep the profile online (foreground; --detach runs it in the background)\", { detach: o(\"boolean\", \"Run in the background (log in the profile folder)\"), timeout: o(\"number\", \"Seconds it waits for a command that holds the profile, and --detach for it to start (default 60)\") }],\n [\"daemon status [--timeout s]\", \"Whether a daemon runs the profile, its version, and its socket (for the socket API)\", { timeout: o(\"number\", \"Seconds to wait for its answer (default 15)\") }],\n [\"daemon stop [--timeout s]\", \"Stop the profile's daemon\", { timeout: o(\"number\", \"Seconds to wait for it to stop (default 20)\") }],\n [\"daemon restart [--timeout s]\", \"Stop the profile's daemon and start it again in the background (after an upgrade: the new code)\", { timeout: o(\"number\", \"Seconds to wait for each step\") }],\n [\"listen [--since seq] [--cursor file] [--type t]... [--turns] [--from <chat|key>]... [--group <group>]... [--exec cmd] [--webhook url] [--print] [--translate lang]\", \"Stream events as JSON lines (starts the profile here if no daemon runs it)\", {\n since: o(\"number\", \"Replay events after this seq first (with --cursor: only while its file holds no seq yet)\"), cursor: o(\"string\", \"A file that keeps the last seq handled (read at start, written after each event); its seq wins over --since\"),\n type: o(\"list\", \"Only events of this type (message.received) or family (message, or group.typing.); repeat for more\"),\n turns: o(\"boolean\", \"Only agent turns: each message received, and each group message that mentions you, as one agent.turn event\"),\n from: o(\"list\", \"Only this chat's events (id, a label given here or the contact's key; again for more)\"),\n group: o(\"list\", \"Only this group's events (again for more); with --from or --group, nobody else's event gets through\"),\n exec: o(\"string\", \"Run this command per event, the event as JSON on stdin\"),\n webhook: o(\"string\", \"POST each event to this URL (else GHOSTLY_WEBHOOK, which ps does not show)\"), print: o(\"boolean\", \"Print events too when --exec or --webhook handles them\"),\n translate,\n }],\n [\"settings get [--show-secret]\", \"The profile's settings: each key settings set takes with its value in effect (unset: the default)\", { \"show-secret\": o(\"boolean\", \"Show credentials too\") }],\n [\"settings set <key> <json-value> [--force]\", \"Change one: relays, irohRelays, hyperdhtRelay, iceServers, publicProfiles, online, shareProfile, sendTyping, autoDownloads, serveFiles, daemonPresence, nick. daemonPresence true: contacts see this profile online while a daemon runs it (off by default). <json-value> - (or none, piped) reads it from stdin: a TURN password stays out of ps\", { force: o(\"boolean\", \"Set a nick even if it looks like a seed, a key or ecash\") }],\n [\"engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]\", \"Any call of the app's engine, with its own parameters (engine --list --verbose names them)\", { \"confirm-real\": o(\"boolean\", \"Confirm a Mainnet (real money) spend\"), \"show-secret\": o(\"boolean\", \"Print a call's secrets\"), yes: o(\"boolean\", \"Confirm a call that deletes chats or groups\"), force: o(\"boolean\", \"Send a text that looks like a secret, or remove a chat (or clear the profile) while a delete for everyone has not reached the contact\") }],\n [\"engine --list [--verbose]\", \"The engine's calls\", { verbose: o(\"boolean\", \"With what each call takes: { linkId, label }, ? for an optional one\") }],\n [\"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)\"],\n [\"identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]\", \"Make an identity proof (a tool's or a published one finishes with identity complete)\", {\n signer: o(\"string\", \"Which signer makes the proof (identity providers lists them)\"), field: o(\"list\", \"A field of the provider's form, name=value\"),\n stdin: o(\"boolean\", \"Take the fields as name=value lines on stdin (a signer's link: out of ps and the shell's history)\"),\n days: o(\"number\", \"How long the proof holds\"), timeout: o(\"number\", \"Seconds to wait for an approval\"),\n }],\n [\"version\", \"This CLI's version (also ghostly --version)\"],\n];\n\n/** A command's words before its arguments: \"group send\", \"send\", \"engine\". */\nconst wordsOf = (usage: string) => usage.split(\" \").filter((w) => /^[a-z][\\w-]*$/.test(w)).slice(0, 2);\n\n/**\n * `rows`, then each of `more` beside the rows of its first word: after the last of them (`group send` with the group\n * commands, `identity add` with the identity ones), or at the end when none has that word. They were all appended after\n * the table: `group send` 106 lines below the group block, `identity add` 60 below its own (agents#1606).\n */\nfunction beside(rows: [string, string][], more: [string, string][]): [string, string][] {\n const out = [...rows];\n for (const row of more) {\n const [first, second] = wordsOf(row[0]);\n let at = -1;\n if (second !== undefined) for (let i = out.length - 1; i >= 0; i--) if (wordsOf(out[i][0])[0] === first && wordsOf(out[i][0]).length > 1) { at = i; break; }\n out.splice(at < 0 ? out.length : at + 1, 0, row);\n }\n return out;\n}\n\n/**\n * The width the help is laid out to: $COLUMNS, else the terminal's when stdout is one (80 when it says nothing), else\n * none: piped, each row stays one line for grep. At a fixed 58-column usage, 170 of the 195 lines of `ghostly help` passed\n * 80 columns, and an 80-column terminal broke every summary mid-word into column 0.\n */\nfunction helpColumns(): number | undefined {\n const given = Number(process.env.COLUMNS);\n if (Number.isInteger(given) && given > 0) return given;\n return process.stdout.isTTY ? process.stdout.columns || 80 : undefined;\n}\n\n/** `prefix`, then `text`'s words in lines of at most `columns` (a longer word alone), each after the first `indent` in. */\nfunction wrap(prefix: string, text: string, columns: number, indent: number): string[] {\n const lines: string[] = [];\n let line = prefix, started = false;\n for (const word of text.trim().match(/\\S+ */g) ?? []) {\n if (started && (line + word.trimEnd()).length > columns) { lines.push(line.trimEnd()); line = \" \".repeat(indent); }\n line += word;\n started = true;\n }\n return [...lines, line.trimEnd()];\n}\n\n/** Lines of text as written, or, laid out to `columns` and one of them wider, as one paragraph wrapped at their indent. */\nfunction paragraph(lines: string[], columns: number | undefined): string[] {\n if (columns === undefined || lines.every((line) => line.length <= columns)) return lines;\n const indent = lines[0].length - lines[0].trimStart().length;\n return wrap(\" \".repeat(indent), lines.join(\" \"), columns, indent);\n}\n\n/**\n * A help row: `label` (a usage or an option, with its indent), its `text` from column `at`, or under the label when the\n * label takes that room. Laid out to `columns`, the text wraps at its column; with under 40 columns left for it (an\n * 80-column terminal beside the 58 of a usage), it goes under its label, 2 further in.\n */\nfunction helpRow(label: string, text: string, at: number, columns: number | undefined): string[] {\n const long = label.length > at - 2;\n if (columns === undefined) return [long ? `${label}\\n${\" \".repeat(at)}${text}` : label.padEnd(at) + text];\n const indent = label.length - label.trimStart().length;\n const labelLines = wrap(\" \".repeat(indent), label, columns, indent + 4);\n if (columns - at < 40) return [...labelLines, ...wrap(\" \".repeat(indent + 2), text, columns, indent + 2)];\n if (long) return [...labelLines, ...wrap(\" \".repeat(at), text, columns, at)];\n return wrap(label.padEnd(at), text, columns, at);\n}\n\n/**\n * What `ghostly` says first in a Ghostly folder with no profile yet: where to start, as the README's \"Five minutes\"\n * does, before the whole list. `$ ` keeps the lines apart from the list's commands. The join pipes the invite in, as\n * docs/CLI.md does: `invite join -` waits for stdin a pipe gives, and a terminal is refused it.\n */\nconst FIRST_STEPS = [\n \"First steps:\",\n \" $ ghostly invite create --label alice make an invite for a contact\",\n \" $ printf '%s' \\\"$INVITE\\\" | ghostly invite join join one, from stdin\",\n \" $ ghostly daemon --detach keep the profile online\",\n \" $ ghostly help <command> one command and its options\",\n];\n\nfunction help(firstSteps = false): string {\n const columns = helpColumns();\n const rows: [string, string][] = [\n ...beside([\n ...SPECIAL.slice(0, 7).map(([usage, summary]) => [usage, summary] as [string, string]),\n ...Object.values(COMMANDS).filter((c) => c.method !== \"events.replay\").map((c) => [c.usage, c.summary] as [string, string]),\n ], [\n ...Object.values(TEXT_COMMANDS).map((c) => [c.usage, c.summary] as [string, string]),\n ...SPECIAL.slice(7).map(([usage, summary]) => [usage, summary] as [string, string]),\n ]),\n [COMMANDS.events.usage, COMMANDS.events.summary],\n ];\n const width = 58;\n return [\n ...paragraph([`ghostly ${VERSION}: Ghostly for bots and terminals, the app's own engine without a screen.`], columns),\n \"\",\n ...(firstSteps ? [...FIRST_STEPS, \"\"] : []),\n ...paragraph([\"Usage: ghostly <command> [options] (JSON on stdout; errors as {\\\"error\\\":{code,message}} with an exit code)\"], columns),\n \"\",\n ...rows.flatMap(([usage, summary]) => helpRow(` ${usage}`, summary, width + 4, columns)),\n \"\",\n \"Options for every command:\",\n ...Object.entries(GLOBAL_OPTIONS).flatMap(([name, o]) => helpRow(` --${name}${o.short ? `, -${o.short}` : \"\"}`, o.description, 24, columns)),\n \"\",\n ...paragraph([\n \"A <chat> is its id, a unique prefix of it, or its name; a <group> the same. Exit codes: 0 done, 1 failed,\",\n \"2 usage, 3 not found, 4 timed out, 5 needs --force/--yes/--confirm-real, 130 stopped with Ctrl-C.\",\n ], columns),\n ...paragraph([\"More: https://ghostly.tools/cli, or the README.md beside this CLI.\"], columns),\n ].join(\"\\n\");\n}\n\nconst EVERY_COMMAND = \"Options for every command: --profile, -p <name> --home <dir> --pretty --help, -h\";\n\n/** What `ghostly help help` answers. */\nconst helpUsage = (columns: number | undefined) => [\n \"Usage: ghostly help [<command>...]\", \"\",\n ...paragraph([\" Help for every command, or for one command or a group of them (also ghostly <command> --help)\"], columns), \"\",\n ...paragraph([EVERY_COMMAND], columns),\n].join(\"\\n\");\n\n/** Every command's help row: usage, summary and, for the table and text commands, their options. */\nfunction helpRows(): { usage: string; summary: string; options?: Record<string, OptionSpec> }[] {\n return [\n ...SPECIAL.map(([usage, summary, options]) => ({ usage, summary, options })),\n ...Object.values(COMMANDS),\n ...Object.values(TEXT_COMMANDS),\n ];\n}\n\n/** The words that name a command in its usage line: up to the first argument or option. */\nfunction commandWords(usage: string): string[] {\n const words: string[] = [];\n for (const word of usage.split(\" \")) {\n if (!/^[a-z][a-z0-9-]*$/.test(word)) break;\n words.push(word);\n }\n return words;\n}\n\n/**\n * A command that takes no argument and is also a group (`status`, with `status set`; `daemon`, with `daemon stop`): a\n * word after it that names none of its commands is a typo of one (`status shwo`). Before, the line said \"Too many\n * arguments: ghostly status\" and `help status shwo` answered status's help with exit 0.\n */\nfunction groupWithNoArguments(usage: string): boolean {\n const words = commandWords(usage), rest = usage.split(\" \").slice(words.length);\n return !rest.some((word) => /^[<[](?!-)/.test(word)) && helpRows().some((row) => { const own = commandWords(row.usage); return own.length > words.length && words.every((word, i) => own[i] === word); });\n}\n\n/**\n * Help for one command (`ghostly help file send`, `ghostly file send --help`): its usage, what it does and its\n * options; for a group (`ghostly help file`), the group's commands.\n */\nexport function commandHelp(words: readonly string[]): string {\n // `help` is no command of the tables: its own usage, rather than \"Unknown command: help\".\n const columns = helpColumns();\n if (words[0] === \"help\") return helpUsage(columns);\n const named = (list: readonly string[]) => helpRows().filter((row) => { const own = commandWords(row.usage); return list.every((word, i) => own[i] === word); });\n // Arguments after the command's words (`ghostly send bob hi --help`) are not part of its name.\n const given = words;\n let rows = named(words);\n while (!rows.length && words.length > 1) rows = named(words = words.slice(0, -1));\n const asked = words.join(\" \");\n if (!rows.length) throw unknownCommand(given[0], given[1], given[2]);\n const exact = rows.filter((row) => commandWords(row.usage).join(\" \") === asked);\n // Words dropped down to a group, not a command (`help chat histroy`): a word the group does not take, as `chat histroy`\n // says, not the group's list with exit 0.\n if (words.length < given.length && (!exact.length || exact.every((row) => groupWithNoArguments(row.usage)))) throw unknownCommand(given[0], given[1], given[2]);\n const lines: string[] = [];\n // The command asked for first, also when others extend its words (`daemon`, then `daemon stop`…): before, `daemon`'s\n // own options were shown nowhere.\n for (const row of exact) {\n lines.push(...(columns === undefined ? [`Usage: ghostly ${row.usage}`] : wrap(\"Usage: ghostly \", row.usage, columns, 4)), \"\", ...paragraph([` ${row.summary}`], columns));\n const options = Object.entries(row.options ?? {}).filter(([, o]) => o.description);\n if (options.length) {\n lines.push(\"\", \"Options:\");\n const labels = options.map(([name, o]) => ` --${o.negatedOnly ? \"no-\" : \"\"}${name}${o.type === \"boolean\" ? \"\" : ` <${o.type === \"number\" ? \"n\" : \"value\"}>`}`);\n // At least two spaces between an option and its text, however long the option.\n const width = Math.max(26, ...labels.map((label) => label.length + 2));\n options.forEach(([, o], i) => lines.push(...helpRow(labels[i], o.description, width, columns)));\n }\n // A text that starts with a dash goes after `--`, and so does everything else on the line.\n if (Object.values(TEXT_COMMANDS).includes(row as (typeof TEXT_COMMANDS)[string]))\n 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));\n lines.push(\"\");\n }\n const rest = rows.filter((row) => !exact.includes(row));\n if (rest.length) {\n const width = Math.min(58, Math.max(...rest.map((row) => row.usage.length)));\n const count = `${rest.length}${exact.length ? \" more\" : \"\"} command${rest.length === 1 ? \"\" : \"s\"}`;\n lines.push(...paragraph([`ghostly ${asked}: ${count} (ghostly help ${asked} <command> for one)`], columns), \"\");\n for (const row of rest) lines.push(...helpRow(` ${row.usage}`, row.summary, width + 4, columns));\n lines.push(\"\");\n }\n lines.push(...paragraph([EVERY_COMMAND], columns));\n return lines.join(\"\\n\");\n}\n\n// ---------- commands with their own flow ----------\n\nasync function profileCommand(sub: string | undefined, argv: string[]): Promise<void> {\n const specs: Record<string, Record<string, OptionSpec>> = {\n create: { use: { type: \"boolean\", description: \"\" }, name: { type: \"string\", description: \"\" }, force: { type: \"boolean\", description: \"\" } },\n backup: { out: { type: \"string\", description: \"\" }, \"passphrase-file\": { type: \"string\", description: \"\" }, passphrase: { type: \"boolean\", description: \"\" }, light: { type: \"boolean\", description: \"\" } },\n restore: { \"passphrase-file\": { type: \"string\", description: \"\" }, use: { type: \"boolean\", description: \"\" } },\n set: { name: { type: \"string\", description: \"\" }, \"share-profile\": { type: \"boolean\", description: \"\", eitherWay: true }, force: { type: \"boolean\", description: \"\" } },\n };\n let parsed: Parsed;\n try {\n parsed = parseArgs(argv, specs[sub ?? \"\"] ?? {}, undefined, { command: commandOf(\"profile\", sub) });\n } catch (e) {\n // A passphrase on the line gets the words for it whichever way it comes. Before, `--passphrase=<secret>` was\n // \"--passphrase takes no value\" on backup (as if it took one) and restore's every form \"Unknown option --passphrase\".\n if ((sub === \"backup\" || sub === \"restore\") && passphraseOnLine(argv)) throw new CliError(\"usage\", PASSPHRASE_ON_LINE);\n throw e;\n }\n // These replace or list `<home>/current`: a name there that is no profile's does not stop them, they are the way out.\n const g = globals(parsed, { ownProfile: [\"create\", \"list\", \"use\", \"restore\"].includes(sub ?? \"\") });\n pretty = g.pretty;\n switch (sub) {\n case \"create\": {\n const [name] = parsed.positionals;\n if (!name) throw new CliError(\"usage\", \"Missing <name>: ghostly profile create <name> [--use] [--name <shown name>] [--force]\");\n noMoreThan(1, parsed.positionals, \"profile create <name> [--use] [--name <shown name>] [--force]\");\n // A command that fails changes nothing: the name is checked before the folder is made, and the profile is made\n // current only once it holds it. Before, the retry with a good name was refused \"Profile <name> exists\".\n const shownName = parsed.options.name === undefined ? undefined : checkShownNameOption(parsed.options.name as string);\n const force = parsed.options.force === true;\n if (shownName) (await import(\"./secretGuard\")).guardText(shownName, force, \"name\", \"set it\");\n const paths = createProfile(g.home, name);\n let shown: unknown = null;\n if (shownName !== undefined) {\n try {\n shown = await withSession({ ...g, profile: name, paths }, (s) => s.call(\"profile.set\", { name: shownName, force }));\n } catch (e) {\n rmSync(paths.dir, { recursive: true, force: true });\n throw e;\n }\n }\n if (parsed.options.use) selectProfile(g.home, name);\n print({ created: name, folder: paths.dir, current: currentProfileOrNone(g.home) === name, ...(shown ? { profile: shown } : {}) });\n return;\n }\n case \"list\": {\n noMoreThan(0, parsed.positionals, \"profile list\");\n const current = currentProfileOrNone(g.home);\n print({ profiles: listProfiles(g.home).map((name) => ({ name, current: name === current, running: lockOwner(profilePaths(g.home, name)) !== null })), home: g.home });\n return;\n }\n case \"use\": {\n const [name] = parsed.positionals;\n if (!name) throw new CliError(\"usage\", \"Missing <name>: ghostly profile use <name>\");\n noMoreThan(1, parsed.positionals, \"profile use <name>\");\n selectProfile(g.home, name);\n // The profile the next commands run on, as `profile create --use` says it: GHOSTLY_PROFILE still picks another.\n const current = currentProfile(g.home);\n if (current !== name) process.stderr.write(`ghostly: GHOSTLY_PROFILE=${current} still picks the profile in this shell: unset it to use ${name}.\\n`);\n print({ current });\n return;\n }\n case \"show\":\n noMoreThan(0, parsed.positionals, \"profile show\");\n print(await withSession(g, (s) => s.call(\"profile.get\"), { offline: true, deferChats: readsNoHistory(\"profile.get\") }));\n return;\n case \"set\": {\n noMoreThan(0, parsed.positionals, \"profile set [--name <name>] [--share-profile | --no-share-profile] [--force]\");\n const params: Record<string, unknown> = {};\n // Checked before the profile opens, so a bad --name is a usage error naming it; the engine takes it as given.\n if (parsed.options.name !== undefined) {\n checkShownNameOption(parsed.options.name as string);\n params.name = parsed.options.name;\n }\n if (parsed.options[\"share-profile\"] !== undefined) params.shareProfile = parsed.options[\"share-profile\"];\n if (!Object.keys(params).length) throw new CliError(\"usage\", \"Nothing to change: ghostly profile set [--name <name>] [--share-profile | --no-share-profile] [--force]\");\n if (parsed.options.force === true) params.force = true;\n print(await withSession(g, (s) => s.call(\"profile.set\", params)));\n return;\n }\n case \"backup\": {\n // Before the positionals are counted: `--passphrase <secret>` was \"Too many arguments\", the secret read as one.\n if (parsed.options.passphrase === true) throw new CliError(\"usage\", PASSPHRASE_ON_LINE);\n noMoreThan(0, parsed.positionals, \"profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light]\");\n const out = parsed.options.out;\n if (typeof out !== \"string\") throw new CliError(\"usage\", \"Missing --out: ghostly profile backup --out <file> [--passphrase-file f | --no-passphrase] [--light]\");\n // Encrypted unless --no-passphrase says otherwise, and never a guess: a passphrase and --no-passphrase together are refused.\n const unsealed = parsed.options.passphrase === false;\n if (unsealed && (parsed.options[\"passphrase-file\"] !== undefined || 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\");\n const light = parsed.options.light === true ? { light: true } : {};\n // The passphrase is read before the profile opens, and the backup only reads the store: offline.\n // A separator at its end names a folder: kept for the backup to refuse, as resolving the path drops it. Before,\n // \"--out backups/\" with no backups folder wrote the backup as a file named backups.\n const resolved = here(out) as string, path = (out.endsWith(\"/\") || out.endsWith(sep)) && !resolved.endsWith(sep) ? `${resolved}${sep}` : resolved;\n // The folder it goes in, as the backup checks it (backup.ts): a missing one is named before the profile opens.\n if (!path.endsWith(sep) && !localStat(dirname(path)).isDirectory()) throw new CliError(\"not_found\", `No such file or folder: ${dirname(path)}`);\n const params = unsealed ? { path, noPassphrase: true, ...light } : { path, passphrase: cleanEnds(await backupPassphrase(parsed.options[\"passphrase-file\"]), parsed.options[\"passphrase-file\"]), ...light };\n const made = await withSession(g, (s) => s.call(\"profile.backup\", params), { offline: true });\n if (unsealed) process.stderr.write(\"ghostly: Not encrypted: this file holds the profile's keys, chats and wallet secrets in the clear. Anyone who gets it gets everything in it, including any money in its wallets.\\n\");\n print(made);\n return;\n }\n case \"restore\": {\n const [given, name] = parsed.positionals;\n if (!given || !name) throw new CliError(\"usage\", `Missing <${given ? \"new profile\" : \"file\"}>: ghostly profile restore <file> <new profile> [--passphrase-file f] [--use]`);\n noMoreThan(2, parsed.positionals, \"profile restore <file> <new profile> [--passphrase-file f] [--use]\");\n // A backup made without a passphrase says so in its header: none is asked for, and the answer says it was not protected.\n const file = here(given) as string;\n const { backupFileProtection, restoreProfile } = await import(\"./backup\");\n const protection = await backupFileProtection(file);\n const paths = await restoreProfile(g.home, checkProfileName(name), file, protection === \"none\" ? undefined : await backupPassphrase(parsed.options[\"passphrase-file\"], RESTORE_PASSPHRASE));\n if (parsed.options.use) selectProfile(g.home, name);\n // Whether --use made it the current profile, as profile create says it.\n print({ restored: name, folder: paths.dir, protection, current: currentProfileOrNone(g.home) === name });\n return;\n }\n default:\n throw unknownCommand(\"profile\", sub);\n }\n}\n\n/**\n * A clean stop (peers told goodbye, the store folded), once; a second signal, or a stop that takes longer than\n * 20 s, leaves at once. The store's journal makes that safe.\n */\nfunction stopper(work: () => Promise<void>): () => void {\n let started = false;\n return () => {\n if (started) process.exit(1);\n started = true;\n setTimeout(() => process.exit(1), 20_000).unref();\n void work().then(() => process.exit(0), () => process.exit(1));\n };\n}\n\n/**\n * Ctrl-C, a service manager's stop, and the terminal or SSH session it ran in closing (SIGHUP, which would otherwise\n * end it on the spot): each a clean stop.\n */\nfunction onStopSignals(stop: () => void): void {\n for (const signal of [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const) process.on(signal, stop);\n}\n\nconst BACKUP_PASSPHRASE = \"The backup passphrase comes from --passphrase-file or GHOSTLY_BACKUP_PASSPHRASE (at least 12 characters). For a backup that is not encrypted, say so with --no-passphrase\";\n/** Restore takes no --no-passphrase: a backup made without one says so itself. */\nconst RESTORE_PASSPHRASE = \"This backup is encrypted: its passphrase comes from --passphrase-file or GHOSTLY_BACKUP_PASSPHRASE\";\nconst PASSPHRASE_ON_LINE = \"The passphrase comes from --passphrase-file or GHOSTLY_BACKUP_PASSPHRASE, never the command line\";\n/**\n * `--passphrase` or `--passphrase=<value>` before any `--` (after it, words are positionals), or a typo of it\n * (`--pasphrase=<value>`): before, that was \"did you mean --passphrase?\", the one form refused here.\n */\nconst passphraseOnLine = (argv: readonly string[]): boolean => {\n const end = argv.indexOf(\"--\");\n return (end === -1 ? argv : argv.slice(0, end)).some((arg) => arg.startsWith(\"--\") && nearest(arg.slice(2).split(\"=\")[0], [\"passphrase\"]) === \"passphrase\");\n};\n\n/**\n * The backup passphrase: from a file or the environment, never the command line (it would sit in shell history). The\n * file is said as every other file the CLI reads: \"\" names none, a folder is named, and an empty one is called that,\n * not \"comes from --passphrase-file\" to someone who gave it. \"-\" is stdin, as for every other secret the CLI takes (a\n * pipe from a password manager); a terminal is refused, as it would show the passphrase as it is typed.\n */\nasync function backupPassphrase(file: unknown, missing = BACKUP_PASSPHRASE): Promise<string> {\n if (typeof file !== \"string\") {\n const value = process.env.GHOSTLY_BACKUP_PASSPHRASE;\n if (!value) throw new CliError(\"usage\", missing);\n return value;\n }\n if (file === \"-\" && process.stdin.isTTY) throw new CliError(\"usage\", \"--passphrase-file - reads stdin: pipe the passphrase in (… | ghostly profile …), or name a file\");\n let value: string;\n if (file === \"-\") value = (await readStdin()).replace(/\\r?\\n$/, \"\");\n else try { value = readFileSync(here(file) as string, \"utf8\").replace(/\\r?\\n$/, \"\"); } catch (error) { throw localFileError(error, file) ?? error; }\n if (!value) throw new CliError(\"bad_request\", `${file === \"-\" ? \"Stdin\" : file} is empty: it holds the backup's passphrase`);\n return value;\n}\n\nconst END_NAMES: Record<string, string> = { \" \": \"a space\", \"\\t\": \"a tab\", \"\\r\": \"a carriage return\", \"\\n\": \"a line break\", \"\\uFEFF\": \"a byte order mark\" };\nconst endName = (char: string) => END_NAMES[char] ?? `U+${char.codePointAt(0)!.toString(16).toUpperCase().padStart(4, \"0\")} (a space)`;\n\n/**\n * A new backup's passphrase, refused when it starts or ends with whitespace or a byte order mark, or holds a NUL (a\n * file saved as UTF-16): only the one line break at a file's end is left out, so the same passphrase typed, pasted or\n * held by a password manager would open nothing (\"Wrong passphrase\"). Restore takes any passphrase: old backups open.\n */\nfunction cleanEnds(passphrase: string, file: unknown): string {\n const source = typeof file !== \"string\" ? \"GHOSTLY_BACKUP_PASSPHRASE\" : file === \"-\" ? \"stdin\" : file;\n if (passphrase.includes(\"\\0\")) throw new CliError(\"bad_request\", `${source} holds a NUL: a file saved as UTF-16? Save the passphrase as UTF-8 text`);\n const trimmed = passphrase.trim();\n if (trimmed === passphrase) return passphrase;\n const at = trimmed && passphrase.startsWith(trimmed) ? \"ends\" : \"starts\";\n const char = at === \"ends\" ? passphrase.at(-1)! : passphrase[0]!;\n const fileRule = typeof file === \"string\" ? \" (one line break at its end is left out already)\" : \"\";\n throw new CliError(\"bad_request\", `The passphrase in ${source} ${at} with ${endName(char)}${fileRule}: the same passphrase typed or pasted would not open the backup. Take it out`);\n}\n\n/** Set on `startDetached`'s child: its parent waits for the profile and starts it again, so the child does not wait too. */\nconst DETACHED_CHILD = \"GHOSTLY_DAEMON_DETACHED\";\n\n/**\n * 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\n * service manager's restart) is waited for until `seconds`, as `daemon --detach` waits for it: the first look used to be\n * the answer, and the profile was left with no daemon. A daemon that comes up meanwhile is the answer instead.\n */\nasync function runDaemon(g: Globals, seconds: number): Promise<void> {\n requireProfile(g);\n const detached = process.env[DETACHED_CHILD] === \"1\";\n delete process.env[DETACHED_CHILD]; // not handed to the hooks it runs\n dropSecretEnv(); // a backup's passphrase comes as a call parameter: nothing the daemon runs gets it\n const { keepServing, openHost, serve } = await engineHost();\n const until = performance.now() + seconds * 1000;\n let host: Host;\n for (;;) {\n await noDaemonAnswers(g, detached);\n try { host = await openHost(g.paths, \"daemon\", VERSION); break; }\n catch (error) {\n if (detached) throw childAnswer(detached, error);\n if (!(error instanceof CliError) || error.code !== \"busy\" || performance.now() >= until) throw error;\n await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(100, until - performance.now()))));\n }\n }\n let served: Awaited<ReturnType<typeof serve>>;\n try { served = await serve(host); } catch (error) { await host.close(); throw childAnswer(detached, error); }\n keepServing();\n const stop = stopper(async () => { await served.close(); await host.close(); });\n host.ctx.stop = stop;\n onStopSignals(stop);\n host.ctx.hub.emit(\"daemon.started\", `daemon.started:${process.pid}:${Date.now()}`, { pid: process.pid, version: VERSION });\n print({ daemon: \"ready\", profile: g.profile, pid: process.pid, socket: g.paths.socket, lastSeq: host.ctx.hub.lastSeq });\n}\n\n/**\n * Throws busy when something answers on the profile's socket while a process holds the profile (a daemon starts only\n * then). With nobody holding it, what answers is no daemon: the start said one ran, and the refusal names the way out.\n */\nasync function noDaemonAnswers(g: Globals, detached = false): Promise<void> {\n const client = await connectDaemon(g.paths);\n if (!client) return;\n client.close();\n throw childAnswer(detached, lockOwner(g.paths) === null ? notTheDaemon(g.paths, false) : new CliError(\"busy\", `A daemon already runs profile ${g.profile}`));\n}\n\n/**\n * A detached child's answer carries its own pid (`child`): its parent reads it in `daemon.log`, where every daemon of\n * the profile writes, and another detach's child that lost the profile, or refused to start, writes there too.\n */\nfunction childAnswer(detached: boolean, error: unknown): unknown {\n if (!detached) return error;\n const failure = asCliError(error);\n return new CliError(failure.code, failure.message, { ...failure.details, child: process.pid });\n}\n\nasync function daemonCommand(argv: string[]): Promise<void> {\n const sub = argv[0] && !argv[0].startsWith(\"-\") ? argv[0] : undefined;\n const parsed = parseArgs(sub ? argv.slice(1) : argv, { detach: { type: \"boolean\", description: \"\" }, timeout: { type: \"number\", description: \"\" } }, undefined, { command: commandOf(\"daemon\", sub) });\n const g = globals(parsed);\n pretty = g.pretty;\n if (!sub || [\"status\", \"stop\", \"restart\"].includes(sub)) noMoreThan(0, parsed.positionals, sub ? `daemon ${sub} [--timeout s]` : \"daemon [--detach] [--timeout s]\");\n if (sub === \"status\") {\n knownProfile(g);\n const client = await connectDaemon(g.paths);\n // The socket, running or not: a program on the socket API (examples/*.mjs) finds it here. It is in the profile's\n // folder, or in /tmp/ghostly-<hash>/ when that path is too long for a socket, so a program cannot guess it.\n // A daemon still starting (its engine, before its socket listens) holds the profile already: it is no one-shot's.\n if (!client) {\n const starting = startingDaemon(g.paths);\n print({ running: false, ...(starting === null ? {} : { starting: true, pid: starting }), profile: g.profile, socket: g.paths.socket });\n return;\n }\n try { print({ running: true, ...(await client.call(\"status\", {}, { timeoutMs: seconds(parsed, 15) * 1000 }) as object), socket: g.paths.socket }); } finally { client.close(); }\n return;\n }\n if (sub === \"stop\") {\n knownProfile(g);\n const stopFor = seconds(parsed, 20);\n // A daemon of an older release never greets: what does not prove itself is stopped as the process that holds the\n // profile (`stopDaemon`), as the stop asked. One of this release that greets late is busy: the stop's deadline waits.\n const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);\n if (!client) throw new CliError(\"not_found\", `No daemon runs profile ${g.profile}`);\n const { pid, listen } = await stopDaemon(g, client, stopFor);\n if (listen) process.stderr.write(listenEnded(pid));\n print({ stopped: true, pid, ...(listen && { listen: true }) });\n return;\n }\n if (sub === \"restart\") {\n // The running one stops (if one runs), and this command's own code starts in the background. The profile is kept\n // for it from before the stop until it holds the profile (`claimForDaemon`): one-shot commands taking it in turn in\n // between left it never starting, and the profile with no daemon until someone started one by hand.\n const stopFor = seconds(parsed, 20), startFor = seconds(parsed, 60);\n requireProfile(g);\n ownProfile(g.paths.dir);\n const unclaim = claimForDaemon(g.paths);\n try { await restartDaemon(g, stopFor, startFor); } finally { unclaim(); }\n return;\n }\n if (sub) throw unknownCommand(\"daemon\", sub);\n const startFor = seconds(parsed, 60);\n if (!parsed.options.detach) { await runDaemon(g, startFor); return; }\n print(await startDetached(g, startFor));\n}\n\n/** `daemon restart`, while the profile is kept for the daemon it starts. */\nasync function restartDaemon(g: Globals, stopFor: number, startFor: number): Promise<void> {\n const client = await connectDaemon(g.paths) ?? await startedDaemon(g, stopFor);\n // The version it ran is asked ahead of the stop, on the same connection, with no deadline of its own: cosmetic,\n // and the stop's deadline ends it (a deadline here, 15 s, closed the connection under a longer stop, which then\n // failed as `unavailable` and never reached the signals).\n const probe = client ? client.call(\"status\").catch(() => null) as Promise<{ version?: string } | null> : null;\n const ended = client ? await stopDaemon(g, client, stopFor) : null;\n const stopped = ended?.pid ?? null;\n // A listen that ran the profile ended with it: the daemon started below has no reader until one listens again.\n if (ended?.listen) process.stderr.write(listenEnded(ended.pid));\n const before = (await probe)?.version ?? null;\n let started: Awaited<ReturnType<typeof startDetached>>;\n try { started = await startDetached(g, startFor); }\n catch (error) {\n // A start that failed after the stop leaves the profile with no daemon: the answer says so, and how to start one.\n if (stopped === null || !(error instanceof CliError) || error.code === \"timeout\") throw error;\n throw new CliError(error.code, `${error.message}. The daemon (process ${stopped}) was stopped: start it again with ghostly daemon --detach`, { ...error.details, stopped });\n }\n const older = restartWarning(before, VERSION);\n if (older) process.stderr.write(older + \"\\n\");\n print({ restarted: true, stopped, ...(ended?.listen && { listen: true }), before, version: VERSION, ...started });\n}\n\n/**\n * The profile's daemon that is starting (`startingDaemon`: it holds the profile, its socket does not listen yet), once\n * its socket answers, waited for up to `seconds`; null when none is starting. One still starting then is the answer,\n * `timeout` with its pid. `daemon stop` said no daemon ran, and the daemon came up a moment later; `daemon restart`\n * failed busy and left the old code running.\n */\nasync function startedDaemon(g: Globals, seconds: number): Promise<DaemonClient | null> {\n const until = performance.now() + seconds * 1000;\n for (;;) {\n // Read before the socket is tried: a daemon whose socket listens in between is found by the try.\n const pid = startingDaemon(g.paths);\n const client = await connectDaemon(g.paths);\n if (client) return client;\n if (pid === null) return null;\n const left = until - performance.now();\n 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 });\n await new Promise((resolve) => setTimeout(resolve, Math.min(100, left)));\n }\n}\n\n/** `--timeout <s>`, or `fallback` without one: seconds above 0 (0 or less would not wait at all). */\nfunction seconds(parsed: Parsed, fallback: number): number {\n const value = parsed.options.timeout;\n if (value === undefined) return fallback;\n if (typeof value !== \"number\" || !(value > 0)) throw new CliError(\"usage\", \"--timeout takes a number of seconds above 0\");\n return value;\n}\n\n/**\n * Asks the daemon to stop and waits until its process is gone, not only until it let go of the profile (it releases\n * the lock a moment before it exits); its pid. One that does not answer the ask in `seconds` (its event loop wedged)\n * is sent SIGTERM, and SIGKILL when that did not end it either in as long: `daemon restart` then starts a fresh one,\n * as the timeout error promises. The pid is the profile lock's holder, which a daemon writes itself. On Windows\n * `process.kill` with either name is TerminateProcess: the first signal ends it, there is no second.\n */\nasync function stopDaemon(g: Globals, client: DaemonClient, seconds: number): Promise<{ pid: number; listen: boolean }> {\n let pid: number, answered = true, listen = false;\n try { ({ pid, listen = false } = await client.call(\"daemon.stop\", {}, { timeoutMs: seconds * 1000 }) as { pid: number; listen?: boolean }); }\n catch (error) {\n // What answers on the socket and does not prove it is the profile's daemon is told nothing: a daemon of an older\n // release (it cannot prove it) is stopped as the process that holds the profile's lock, which only this user\n // can write. With nobody holding it, what answers is not the daemon, and the refusal stands, saying what to do.\n const refused = isNotTheDaemon(error);\n if (!(error instanceof CliError && error.code === \"timeout\") && !refused) throw error;\n const holder = lockOwner(g.paths);\n if (holder === null) throw refused ? notTheDaemon(g.paths, false) : error;\n process.stderr.write(refused\n ? `ghostly: what answers on the socket did not prove it is this profile's daemon (an older release's cannot): stopping the process that holds the profile (${holder}) with SIGTERM\\n`\n : `ghostly: the daemon (process ${holder}) did not answer daemon.stop in ${seconds} s: stopping it with SIGTERM\\n`);\n pid = holder;\n answered = false;\n signal(pid, \"SIGTERM\");\n }\n client.close();\n const running = () => lockOwner(g.paths) === pid || processAlive(pid);\n const gone = async () => {\n const until = performance.now() + seconds * 1000;\n while (running()) {\n const left = until - performance.now();\n if (left <= 0) break;\n await new Promise((resolve) => setTimeout(resolve, Math.min(100, left)));\n }\n return !running();\n };\n if (await gone()) return { pid, listen };\n // A wedged event loop runs no SIGTERM handler either.\n if (!answered) {\n process.stderr.write(`ghostly: the daemon (process ${pid}) did not stop on SIGTERM in ${seconds} s: killing it\\n`);\n signal(pid, \"SIGKILL\");\n if (await gone()) return { pid, listen };\n }\n throw new CliError(\"timeout\", `The daemon (process ${pid}) has not stopped yet`, { pid });\n}\n\n/** What `daemon stop` and `restart` say of a daemon that was a `listen` running the profile: that listen is over. */\nfunction listenEnded(pid: number): string {\n 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`;\n}\n\n/** Throws busy, with its pid, when a process other than `except` holds the profile. */\nfunction heldBy(g: Globals, except?: number): void {\n const owner = lockOwner(g.paths);\n if (owner !== null && owner !== except) throw new CliError(\"busy\", `Profile ${g.profile} is in use by process ${owner}`, { pid: owner });\n}\n\n/** Gone already, or not ours to signal: the wait that follows says so. */\nfunction signal(pid: number, name: \"SIGTERM\" | \"SIGKILL\"): void {\n try { process.kill(pid, name); } catch { /* ESRCH, EPERM */ }\n}\n\nfunction processAlive(pid: number): boolean {\n try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === \"EPERM\"; }\n}\n\n/**\n * A daemon in the background, running this command's code, once its socket answers. A one-shot command (or a listen)\n * that opened the profile in process holds it: the child would only log that. One that ends in a moment (a bot's\n * `send` every 200 ms, which takes the profile in the gap of a restart) is waited for, and so is one that took it\n * between the look and the child's start; one that still holds it at `seconds` is the answer, busy with its pid.\n */\nasync function startDetached(g: Globals, seconds: number) {\n requireProfile(g);\n // Before the log is opened in the profile's folder; the child checks again before it takes the profile (`openHost`).\n ownProfile(g.paths.dir);\n // Kept for the child until it holds the profile (`claimForDaemon`; `daemon restart` claimed it before its stop).\n const unclaim = claimForDaemon(g.paths);\n try {\n const until = performance.now() + seconds * 1000;\n for (;;) {\n await noDaemonAnswers(g);\n if (lockOwner(g.paths) === null) {\n const started = await spawnDaemon(g, until);\n if (started) return started;\n }\n if (performance.now() >= until) { heldBy(g); throw new CliError(\"engine\", `The daemon did not start; see ${g.paths.log}`); }\n await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(100, until - performance.now()))));\n }\n } finally { unclaim(); }\n}\n\n/** `startDetached`'s child, or null when another process took the profile ahead of it and there is time to try again. */\nasync function spawnDaemon(g: Globals, until: number) {\n const log = openSync(g.paths.log, \"a\", 0o600), logFrom = fstatSync(log).size;\n const child = spawn(process.execPath, [...process.execArgv, process.argv[1], \"daemon\", \"--home\", g.home, \"--profile\", g.profile], { detached: true, stdio: [\"ignore\", log, log], env: { ...childEnv(process.env), [DETACHED_CHILD]: \"1\" } });\n closeSync(log); // the child has its own\n child.unref();\n const spawned = { error: null as Error | null };\n // A spawn that fails outright (EAGAIN, EMFILE) sets `exitCode` to the errno before the \"error\" event, so the loop below\n // ends on its own; the listener swallows the otherwise uncaught event and keeps the cause for the message.\n child.once(\"error\", (error) => { spawned.error = error; });\n let client: DaemonClient | null = null;\n // Try at once, then every 200 ms, never past `until`: a small `--timeout` gives up near-immediately instead of always\n // waiting one 200 ms poll first (the first try finds no socket yet and returns at once). A child that exited or was\n // killed (SIGABRT on a V8 out-of-memory, the OOM killer) ends the wait too, instead of polling to the deadline.\n while (child.exitCode === null && child.signalCode === null && !spawned.error) {\n const left = until - performance.now();\n if (left <= 0) break;\n client = await connectDaemon(g.paths, Math.min(500, left));\n if (client) break;\n await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(200, until - performance.now()))));\n }\n if (!client) {\n // Another process took the profile between the look and the child's start: it holds it still, or the child's\n // answer in the log says so (a one-shot that already ended). Tried again while there is time. Only a child that\n // ended busy lost it: one that exited 0 or by a signal had it and was stopped (`daemon stop`), and stays stopped.\n const answer = !spawned.error && child.exitCode !== null && child.pid !== undefined ? childAnswerIn(g.paths.log, logFrom, child.pid) : null;\n const lost = !spawned.error && child.exitCode === EXIT.busy && child.pid !== undefined\n && (![null, child.pid].includes(lockOwner(g.paths)) || answer?.code === \"busy\");\n if (lost && performance.now() < until) return null;\n heldBy(g, child.pid);\n // Alive still: it is starting (a large profile takes seconds), not failed, and the profile is its own now.\n if (child.exitCode === null && child.signalCode === null && child.pid !== undefined && processAlive(child.pid)) {\n throw new CliError(\"timeout\", `The daemon (process ${child.pid}) is still starting; ghostly daemon status shows when it is up`, { pid: child.pid, log: g.paths.log });\n }\n // It refused to start (a mistyped GHOSTLY_* value is `usage`, exit 2, as in the foreground): its own answer.\n if (answer) {\n const details: Record<string, unknown> = { ...answer.details, log: g.paths.log };\n delete details.child;\n throw new CliError(answer.code, answer.message, details);\n }\n throw new CliError(\"engine\", spawned.error ? `The daemon could not be spawned: ${spawned.error.message}` : `The daemon did not start; see ${g.paths.log}`);\n }\n client.close();\n return { daemon: \"started\", profile: g.profile, pid: child.pid, socket: g.paths.socket, log: g.paths.log };\n}\n\n/**\n * The error the detached child `pid` answered with, as it wrote it to the log from byte `from` on: `busy` when it found\n * the profile taken, its refusal when it did not start. Another child's line (a detach started at the same time) is\n * not its own. Null when it wrote none (a crash, a signal).\n */\nfunction childAnswerIn(log: string, from: number, pid: number): CliError | null {\n let fd: number;\n try { fd = openSync(log, \"r\"); } catch { return null; }\n try {\n const buffer = Buffer.alloc(64 * 1024);\n const text = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, from)).toString(\"utf8\");\n for (const line of text.split(\"\\n\")) {\n try {\n const { error } = JSON.parse(line) as { error?: { code?: unknown; message?: unknown; details?: Record<string, unknown> } };\n if (error?.details?.child !== pid || typeof error.code !== \"string\" || !Object.hasOwn(EXIT, error.code) || typeof error.message !== \"string\") continue;\n return new CliError(error.code as ErrorCode, error.message, error.details);\n } catch { /* not JSON: the engine's notes */ }\n }\n return null;\n } finally { closeSync(fd); }\n}\n\n/**\n * Nobody reads `listen`'s output any more (`listen | head -n 1`, a `grep -m1` that found its line): it stops as on\n * SIGTERM, exit 0. Through a daemon it died on an 'error' nobody handled; on its own profile it served on with nobody\n * to tell, holding the profile until `daemon stop`. Any other failure of the output is still an error.\n */\nfunction onReaderGone(stop: () => void): void {\n let gone = false;\n process.stdout.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (gone) return;\n if (error.code !== \"EPIPE\") throw error;\n gone = true;\n stop();\n });\n}\n\nasync function listenCommand(argv: string[]): Promise<void> {\n const parsed = parseArgs(argv, {\n since: { type: \"number\", description: \"\" }, cursor: { type: \"string\", description: \"\" }, type: { type: \"list\", description: \"\" },\n exec: { type: \"string\", description: \"\" }, webhook: { type: \"string\", description: \"\" }, print: { type: \"boolean\", description: \"\" },\n from: { type: \"list\", description: \"\" }, group: { type: \"list\", description: \"\" }, turns: { type: \"boolean\", description: \"\" },\n translate: { type: \"string\", description: \"\" },\n }, undefined, { command: \"listen\" });\n // Before the profile opens: `listen bob` (meant as `--from bob`) streams nobody's events instead of everybody's.\n noMoreThan(0, parsed.positionals, SPECIAL.find(([usage]) => usage.startsWith(\"listen \"))![0]);\n // Before the profile opens: a unit file's `--webhook \"$URL\"` with URL unset ran a plain listen, no hook and no word.\n const blank = (value: unknown) => typeof value === \"string\" && value.trim() === \"\";\n if (blank(parsed.options.webhook)) throw new CliError(\"usage\", \"--webhook needs a URL\");\n // GHOSTLY_WEBHOOK: the URL out of `ps`, where a long-running listen's arguments (a bridge's token in the URL) are\n // every local account's to read. Read once, here; no hook or other child gets it (SECRET_ENV).\n const envWebhook = process.env.GHOSTLY_WEBHOOK;\n delete process.env.GHOSTLY_WEBHOOK;\n if (envWebhook !== undefined && parsed.options.webhook !== undefined) throw new CliError(\"usage\", \"A webhook is set in GHOSTLY_WEBHOOK and --webhook was given: choose one\");\n if (blank(envWebhook)) throw new CliError(\"usage\", \"GHOSTLY_WEBHOOK is empty: it holds the webhook's URL\");\n const webhook = (parsed.options.webhook as string | undefined) ?? envWebhook;\n if (blank(parsed.options.exec)) throw new CliError(\"usage\", \"--exec needs a command\");\n if (parsed.options.cursor === \"\") throw new CliError(\"usage\", \"--cursor needs a file\");\n if ((parsed.options.from as string[] | undefined)?.some(blank)) throw new CliError(\"usage\", \"--from needs a chat or a contact key\");\n if ((parsed.options.group as string[] | undefined)?.some(blank)) throw new CliError(\"usage\", \"--group needs a group\");\n const g = globals(parsed);\n pretty = false; // one event per line\n if (webhook !== undefined) {\n const url = checkWebhook(webhook, envWebhook !== undefined ? \"GHOSTLY_WEBHOOK\" : \"--webhook\");\n if (envWebhook === undefined && (url.search || url.pathname !== \"/\")) process.stderr.write(\"ghostly: --webhook's URL shows in ps to every account on this machine while listen runs, a token in it too: give it in GHOSTLY_WEBHOOK instead\\n\");\n }\n const types = (parsed.options.type as string[] | undefined) ?? [];\n const turns = parsed.options.turns === true;\n if (turns && types.length) throw new CliError(\"usage\", \"--turns takes the place of --type: a turn is a message received, or a group message that mentions you\");\n checkTypes(types, (line) => process.stderr.write(line + \"\\n\"));\n const from = (parsed.options.from as string[] | undefined) ?? [], groups = (parsed.options.group as string[] | undefined) ?? [];\n const cursor = here(parsed.options.cursor);\n // Before the profile opens: a cursor that cannot be written is no per-event warning.\n checkCursor(cursor);\n const starting = startAt(sinceOf(parsed.options), cursor, (line) => process.stderr.write(line + \"\\n\")), since = starting.from;\n // Kept for the whole listen (a model loads once); its process ends with this one.\n const translator = await translatorFor(parsed.options.translate, g.home);\n // A cursor that can no longer be written (a full disk) stops the listener, with the error and its exit code: run on,\n // a restart would hand every event since again (agents#1710). How it stops is the branch's below.\n let quit = (code: number): void => { process.exit(code); };\n const cursorFailed = (error: unknown) => {\n const failure = localFileError(error, cursor) ?? asCliError(error);\n process.stderr.write(`ghostly: could not write the cursor ${cursor}: ${failure.message}. Stopped, so that no event is handed twice\\n`);\n print({ error: failure.toJSON() });\n quit(EXIT[failure.code]);\n };\n const start = async (call: (method: string, params: Record<string, unknown>) => Promise<unknown>, peerOf: (chat: string) => Promise<string | null>) => {\n return eventHandler({\n types, turns,\n translate: translator?.event,\n exec: parsed.options.exec as string | undefined,\n profile: { home: g.home, name: g.profile },\n webhook,\n cursor,\n cursorFailed,\n // With a hook, events go to the hook; --print shows them too.\n print: parsed.options.print === true || (!parsed.options.exec && !webhook),\n write: (line) => process.stdout.write(line + \"\\n\"),\n drained: () => new Promise<void>((resolve) => {\n const done = () => { process.stdout.off(\"drain\", done); process.stdout.off(\"close\", done); resolve(); };\n process.stdout.on(\"drain\", done);\n process.stdout.on(\"close\", done);\n }),\n allow: from.length || groups.length ? await allowlist(from, groups, call, peerOf) : undefined,\n });\n };\n requireProfile(g);\n // With no daemon, this process becomes it (the socket too, so hooks can answer with `ghostly send`). A profile held\n // is waited for as a one-shot waits (`openOneShot`): a daemon starting answers on its socket in a moment, and is\n // followed. A listen started a second too early used to die busy, while one started after followed it for good.\n const opened = await connectDaemon(g.paths) ?? await openOneShot(g, {}, \"daemon\");\n if (opened instanceof DaemonClient) {\n const client = opened;\n await warnVersion(client);\n // The subscription takes the connection: a chat's contact key is asked on a connection of its own.\n const handle = await start((m, p) => client.call(m, p), async (chat) => {\n const c = await connectDaemon(g.paths, 1000);\n if (!c) return null;\n try { return ((await c.call(\"chat.get\", { chat }, { timeoutMs: ANSWER_MS })) as { peer?: string }).peer || null; } finally { c.close(); }\n }).catch((error) => { client.close(); throw error; });\n // Followed until stopped, past a daemon restart and past a feed that fell behind (`followDaemon`); a daemon gone\n // longer than a restart takes (`daemon stop`) is said once on stderr, and so is the one that answers again.\n const following = followDaemon(g.paths, client, handle, since, PAUSE_HOLD_MS, g.profile);\n // A hook at work is given its time, then ended (`EventHandler.stop`): it never runs on after the listen.\n const stop = stopper(async () => { following.close(); await handle.stop(); });\n quit = (code) => { following.close(); process.exit(code); };\n onReaderGone(stop);\n // Before the subscription's answer is awaited: the events it replays can come in the same read, and the first one's\n // hook started before the await went on. A SIGTERM then ended the listen on the spot and left the hook running.\n onStopSignals(stop);\n const answer = await following.subscribed as { lastSeq?: unknown } | null;\n if (typeof answer?.lastSeq === \"number\") starting.known(answer.lastSeq);\n return;\n }\n const [{ keepServing, serve }, { callApi }] = await Promise.all([engineHost(), engineApi()]);\n const host = opened;\n const call = (m: string, p: Record<string, unknown>) => callApi(host.ctx, m, p);\n const handle = await start(call, async (chat) => ((await call(\"chat.get\", { chat })) as { peer?: string }).peer || null).catch(async (error) => { await host.close(); throw error; });\n const served = await serve(host).catch(async (error) => { await host.close(); throw error; });\n keepServing();\n // The hook first: one at work may still answer through this socket (`ghostly send`).\n const stop = stopper(async () => { await handle.stop(); await served.close(); await host.close(); });\n quit = (code) => {\n setTimeout(() => process.exit(code), 20_000).unref();\n void handle.stop().then(() => served.close()).then(() => host.close()).finally(() => process.exit(code));\n };\n // Asked to stop over the socket (`daemon stop`, `daemon restart`, the profile cleared): the events stop with it, so\n // the listen says so and fails. An exit 0 read as \"done\": a service manager restarted nothing, and no line said why.\n host.ctx.listen = true;\n host.ctx.stop = () => {\n 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)`;\n process.stderr.write(`ghostly: ${message}. Start ghostly daemon --detach first, then listen through it: a restart then does not end the listen\\n`);\n print({ error: new CliError(\"unavailable\", message).toJSON() });\n quit(EXIT.unavailable);\n };\n onStopSignals(stop);\n onReaderGone(stop);\n // The hub's listener comes off while the feed is paused, and back after a replay from the last event taken. What a\n // replay gave and the feed did not take yet waits for the resume: one read of the journal per catch-up, not one per\n // pause; the journal is read again only for what came meanwhile.\n let off: (() => void) | null = null, left: GhostlyEvent[] = [];\n const open = (from: number | undefined) => {\n for (;;) {\n const events = left.length ? left : host.ctx.hub.replay(from ?? host.ctx.hub.lastSeq);\n left = [];\n if (!events.length) break;\n for (let i = 0; i < events.length; i++) {\n feed.take(events[i]);\n if (feed.paused) { left = events.slice(i + 1); return; }\n }\n from = feed.since;\n }\n off = host.ctx.hub.onEvent(feed.take);\n };\n const feed = new Feed(handle, since, () => { off?.(); off = null; }, open);\n starting.known(host.ctx.hub.lastSeq);\n open(since);\n host.ctx.hub.emit(\"daemon.started\", `daemon.started:${process.pid}:${Date.now()}`, { pid: process.pid, version: VERSION, listen: true });\n}\n\nasync function engineCommand(argv: string[]): Promise<void> {\n const parsed = parseArgs(argv, { \"confirm-real\": { type: \"boolean\", description: \"\" }, \"show-secret\": { type: \"boolean\", description: \"\" }, yes: { type: \"boolean\", description: \"\" }, force: { type: \"boolean\", description: \"\" }, list: { type: \"boolean\", description: \"\" }, verbose: { type: \"boolean\", description: \"\" } }, undefined, { command: \"engine\" });\n const g = globals(parsed);\n pretty = g.pretty;\n if (parsed.options.list) {\n noMoreThan(0, parsed.positionals, \"engine --list [--verbose]\");\n const methods = [...ENGINE_METHODS, ...ENGINE_READS].sort();\n // `takes`: what each call takes, in ENGINE_PARAMS' words.\n print(parsed.options.verbose ? { methods, takes: Object.fromEntries(methods.map((m) => [m, ENGINE_PARAMS[m] ?? READ_PARAMS[m]])) } : { methods });\n return;\n }\n const [method, raw] = parsed.positionals;\n if (!method) throw new CliError(\"usage\", \"Missing <method>: ghostly engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]\");\n noMoreThan(2, parsed.positionals, \"engine <method> [json-params | -] [--confirm-real] [--show-secret] [--yes] [--force]\");\n if (!ENGINE_METHODS.includes(method) && !ENGINE_READS.includes(method)) throw new CliError(\"not_found\", `The engine has no call ${method} (ghostly engine --list)`);\n const showSecret = parsed.options[\"show-secret\"] === true;\n if (SECRET_RESULTS.has(method) && !showSecret) throw new CliError(\"confirm\", `${method} answers with secrets: add --show-secret to print them`);\n let params: unknown;\n const text = raw === \"-\" ? await readStdin() : raw;\n if (text !== undefined && text.trim()) {\n try { params = JSON.parse(text); } catch { throw new CliError(\"usage\", \"The parameters must be JSON (an object)\"); }\n }\n const confirmReal = parsed.options[\"confirm-real\"] === true;\n if (confirmReal && params && typeof params === \"object\") (params as Record<string, unknown>).confirmedReal = true;\n const yes = parsed.options.yes === true;\n let result = await withSession(g, (s) => s.call(\"engine.call\", { method, params, confirmReal, yes, force: parsed.options.force === true }), { offline: ENGINE_READS.includes(method) });\n if (method === \"getState\" && !showSecret && result && typeof result === \"object\") {\n const { hideStateSecrets } = await engineApi();\n result = hideStateSecrets(result as Parameters<typeof hideStateSecrets>[0]);\n }\n print(hideSecretFields(method, result, showSecret));\n}\n\nasync function settingsCommand(sub: string | undefined, argv: string[]): Promise<void> {\n // A JSON value may start with a dash (`settings set k -- -1`).\n const parsed = parseArgs(argv, { \"show-secret\": { type: \"boolean\", description: \"\" }, force: { type: \"boolean\", description: \"\" } }, undefined, { command: commandOf(\"settings\", sub), text: sub === \"set\" });\n const g = globals(parsed);\n pretty = g.pretty;\n if (sub === \"get\") { noMoreThan(0, parsed.positionals, \"settings get [--show-secret]\"); print(await withSession(g, (s) => s.call(\"settings.get\", { showSecret: parsed.options[\"show-secret\"] === true }), { offline: true, deferChats: readsNoHistory(\"settings.get\") })); return; }\n if (sub === \"set\") {\n const [key, given] = parsed.positionals;\n if (!key) throw new CliError(\"usage\", \"Missing <key>: ghostly settings set <key> <json-value> [--force]\");\n noMoreThan(2, parsed.positionals, \"settings set <key> <json-value> [--force]\");\n // readRelays stays the API's to refuse: it says why the CLI does not follow it.\n const kind = key === \"readRelays\" ? undefined : checkSettingKey(key, (await engineApi()).SETTABLE);\n // `-`, or no value on a pipe: the value from stdin, out of ps and the shell's history (a TURN password).\n const { value, warning } = await settingValue(key, given, readStdin, process.stdin.isTTY === true, (note) => process.stderr.write(`ghostly: ${note}\\n`));\n if (warning) process.stderr.write(`ghostly: ${warning}\\n`);\n let parsedValue: unknown;\n try { parsedValue = JSON.parse(value); } catch { parsedValue = value; }\n // A text setting (nick) keeps the word as given when it reads as JSON of another kind (2024, true, null).\n if (kind === \"string\" && typeof parsedValue !== \"string\") parsedValue = value;\n if (kind) checkSettingValue(key, kind, parsedValue, value);\n const force = parsed.options.force === true ? { force: true } : {};\n printAnswer(await withSession(g, (s) => s.call(\"settings.set\", { [key]: parsedValue, ...force }), { offline: LOCAL_SETTINGS.has(key) }) as Record<string, unknown>);\n return;\n }\n throw unknownCommand(\"settings\", sub);\n}\n\nasync function textCommand(name: string, argv: string[]): Promise<void> {\n const spec = TEXT_COMMANDS[name];\n const parsed = parseArgs(argv, spec.options, idSlot(spec), { command: name, text: true });\n const g = globals(parsed);\n pretty = g.pretty;\n const [target, ...rest] = parsed.positionals;\n // `edit` names the message before the text.\n const [message, ...words] = spec.message ? rest : [undefined, ...rest];\n if (!target || (spec.message && !message)) throw new CliError(\"usage\", `Missing <${target ? \"message\" : spec.target}>: ghostly ${spec.usage}`);\n // Before stdin is read and the profile opens: the API's own check answered once a one-shot was online (exit 1).\n timeout(parsed.options);\n // Empty (an unset variable in a script), it sent a plain message: an id the chat lacks is exit 3.\n if (parsed.options.reply === \"\") throw new CliError(\"usage\", \"--reply needs a message id\");\n // Stdin only when no text word was given at all: `send bob \"$line\"` with an empty line is no text, not the rest of stdin.\n let text = words.join(\" \");\n if (parsed.options.text !== undefined) {\n if (text || parsed.options.stdin) throw new CliError(\"usage\", \"Give the text once: as arguments, --text or stdin\");\n text = String(parsed.options.text);\n } else if (parsed.options.stdin || (words.length === 0 && !process.stdin.isTTY)) {\n if (text) throw new CliError(\"usage\", \"Give the text as arguments or on stdin, not both\");\n // What the note and the give-up name: the command as typed (a name with a space, quoted).\n const typed = [name, ...[target, ...(message !== undefined ? [message] : [])].map((word) => /^[\\w@.:+-]+$/.test(word) ? word : `'${word.replaceAll(\"'\", \"'\\\\''\")}'`)].join(\" \");\n text = await textFromStdin(readStdin, typed, parsed.options.stdin === true, (note) => process.stderr.write(`ghostly: ${note}\\n`));\n }\n if (!text.trim()) throw new CliError(\"usage\", `No text: ghostly ${spec.usage}`);\n const params: Record<string, unknown> = { [spec.target]: target, text, force: parsed.options.force === true, ...(message !== undefined && { message }) };\n if (spec.target === \"group\") params.mentions = parsed.options.mention ?? [];\n if (parsed.options.reply !== undefined) params.reply = parsed.options.reply;\n if (!spec.message) Object.assign(params, (await import(\"./buttons\")).buttonsOf(parsed.options));\n print(await withSession(g, (s) => {\n // The wait is the API's own when none is given: a one-shot's in a chat stays until the message went out or the edit\n // was confirmed, but not on a chat nobody joined yet. A group has no receipts: `--wait sent` waits until an edge took\n // it. None by default.\n if (parsed.options.wait !== undefined) params.wait = parsed.options.wait;\n if (parsed.options.timeout !== undefined) params.timeout = parsed.options.timeout;\n return s.call(spec.method, params);\n }, { deferGroups: spec.target === \"chat\", deferChats: spec.target === \"chat\" || oneGroupOnly(spec.method) }));\n}\n\n/**\n * `identity add`: a proof. An in-app signer finishes in this one command (what it waits on is printed to stderr as it\n * comes); a tool or a published record answers with the statement, and `identity complete` finishes it later, in the\n * same daemon.\n */\nasync function identityAddCommand(argv: string[]): Promise<void> {\n const parsed = parseArgs(argv, {\n signer: { type: \"string\", description: \"\" }, field: { type: \"list\", description: \"\" }, stdin: { type: \"boolean\", description: \"\" }, days: { type: \"number\", description: \"\" }, timeout: { type: \"number\", description: \"\" },\n }, undefined, { command: \"identity add\" });\n const g = globals(parsed);\n pretty = g.pretty;\n const [provider, ...subject] = parsed.positionals;\n if (!provider) throw new CliError(\"usage\", \"Missing <provider>: ghostly identity add <provider> [subject] [--signer id] [--field name=value]... [--stdin] [--days n] [--timeout s]\");\n // Before the profile opens, as a usage error that names the flag: the API's own check answered once it had opened, in\n // its parameter's words (\"days must be a number from 1 to 365\"), and `--days 1.5` got past it to the engine's.\n inRange(parsed.options, \"timeout\", \"a number of seconds\", 5, 3600);\n const items = (parsed.options.field as string[] | undefined) ?? [];\n const known = parsed.options.days !== undefined || items.length\n ? (await import(\"@ghostly/browser/proofs/registry\")).IDENTITY_PROVIDERS.find((p) => p.id === provider)\n : undefined;\n // The most days are the provider's; an unknown provider is the API's to name.\n if (known && parsed.options.days !== undefined) inRange(parsed.options, \"days\", \"a whole number\", 1, known.validity.maxDays, true);\n // A signer's secret (a bunker:// link) on the command line shows in ps for as long as the approval is waited for.\n const { fields, warning } = await identityFields(items, parsed.options.stdin === true, identitySecretFields(known, parsed.options.signer as string | undefined), readStdin, process.stdin.isTTY === true);\n if (warning) process.stderr.write(`ghostly: ${warning}\\n`);\n const params ={ provider, subject: subject.join(\" \") || undefined, signer: parsed.options.signer, fields, days: parsed.options.days, timeout: parsed.options.timeout };\n const tell = (event: GhostlyEvent) => {\n if (event.type === \"identity.approval\" || event.type === \"identity.progress\") process.stderr.write(JSON.stringify(event) + \"\\n\");\n };\n const addThroughDaemon = async (client: DaemonClient) => {\n await warnVersion(client);\n const watcher = await connectDaemon(g.paths);\n await watcher?.subscribe(undefined, tell);\n try { print(await client.call(\"identity.add\", params)); } finally { client.close(); watcher?.close(); }\n };\n requireProfile(g);\n const client = await connectDaemon(g.paths);\n if (client) { await addThroughDaemon(client); return; }\n const [, { callApi }] = await Promise.all([engineHost(), engineApi()]);\n const host = await openOneShot(g);\n if (host instanceof DaemonClient) { await addThroughDaemon(host); return; }\n const off = host.ctx.hub.onEvent(tell);\n try {\n const result = await callApi(host.ctx, \"identity.add\", params) as { done: boolean; draft?: string };\n if (!result.done) {\n await callApi(host.ctx, \"identity.cancel\", { draft: result.draft }).catch(() => {});\n throw new CliError(\"unavailable\", \"A proof made in two steps waits in the daemon between them: start `ghostly daemon --detach`, then run this again\");\n }\n print(result);\n } finally { off(); await host.close(); }\n}\n\nasync function tableCommand(name: string, argv: string[]): Promise<void> {\n const command = COMMANDS[name];\n const parsed = parseArgs(argv, command.options ?? {}, idSlot(command), { command: name, text: takesText(command), number: numberSlot(command) });\n const g = globals(parsed);\n pretty = g.pretty;\n const args = positionals(command, parsed.positionals);\n if (command.run) {\n printAnswer(await command.run(parsed, args));\n return;\n }\n const params = command.params?.(parsed, args) ?? {};\n for (const key of Object.keys(params)) if (params[key] === undefined) delete params[key];\n // `events` and `chat history --translate`: added here, where the runtime is, to the answer the daemon gave.\n const translator = await translatorFor(parsed.options.translate, g.home);\n // Evidence is read here, where the file is: the daemon runs elsewhere.\n const pipedEvidence = command.method === \"identity.complete\" && !params.evidenceFile && !params.stdin && process.stdin.isTTY !== true;\n if (command.method === \"identity.complete\") {\n if (params.evidenceFile) {\n try { params.evidence = readInput(params.evidenceFile as string); } catch (error) { throw localFileError(error, params.evidenceFile as string) ?? error; }\n }\n else if (params.stdin) params.evidence = await evidenceFromStdin(readStdin, String(params.draft), process.stdin.isTTY === true);\n delete params.evidenceFile; delete params.stdin;\n }\n if (command.method === \"x401.credential.add\") {\n // Nothing read is said of the file or stdin given, not as the API's missing `credential`; nothing on stdin (or a\n // terminal) as a join or a redeem says it, a usage error.\n try { params.credential = params.file === \"-\" ? await credentialFromStdin(readStdin, process.stdin.isTTY === true) : readInput(params.file as string); }\n // A file not there, a folder, one not allowed: said as every other file the CLI reads.\n catch (error) { throw (error instanceof CliError && error) || localFileError(error, params.file as string) || new CliError(\"usage\", `Cannot read the credential: ${error instanceof Error ? error.message : String(error)}`); }\n if (!params.credential) throw new CliError(\"bad_request\", `${params.file as string} is empty: it holds the SD-JWT VC the issuer sent`);\n delete params.file;\n }\n // Before stdin adds its own: only the --value names came on the command line.\n const lineValues = command.method === \"wallet.create\" ? Object.keys((params.values as Record<string, string> | undefined) ?? {}) : [];\n const secretWarning = await secretsFromStdin(command.method, params, readStdin, process.stdin.isTTY === true, (note) => process.stderr.write(`ghostly: ${note}\\n`));\n if (secretWarning) process.stderr.write(`ghostly: ${secretWarning}\\n`);\n const result = await withSession(g, async (s) => {\n if (lineValues.length) {\n // Which fields are secret is the source's form, in the engine.\n const list = await s.call(\"wallet.list\", { network: params.network ?? \"testnet\" }).catch(() => undefined);\n const warning = secretValuesWarning(list, params.type, params.provider, lineValues);\n if (warning) process.stderr.write(`ghostly: ${warning}\\n`);\n }\n const result = await (pipedEvidence\n ? completeWithPipedEvidence((p) => s.call(command.method, p), params, readStdin, (note) => process.stderr.write(`ghostly: ${note}\\n`))\n : s.call(command.method, params)) as Record<string, unknown>;\n // A one-shot join leaves once the contact can be reached: its answer has to be out first.\n if (command.method === \"invite.join\" && s.mode === \"one-shot\") {\n const joined = await oneShotJoinWait(s, result, typeof params.label === \"string\" ? params.label : undefined);\n if (joined.note) process.stderr.write(`ghostly: ${joined.note}\\n`);\n return joined.answer;\n }\n return result;\n }, { deferGroups: chatOnly(command.method, params) || newChatOnly(command.method), deferChats: oneChatOnly(command.method, params) || oneGroupOnly(command.method) || readsNoHistory(command.method, params), offline: offlineCall(command.method, params) });\n if (translator) {\n try { printAnswer(await (await import(\"./translate\")).translateAnswer(result, translator)); } finally { translator.close(); }\n return;\n }\n printAnswer(result);\n}\n\n/**\n * `call pipe`: a call's audio socket bridged to stdin and stdout, for shell pipelines. stdout carries audio only (the\n * contact's, raw PCM); what the command says goes to stderr. It ends when the call does.\n */\nasync function callPipeCommand(argv: string[]): Promise<void> {\n failures = process.stderr;\n const parsed = parseArgs(argv, {}, idSlot({ args: [\"call...?\"] }), { command: \"call pipe\" });\n const g = globals(parsed);\n const ref = parsed.positionals.join(\" \") || undefined;\n const client = await connectDaemon(g.paths);\n if (!client) throw new CliError(\"unavailable\", `No daemon runs profile ${g.profile}: calls need one (ghostly daemon --detach)`);\n let call: { call: string; audio: { socket: string; token: string; rate: number } | null };\n // The connection stays: the call's end comes on it with its reason, so the pipe says why it leaves (the call ended,\n // or another program took its audio). It left with exit 0 and no word for either.\n let reason: string | null = null, heard: (() => void) | null = null;\n try {\n call = await client.call(\"call.get\", ref ? { call: ref } : {}, { timeoutMs: ANSWER_MS }) as typeof call;\n if (!call.audio) throw new CliError(\"unavailable\", \"That call has no audio yet: answer it first\");\n const id = call.call;\n await client.subscribe(undefined, (event) => {\n if (event.type !== \"call.ended\" || event.call !== id) return;\n reason = String(event.reason);\n heard?.();\n }, () => heard?.());\n } catch (error) {\n client.close();\n throw error;\n }\n const audio = call.audio;\n const socket = connect(audio.socket);\n await new Promise<void>((resolve, reject) => { socket.once(\"connect\", resolve); socket.once(\"error\", reject); });\n // The call's token first: until it comes, the socket is nobody's (WISP 1100 § Calls).\n socket.write(`${audio.token}\\n`);\n process.stderr.write(`ghostly: call ${call.call}: s16le mono ${audio.rate} Hz on stdin/stdout\\n`);\n // A clip that ends (`ffmpeg -t 3 … | ghostly call pipe`) is queued and played, and the contact's audio goes on\n // coming: the end of stdin never closes the socket, whose daemon side would close the call's audio with it.\n process.stdin.pipe(socket, { end: false });\n // Nobody reads the contact's audio any more (`call pipe | head -c …`, a player closed): the pipe leaves, exit 0, and\n // the call goes on (another program may take its audio). It died on an EPIPE nobody handled, with a stack trace.\n let readerGone = false;\n onReaderGone(() => {\n readerGone = true;\n process.stderr.write(`ghostly: call ${call.call}: nothing reads its audio any more; the call goes on\\n`);\n socket.destroy();\n });\n socket.pipe(process.stdout);\n socket.on(\"close\", () => void (async () => {\n if (!readerGone) process.stderr.write(`ghostly: call ${call.call}: ${await whyClosed()}\\n`);\n client.close();\n exit(0);\n })());\n socket.on(\"error\", () => exit(1));\n\n /** Why the daemon closed the call's socket: a call still on gave it to another program; one gone ended. */\n async function whyClosed(): Promise<string> {\n if (reason === null) {\n // The call leaves the daemon's calls before its socket closes, and call.ended comes once the contact is told.\n const on = await client!.call(\"call.get\", { call: call.call }, { timeoutMs: 5000 }).then(() => true, () => false);\n if (on && reason === null) return \"another program took its audio; the call goes on\";\n if (reason === null) await new Promise<void>((resolve) => { heard = resolve; setTimeout(resolve, 3000).unref(); });\n }\n return reason === null ? \"the call ended\" : `the call ended (${reason})`;\n }\n}\n\n// ---------- entry ----------\n\n/**\n * The command's words when the line asks for help (`help <words>`, or `--help`/`--help=true`/`-h` before any `--`), else\n * null. `--help=false` asks for none: the command runs. A `-h` or `--help` that is an option's value, as the parser\n * reads it (`profile set --name --help`, `edit … --text \"$NEW\"`), asks for none either: it printed the help with exit 0\n * and changed nothing.\n */\nfunction helpAsked(argv: readonly string[]): string[] | null {\n const end = argv.indexOf(\"--\");\n const head = end === -1 ? argv : argv.slice(0, end);\n const words = (list: readonly string[]) => { const out: string[] = []; for (const word of list) { if (word.startsWith(\"-\")) break; out.push(word); } return out; };\n if (head[0] === \"help\") return words(head.slice(1));\n const options = optionsOf(words(head));\n for (let i = 0; i < head.length; i++) {\n const word = head[i];\n if (word === \"--help\" || word === \"--help=true\" || word === \"-h\") return words(head);\n const option = word.startsWith(\"--\") ? (word.includes(\"=\") ? undefined : options[word.slice(2)]) : word.length === 2 && word.startsWith(\"-\") ? Object.values(options).find((o) => o.short === word.slice(1)) : undefined;\n if (!option || option.type === \"boolean\") continue;\n if (option.optionalValue && !(i + 1 < head.length && head[i + 1] !== \"\" && Number.isFinite(Number(head[i + 1])))) continue;\n i++;\n }\n return null;\n}\n\n/** The options of the command `words` name (its longest command), with the global ones: what takes a value on its line. */\nfunction optionsOf(words: readonly string[]): Record<string, OptionSpec> {\n for (let n = words.length; n > 0; n--) {\n const asked = words.slice(0, n).join(\" \");\n const row = helpRows().find((r) => commandWords(r.usage).join(\" \") === asked);\n if (row) return { ...GLOBAL_OPTIONS, ...row.options };\n }\n return GLOBAL_OPTIONS;\n}\n\n/** No profile yet in the Ghostly folder these global options name: `ghostly`'s first run there. */\nfunction newHome(argv: readonly string[]): boolean {\n try {\n return listProfiles(ghostlyHome(parseArgs([...argv], {}).options.home as string | undefined)).length === 0;\n } catch {\n return false;\n }\n}\n\nexport async function main(input: string[]): Promise<number> {\n const argv = liftGlobals(input);\n // Global options alone (`ghostly --pretty`, `ghostly -p bot`) name no command: lifted, one of them comes first.\n const helpFor = argv.length === 0 || globalOption(argv[0]) ? [] : helpAsked(argv);\n if (helpFor) { process.stdout.write((helpFor.length ? commandHelp(helpFor) : help(argv[0] !== \"help\" && newHome(argv))) + \"\\n\"); return 0; }\n if (argv[0] === \"--version\" || argv[0] === \"version\") {\n // Global options come after the command once lifted: `--pretty` indents this answer too. Anything else is refused,\n // as every command refuses it: `version --json` (a typo) answered the version.\n const parsed = parseArgs(argv.slice(1), {}, undefined, { command: \"version\" });\n noMoreThan(0, parsed.positionals, \"version\");\n pretty = parsed.options.pretty === true;\n print({ version: VERSION });\n return 0;\n }\n const [first, second, third] = argv;\n const two = second && !second.startsWith(\"-\") ? `${first} ${second}` : \"\";\n const three = two && third && !third.startsWith(\"-\") ? `${two} ${third}` : \"\";\n // A command is one its table lists itself: every object has `constructor` and `toString`, which are no commands.\n const text = (name: string) => Object.hasOwn(TEXT_COMMANDS, name), table = (name: string) => Object.hasOwn(COMMANDS, name);\n if (first === \"profile\" && !table(two)) { await profileCommand(second, argv.slice(2)); return 0; }\n if (first === \"daemon\") { await daemonCommand(argv.slice(1)); return -1; }\n if (first === \"listen\") { await listenCommand(argv.slice(1)); return -1; }\n if (first === \"engine\") { await engineCommand(argv.slice(1)); return 0; }\n if (first === \"settings\") { await settingsCommand(second, argv.slice(2)); return 0; }\n if (two === \"identity add\") { await identityAddCommand(argv.slice(2)); return 0; }\n if (two === \"call pipe\") { await callPipeCommand(argv.slice(2)); return -1; }\n if (three && table(three)) { await tableCommand(three, argv.slice(3)); return 0; }\n if (two && text(two)) { await textCommand(two, argv.slice(2)); return 0; }\n if (two && table(two)) { await tableCommand(two, argv.slice(2)); return 0; }\n if (text(first)) { await textCommand(first, argv.slice(1)); return 0; }\n if (table(first) && two && groupWithNoArguments(COMMANDS[first].usage)) throw unknownCommand(first, second);\n if (table(first)) { await tableCommand(first, argv.slice(1)); return 0; }\n // Lifting stopped at it: a word with a dash there is a mistyped global option, not a command (`-` and `--` are none).\n if (first.startsWith(\"-\") && first !== \"-\" && first !== \"--\") throw unknownGlobalOption(first);\n throw unknownCommand(first, two ? second : undefined, three ? third : undefined);\n}\n\n/**\n * A command line that names no command. The words of a group (`ghostly chat`, `ghostly wallet frob`, `ghostly x401\n * credential`) are answered with the group's commands, as `ghostly help chat` lists them; before, it was only \"Unknown\n * command: chat\". The longest group the words name answers: `x401 credential frob` lists add, list and remove.\n * A word near one of them is a typo: `chat lst` and `sned hi` say the command meant (`chat list`, `send`) and its help.\n */\nexport function unknownCommand(first: string | undefined, second?: string, third?: string): CliError {\n const asked = [first, second, third].filter((word): word is string => !!word);\n const all = helpRows().map((row) => commandWords(row.usage));\n const takes = (group: readonly string[]) => [...new Set(all.filter((words) => words.length > group.length && group.every((word, i) => words[i] === word)).map((words) => words[group.length]))];\n const meant = (typed: readonly string[], words: readonly string[]) => new CliError(\"usage\", `Unknown command: ${typed.join(\" \")} (did you mean ${words.join(\" \")}? ghostly help ${words.join(\" \")})`);\n for (let depth = Math.min(asked.length, 2); depth >= 1; depth--) {\n const group = asked.slice(0, depth), name = group.join(\" \"), extra = asked[depth];\n const subs = takes(group);\n if (!subs.length) continue;\n const near = extra === undefined ? undefined : nearest(extra, subs);\n if (near) return meant([...group, extra!], [...group, near]);\n const list = `${subs.slice(0, -1).join(\", \")}${subs.length > 1 ? \" or \" : \"\"}${subs.at(-1)}`;\n 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})`);\n }\n // A first word that names no command: the words after it are its arguments (`sned hi`), unless they are a command\n // word of the one it meant (`chta list`).\n const near = asked[0] === undefined ? undefined : nearest(asked[0], takes([]));\n if (!near) return new CliError(\"usage\", `Unknown command: ${asked[0] ?? '\"\"'} (ghostly help)`);\n return asked[1] !== undefined && takes([near]).includes(asked[1]) ? meant(asked.slice(0, 2), [near, asked[1]]) : meant([asked[0]], [near]);\n}\n\n/** The command a group's word names (`profile set`), for its usage errors; the group itself for a word it does not take. */\nfunction commandOf(group: string, sub: string | undefined): string {\n return sub !== undefined && helpRows().some((row) => commandWords(row.usage).join(\" \") === `${group} ${sub}`) ? `${group} ${sub}` : group;\n}\n\n/** Leaves once what was printed reached stdout (a pipe drains asynchronously). */\nfunction exit(code: number): void {\n process.stdout.write(\"\", () => process.exit(code));\n}\n\n/**\n * Stdout is the command's answer and nothing else: one JSON object, or a stream of JSON lines. What the engine notes\n * as it works (a relay left alone for a minute, a wallet moved to its network's key) is written with `console.info`\n * and the like, which Node sends to stdout: a script reading the answer (`ghostly wallet list | jq`) then failed on a\n * line that is not JSON. Those notes go to stderr, where a daemon's log and a terminal still show them.\n */\nexport function notesToStderr(): void {\n for (const level of [\"log\", \"info\", \"debug\"] as const) console[level] = (...args: unknown[]) => { process.stderr.write(`${format(...args)}\\n`); };\n}\n\n/** Runs the command line; `-1` from `main` means the process stays (a daemon, a listener). */\nexport async function run(argv: string[]): Promise<void> {\n notesToStderr();\n try {\n const code = await main(argv);\n if (code >= 0) exit(code);\n } catch (error) {\n const failure = asCliError(error);\n failures.write(jsonOut({ error: failure.toJSON() }, pretty ? 2 : undefined) + \"\\n\");\n exit(EXIT[failure.code]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACyBA,IAAa,iBAAiB,UAA0B,kBAAkB,KAAK,KAAK,IAAI,OAAO,KAAK,IAAI;AACxG,IAAM,cAAc,MAAc,QAAoB,UAAkB,IAAI,SAAS,SAAS,KAAK,KAAK,SAAS,OAAO,SAAS,WAAW,QAAQ,KAAK,UAAU,KAAK,GAAG;;;;;AAM3K,IAAM,+BAAe,IAAI,QAAiF;;AAG1G,SAAgB,WAAW,QAAiD;CAC1E,OAAO,aAAa,IAAI,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,WAAW,OAAO,WAAW,IAAI,CAAC,EAAE;AACtF;;;;AAUA,IAAa,iBAA6C;CACxD,SAAS;EAAE,MAAM;EAAU,OAAO;EAAK,aAAa;CAAmE;CACvH,MAAM;EAAE,MAAM;EAAU,aAAa;CAA6D;CAClG,QAAQ;EAAE,MAAM;EAAW,aAAa;CAAyB;CACjE,MAAM;EAAE,MAAM;EAAW,OAAO;EAAK,aAAa;CAAY;AAChE;;;;;;;;;;;;;;;AAgBA,SAAgB,UAAU,MAAyB,MAAkC,eAA2C,OAAO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