@ghostlytools/cli 1.13.2 → 1.13.3
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 +9 -8
- package/dist/assets/{api-DV52o7A8.js → api-DO0YMLiB.js} +2 -2
- package/dist/assets/{api-O57SNJcb.js → api-Dz2cw7WD.js} +155 -44
- package/dist/assets/api-Dz2cw7WD.js.map +1 -0
- package/dist/assets/{apiKit-CPTFJHA7.js → apiKit-DAFsWtyk.js} +17 -3
- package/dist/assets/apiKit-DAFsWtyk.js.map +1 -0
- package/dist/assets/{appFetch-Ca9DNQQ2.js → appFetch-BQO5Pk7W.js} +2 -2
- package/dist/assets/{appFetch-Ca9DNQQ2.js.map → appFetch-BQO5Pk7W.js.map} +1 -1
- package/dist/assets/{apps-gXpGFPiv.js → apps-B88rYWRm.js} +45 -19
- package/dist/assets/apps-B88rYWRm.js.map +1 -0
- package/dist/assets/{apps-uZTu5FlR.js → apps-D4KRpZB4.js} +1 -1
- package/dist/assets/{backup-Di2U6QVH.js → backup-BeXBtbVL.js} +1 -1
- package/dist/assets/{backup-CxH3auHB.js → backup-CNLY905d.js} +10 -5
- package/dist/assets/backup-CNLY905d.js.map +1 -0
- package/dist/assets/bark_ffi_wasm_bg-CjjCN3FD.js +5 -0
- package/dist/assets/{bitcoind-BpZn3bRN.js → bitcoind-BXZdQ1wZ.js} +2 -2
- package/dist/assets/{bitcoind-BpZn3bRN.js.map → bitcoind-BXZdQ1wZ.js.map} +1 -1
- package/dist/assets/bitcoindevkit_bg-D6IFIaJi.js +5 -0
- package/dist/assets/{buttons-D4udKEvT.js → buttons-BKojbx0Q.js} +4 -4
- package/dist/assets/{buttons-D4udKEvT.js.map → buttons-BKojbx0Q.js.map} +1 -1
- package/dist/assets/buttons-_5Fw8uHn.js +1 -0
- package/dist/assets/{client-DGx7E8b3.js → client-BtPhfWjK.js} +2 -2
- package/dist/assets/{client-DGx7E8b3.js.map → client-BtPhfWjK.js.map} +1 -1
- package/dist/assets/{fedimintSdk-D-6H9Pe7.js → fedimintSdk-eLXBrj9i.js} +2 -2
- package/dist/assets/{fedimintSdk-D-6H9Pe7.js.map → fedimintSdk-eLXBrj9i.js.map} +1 -1
- package/dist/assets/fedimint_client_wasm_bg-CRQlnJdu.js +5 -0
- package/dist/assets/{fixedHosts-CODN2pTL.js → fixedHosts-BJFL8Ell.js} +3 -3
- package/dist/assets/{fixedHosts-CODN2pTL.js.map → fixedHosts-BJFL8Ell.js.map} +1 -1
- package/dist/assets/{groupMeta-CeZpqVVC.js → groupMeta-Cz95F6sX.js} +98 -9
- package/dist/assets/groupMeta-Cz95F6sX.js.map +1 -0
- package/dist/assets/{host-CRA7h5A2.js → host-BsBWxTtW.js} +172 -22
- package/dist/assets/host-BsBWxTtW.js.map +1 -0
- package/dist/assets/{identityProofs-B8zCp5_0.js → identityProofs-zI_Iy9uI.js} +15 -1
- package/dist/assets/identityProofs-zI_Iy9uI.js.map +1 -0
- package/dist/assets/{irohWeb-mnOi2Jp7.js → irohWeb-BLDcHwYz.js} +50 -13
- package/dist/assets/irohWeb-BLDcHwYz.js.map +1 -0
- package/dist/assets/{main-Chc871HV.js → main-D48Ben7C.js} +68 -28
- package/dist/assets/main-D48Ben7C.js.map +1 -0
- package/dist/assets/{ownDid-BOuSlDv-.js → ownDid-CwxFBzOH.js} +5 -4
- package/dist/assets/ownDid-CwxFBzOH.js.map +1 -0
- package/dist/assets/{ownStatus-CLA1VPkL.js → ownStatus-DjD0sQKF.js} +34 -11
- package/dist/assets/ownStatus-DjD0sQKF.js.map +1 -0
- package/dist/assets/{profiles-BH1bH9aE.js → profiles-BAJf0c9E.js} +33 -8
- package/dist/assets/profiles-BAJf0c9E.js.map +1 -0
- package/dist/assets/{registry-DAq16T-V.js → registry-CHwHTWbK.js} +1 -1
- package/dist/assets/{registry-DP_-RA-v.js → registry-CPuexTle.js} +25 -13
- package/dist/assets/registry-CPuexTle.js.map +1 -0
- package/dist/assets/{resolve-B1eQ4dVQ.js → resolve-BqmGXKn4.js} +2 -2
- package/dist/assets/{resolve-B1eQ4dVQ.js.map → resolve-BqmGXKn4.js.map} +1 -1
- package/dist/assets/{server-Bd2ofxc1.js → server-e4oKeNez.js} +399 -88
- package/dist/assets/server-e4oKeNez.js.map +1 -0
- package/dist/assets/{sshForges-As7dbGXM.js → sshForges-Cqt3qfWe.js} +2 -2
- package/dist/assets/{sshForges-As7dbGXM.js.map → sshForges-Cqt3qfWe.js.map} +1 -1
- package/dist/assets/translate-DnuQMfj0.js.map +1 -1
- package/dist/assets/{waitNotice-BHuMofaH.js → waitNotice-mB0Ym145.js} +2 -2
- package/dist/assets/{waitNotice-BHuMofaH.js.map → waitNotice-mB0Ym145.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-O57SNJcb.js.map +0 -1
- package/dist/assets/apiKit-CPTFJHA7.js.map +0 -1
- package/dist/assets/apps-gXpGFPiv.js.map +0 -1
- package/dist/assets/backup-CxH3auHB.js.map +0 -1
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +0 -5
- package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +0 -1
- package/dist/assets/bark_ffi_wasm_bg-VNmaJsc9.wasm +0 -0
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +0 -5
- package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +0 -1
- package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
- package/dist/assets/buttons-YTYEqvGC.js +0 -1
- package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +0 -5
- package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js.map +0 -1
- package/dist/assets/fedimint_client_wasm_bg-DeFtkIv6.wasm +0 -0
- package/dist/assets/groupMeta-CeZpqVVC.js.map +0 -1
- package/dist/assets/host-CRA7h5A2.js.map +0 -1
- package/dist/assets/identityProofs-B8zCp5_0.js.map +0 -1
- package/dist/assets/irohWeb-mnOi2Jp7.js.map +0 -1
- package/dist/assets/main-Chc871HV.js.map +0 -1
- package/dist/assets/ownDid-BOuSlDv-.js.map +0 -1
- package/dist/assets/ownStatus-CLA1VPkL.js.map +0 -1
- package/dist/assets/profiles-BH1bH9aE.js.map +0 -1
- package/dist/assets/registry-DP_-RA-v.js.map +0 -1
- package/dist/assets/server-Bd2ofxc1.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"api-O57SNJcb.js","names":["constants","randomBytes","randomBytes","engine","open"],"sources":["../../src/typing.ts","../../src/voicePeaks.ts","../../src/files.ts","../../src/statusCards.ts","../../src/holds.ts","../../src/views.ts","../../src/groupAdmin.ts","../../src/identities.ts","../../src/x401.ts","../../src/services.ts","../../src/calls/api.ts","../../src/appServe.ts","../../src/appEvents.ts","../../src/appChat.ts","../../../../apps/ui/src/lib/localHost.ts","../../src/wallets.ts","../../src/api.ts"],"sourcesContent":["import { TYPING_REFRESH_MS, type TypingKind } from \"@ghostly/core\";\nimport type { EngineState } from \"@ghostly/browser/shared/types\";\nimport { node, state, type ApiContext } from \"./apiKit\";\n\n/**\n * `typing --for` and `group typing --for`: a `start` holds 6 s on the other side (WISP 401 § Typing, WISP 902 · Group\n * Mesh § Typing), so the daemon says it again until the time is up, a message goes to that chat or group, or a\n * `--stop`. The engine sends a `start` at most once per refresh, counted from when the last one went: asking every half\n * refresh missed the tick at 3 s by a millisecond about half the time, so a start went every 4.5 s, 1.5 s inside the\n * contact's 6 s, and a busy machine flickered the contact's indicator off and on. Asking every half second sends one\n * at most 3.5 s after the last, and soon again when the send limit held one back.\n */\nconst KEEP_EVERY_MS = TYPING_REFRESH_MS / 6;\nconst keepers = new WeakMap<ApiContext, Map<string, () => void>>();\n\n/** Where typing is said: a 1:1 chat, or a private group. */\nexport type TypingTarget = { linkId: string } | { groupId: string };\ntype Word = { kind?: TypingKind; status?: string };\n\nfunction keepersOf(ctx: ApiContext): Map<string, () => void> {\n let map = keepers.get(ctx);\n if (!map) keepers.set(ctx, (map = new Map()));\n return map;\n}\n\nconst keyOf = (target: TypingTarget) => \"groupId\" in target ? `group:${target.groupId}` : target.linkId;\n\n/** Says it once: this side is typing (with its word), or stopped. */\nexport function sayTyping(ctx: ApiContext, target: TypingTarget, typing: boolean, word: Word = {}): void {\n const said = typing ? word : {};\n if (\"groupId\" in target) node(ctx).setGroupTyping({ groupId: target.groupId, typing, ...said });\n else node(ctx).setTyping({ linkId: target.linkId, typing, ...said });\n}\n\n/**\n * Says this side is typing in the chat or group for `ms`, with the kind and status it gave (`--kind`, `--status`) each\n * time; resolves when that ends, whichever way.\n */\nexport function keepTyping(ctx: ApiContext, target: TypingTarget, ms: number, word: Word = {}): Promise<void> {\n endTyping(ctx, target, false);\n const map = keepersOf(ctx), key = keyOf(target);\n return new Promise<void>((resolve) => {\n const end = () => { clearInterval(again); clearTimeout(until); off(); if (map.get(key) === end) map.delete(key); resolve(); };\n const again = setInterval(() => sayTyping(ctx, target, true, word), KEEP_EVERY_MS);\n const until = setTimeout(() => { end(); sayTyping(ctx, target, false); }, ms);\n // A message ends it, sent from anywhere (the engine said `stop` with it).\n const off = ctx.hub.onEvent((event) => {\n if (\"groupId\" in target ? event.type === \"group.sent\" && event.group === target.groupId : event.type === \"message.sent\" && event.chat === target.linkId) end();\n });\n map.set(key, end);\n });\n}\n\n/** How long a one-shot's `--for` waits for its chat or group to be live: a fresh one-shot connects first. */\nexport const ONE_SHOT_LIVE_GRACE_MS = 15_000;\n\n/**\n * A one-shot's `--for` (it holds the profile while it runs): kept the whole time once the chat or group is live, as a\n * daemon keeps it; ended when it is not live within `ONE_SHOT_LIVE_GRACE_MS`, since nobody would see it, and `--stop`\n * or a send from another shell could not end it.\n */\nexport async function keepOneShot(ctx: ApiContext, target: TypingTarget, kept: Promise<void>, live: (state: EngineState) => boolean): Promise<void> {\n let stop = () => {};\n const cameLive = new Promise<boolean>((resolve) => {\n if (live(state(ctx))) return resolve(true);\n const timer = setTimeout(() => { off(); resolve(false); }, ONE_SHOT_LIVE_GRACE_MS);\n const off = ctx.hub.onState((next) => { if (live(next)) { clearTimeout(timer); off(); resolve(true); } });\n stop = () => { clearTimeout(timer); off(); resolve(true); };\n });\n if (await Promise.race([kept.then(() => true), cameLive])) { stop(); await kept; return; }\n endTyping(ctx, target, false);\n}\n\n/** Ends a kept `--for` in the chat or group; `tell`: and says this side stopped. Whether one was kept. */\nexport function endTyping(ctx: ApiContext, target: TypingTarget, tell: boolean): boolean {\n const end = keepersOf(ctx).get(keyOf(target));\n if (!end) return false;\n end();\n if (tell) sayTyping(ctx, target, false);\n return true;\n}\n","import { spawn } from \"node:child_process\";\nimport { open, type FileHandle } from \"node:fs/promises\";\nimport { VOICE_LIMITS, VOICE_METER, downsamplePeaks, voiceLevel } from \"@ghostly/core\";\nimport { childEnv } from \"./childEnv\";\n\n/**\n * The waveform and length of a voice note sent from a file (`file send --voice`), measured as the apps measure their\n * own recordings (packages/core voice.ts `voicePeaksOf`, the recorder's meter) so the bars look the same. The sound is\n * decoded here, without native code: WAV by hand, Opus in WebM or Ogg and MP3 with the wasm decoders, anything\n * else (AAC in MP4, FLAC…) with `ffmpeg` when it is on the PATH.\n *\n * The decoders hand their samples to a sink a piece at a time, and the meter (`VoiceMeter`) keeps only the\n * analyser's window of them: the whole sound decoded into memory first took 2.6 GiB for a 60-minute MP3, in the\n * daemon, only for it to be refused as longer than a voice note (agents#878). Decoding stops once the sound is longer\n * than a voice note may be. A WAV and an MP3 are read from the file in pieces, and a kind left to ffmpeg is not read\n * here at all: the whole file read first took +190 MiB for a 15-minute WAV (agents#1577).\n */\n\nexport interface Sound {\n /** One channel, -1 to 1: the channels averaged, as the recorder's analyser hears them. */\n mono: Float32Array;\n sampleRate: number;\n}\n\nexport interface VoiceMeasure { duration: number; peaks: number[] }\n\n/** Where a decoder puts what it decoded: `push` answers false once nothing more is wanted (the decoder stops). */\nexport interface SoundSink {\n start(sampleRate: number): void;\n push(channels: readonly Float32Array[], length: number): boolean;\n}\n\n/** Longer than any voice note (15 minutes) with room: a WebM or Ogg past it is not read (their demuxers hold it all). */\nconst MAX_BYTES = 256 * 1024 * 1024;\n/** Read first to tell a file's kind; a WAV's header is looked for in up to `WAV_HEAD_MAX` (as in ffmpeg's output). */\nconst HEAD_BYTES = 64 * 1024;\nconst WAV_HEAD_MAX = 1024 * 1024;\nconst FFMPEG_TIMEOUT_MS = 120_000;\n/** Read past the longest voice note by this much, so its length is known to be too long (`parseVoiceMeta` allows 5 s). */\nconst PAST_LIMIT_MS = 6_000;\n\n/**\n * The recorder's meter, run over the samples as they come (core `voiceLevelsOf`, reading for reading): the channels\n * averaged as `mix` does, a reading every `intervalMs` over the window that ends there, nothing kept but that window.\n */\nexport class VoiceMeter implements SoundSink {\n private rate = 0;\n private window = 1;\n private ring = new Float32Array(1);\n private count = 0;\n private step = 1;\n private nextEnd = 0;\n private limit = Infinity;\n private readonly levels: number[] = [];\n private readonly scratch: number[] = [];\n\n constructor(private readonly maxMs: number = VOICE_LIMITS.maxDurationMs + PAST_LIMIT_MS) {}\n\n start(sampleRate: number): void {\n if (this.rate) return;\n this.rate = sampleRate;\n this.window = Math.max(1, Math.round((VOICE_METER.window * sampleRate) / VOICE_METER.windowRate));\n this.ring = new Float32Array(this.window);\n this.nextEnd = this.endOf(1);\n this.limit = Math.ceil((this.maxMs * sampleRate) / 1000);\n }\n\n private endOf(step: number): number { return Math.round((step * VOICE_METER.intervalMs * this.rate) / 1000); }\n\n push(channels: readonly Float32Array[], length: number): boolean {\n if (!(this.rate > 0)) return false;\n const one = channels.length === 1 ? channels[0]! : null, n = channels.length;\n for (let i = 0; i < length; i++) {\n if (this.count >= this.limit) return false;\n let sample: number;\n if (one) sample = one[i]!;\n else {\n // As `mix` adds into a Float32Array: rounded to a float after each channel.\n sample = 0;\n for (let c = 0; c < n; c++) sample = Math.fround(sample + channels[c]![i]! / n);\n }\n this.ring[this.count % this.window] = sample;\n this.count++;\n while (this.count === this.nextEnd) {\n const from = Math.max(0, this.count - this.window);\n this.scratch.length = 0;\n for (let k = from; k < this.count; k++) this.scratch.push(this.ring[k % this.window]!);\n this.levels.push(voiceLevel(this.scratch));\n this.nextEnd = this.endOf(++this.step);\n }\n }\n return this.count < this.limit;\n }\n\n /** The length and waveform measured so far; null when no sound came. */\n result(): VoiceMeasure | null {\n if (!this.count || !(this.rate > 0)) return null;\n return { duration: Math.round((this.count / this.rate) * 1000), peaks: downsamplePeaks(this.levels, VOICE_LIMITS.bars) };\n }\n}\n\n/** Every sample, kept: the whole sound in memory (tests and comparisons; `measureVoice` never does this). */\nclass Collector implements SoundSink {\n rate = 0;\n private readonly parts: Float32Array[] = [];\n start(sampleRate: number): void { this.rate ||= sampleRate; }\n push(channels: readonly Float32Array[], length: number): boolean {\n this.parts.push(mix(channels, length).slice());\n return true;\n }\n sound(): Sound {\n const mono = new Float32Array(this.parts.reduce((n, p) => n + p.length, 0));\n let at = 0;\n for (const part of this.parts) { mono.set(part, at); at += part.length; }\n return { mono, sampleRate: this.rate };\n }\n}\n\n/**\n * A file that is not sound: a decoder read it and found none (a WAV without its samples, ffmpeg's \"Invalid data\n * found\"). Not one that could not be read here (no ffmpeg, a WAV format not read): that may still be a voice note.\n */\nexport class NotSound extends Error {}\n\n/**\n * The waveform and length of the sound in `path`, or why they could not be read (`notSound` when the file is no sound\n * at all). A sound longer than a voice note may be is read only a little past that length: its duration says it is\n * too long, and the send is refused for it.\n */\nexport async function measureVoice(path: string): Promise<{ voice: VoiceMeasure } | { problem: string; notSound?: true }> {\n const meter = new VoiceMeter();\n try {\n await streamSound(path, meter);\n } catch (error) {\n return { problem: error instanceof Error ? error.message : String(error), ...(error instanceof NotSound ? { notSound: true } : {}) };\n }\n const voice = meter.result();\n return voice ? { voice } : { problem: \"no sound in it\", notSound: true };\n}\n\n/** Decodes the sound in `path` into `sink`, by this module's decoders or else ffmpeg. */\nexport async function streamSound(path: string, sink: SoundSink): Promise<void> {\n let own: Error | undefined;\n try {\n if (await streamFile(path, sink)) return;\n } catch (error) {\n own = error instanceof Error ? error : new Error(String(error));\n }\n try {\n await streamFfmpeg(path, sink);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // ffmpeg's word on it, or this module's when ffmpeg could not give one (not here, too slow).\n const notSound = error instanceof NotSound || own instanceof NotSound;\n throw new (notSound ? NotSound : Error)(own ? `${own.message}; ${reason}` : reason, { cause: error });\n }\n}\n\ntype Kind = \"wav\" | \"webm\" | \"ogg\" | \"mp3\" | null;\n\n/** The kind of sound a file's first bytes say it is, of those this module decodes itself. */\nfunction kindOf(head: Uint8Array): Kind {\n if (ascii(head, 0, 4) === \"RIFF\" && ascii(head, 8, 4) === \"WAVE\") return \"wav\";\n if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return \"webm\";\n if (ascii(head, 0, 4) === \"OggS\") return \"ogg\";\n if (ascii(head, 0, 3) === \"ID3\" || (head[0] === 0xff && (head[1]! & 0xe0) === 0xe0)) return \"mp3\";\n return null;\n}\n\n/**\n * Feeds `sink` the sound of a kind this module decodes itself, reading the file only as far as its decoder goes; false\n * for a kind it leaves to ffmpeg, not read past its head.\n */\nasync function streamFile(path: string, sink: SoundSink): Promise<boolean> {\n const file = await open(path);\n try {\n const { size } = await file.stat();\n const kind = kindOf(await readAt(file, 0, Math.min(size, 12)));\n if (kind === \"wav\") { await streamWavFile(file, size, sink); return true; }\n if (kind === \"mp3\") { await streamMp3(piecesOf(file, size, MP3_PIECE), sink); return true; }\n if (!kind) return false;\n if (size > MAX_BYTES) throw new Error(\"too large to decode\");\n return streamOpusOf(kind, await file.readFile(), sink);\n } finally {\n await file.close();\n }\n}\n\nasync function streamOpusOf(kind: \"webm\" | \"ogg\", bytes: Uint8Array, sink: SoundSink): Promise<boolean> {\n const opus = kind === \"webm\" ? demuxWebm(bytes) : demuxOgg(bytes);\n if (!opus) return false;\n await streamOpus(opus, sink);\n return true;\n}\n\n/** Up to `length` bytes of the file from `at` (fewer at its end), into `into` when given. */\nasync function readAt(file: FileHandle, at: number, length: number, into = Buffer.allocUnsafe(length)): Promise<Buffer> {\n let got = 0;\n while (got < length) {\n const { bytesRead } = await file.read(into, got, length - got, at + got);\n if (!bytesRead) break;\n got += bytesRead;\n }\n return into.subarray(0, got);\n}\n\n/** The file in pieces of `piece` bytes, each read into the same buffer once the one before is used. */\nasync function* piecesOf(file: FileHandle, size: number, piece: number): AsyncGenerator<Uint8Array> {\n const buffer = Buffer.allocUnsafe(piece);\n for (let at = 0; at < size; at += piece) {\n const bytes = await readAt(file, at, Math.min(piece, size - at), buffer);\n if (!bytes.length) return;\n yield bytes;\n }\n}\n\nfunction ascii(bytes: Uint8Array, at: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(at, at + length));\n}\n\nfunction mix(channels: readonly Float32Array[], length: number): Float32Array {\n if (channels.length === 1) return channels[0]!.subarray(0, length);\n const mono = new Float32Array(length);\n for (const channel of channels) for (let i = 0; i < length; i++) mono[i]! += channel[i]! / channels.length;\n return mono;\n}\n\n// ---------- WAV ----------\n\n\n/** The channels and rates a WAV's sound may have (ffmpeg's DSD at 705.6 kHz among them). */\nconst WAV_MAX_CHANNELS = 255;\nconst WAV_MIN_RATE = 1_000;\nconst WAV_MAX_RATE = 768_000;\n\n/** The format of a WAV and where its samples are; null while its header is not all there. */\nfunction wavHeader(bytes: Uint8Array): { format: number; channels: number; sampleRate: number; bits: number; from: number; to: number } | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let format = 0, channels = 0, sampleRate = 0, bits = 0;\n let at = 12;\n while (at + 8 <= bytes.length) {\n const id = ascii(bytes, at, 4);\n const size = view.getUint32(at + 4, true);\n const body = at + 8;\n if (id === \"fmt \") {\n if (body + 16 > bytes.length) return null;\n format = view.getUint16(body, true);\n channels = view.getUint16(body + 2, true);\n sampleRate = view.getUint32(body + 4, true);\n bits = view.getUint16(body + 14, true);\n // WAVE_FORMAT_EXTENSIBLE: the real format is the sub-format GUID's first two bytes.\n if (format === 0xfffe && size >= 26) { if (body + 26 > bytes.length) return null; format = view.getUint16(body + 24, true); }\n } else if (id === \"data\") {\n if (!channels || !sampleRate || !bits) throw new NotSound(\"a WAV without its format\");\n // What is read and kept goes with the channels and the rate: a header past any sound's takes no memory.\n if (channels > WAV_MAX_CHANNELS || sampleRate < WAV_MIN_RATE || sampleRate > WAV_MAX_RATE)\n throw new NotSound(`a WAV with ${channels} channel${channels === 1 ? \"\" : \"s\"} at ${sampleRate} Hz, which no sound has`);\n const to = size === 0 || size === 0xffffffff ? Infinity : body + size;\n return { format, channels, sampleRate, bits, from: body, to };\n }\n at = body + size + (size & 1);\n }\n return null;\n}\n\n/** How a WAV's sample is read, or undefined for a format not read here. */\nfunction sampleReader(view: DataView, format: number, bits: number): ((at: number) => number) | undefined {\n return format === 1 && bits === 8 ? (at) => (view.getUint8(at) - 128) / 128\n : format === 1 && bits === 16 ? (at) => view.getInt16(at, true) / 32768\n : format === 1 && bits === 24 ? (at) => (((view.getInt8(at + 2) << 16) | (view.getUint8(at + 1) << 8) | view.getUint8(at)) / 8388608)\n : format === 1 && bits === 32 ? (at) => view.getInt32(at, true) / 2147483648\n : format === 3 && bits === 32 ? (at) => view.getFloat32(at, true)\n : format === 3 && bits === 64 ? (at) => view.getFloat64(at, true)\n : undefined;\n}\n\n/** Frames of a channel each pushed at a time: few enough to keep nothing large, many enough for few calls. */\nconst PIECE_FRAMES = 4096;\n\n/**\n * PCM (8, 16, 24 or 32 bit) or float (32 or 64 bit) WAV, read a piece of frames at a time until the sink wants no\n * more. A data chunk whose size is unknown (a pipe) runs to the end.\n */\nasync function streamWavFile(file: FileHandle, size: number, sink: SoundSink): Promise<void> {\n let header: ReturnType<typeof wavHeader> = null;\n for (let length = HEAD_BYTES; !header; length *= 2) {\n header = wavHeader(await readAt(file, 0, Math.min(size, length)));\n if (length >= size || length >= WAV_HEAD_MAX) break;\n }\n if (!header) throw new NotSound(\"a WAV without sound\");\n const { format, bits, channels } = header;\n if (!sampleReader(new DataView(new ArrayBuffer(0)), format, bits)) throw new Error(`a WAV in a format not read here (${format}, ${bits} bit)`);\n sink.start(header.sampleRate);\n const frame = (bits / 8) * channels, end = Math.min(size, header.to);\n const buffer = Buffer.allocUnsafe(PIECE_FRAMES * frame);\n for (let at = header.from; at + frame <= end;) {\n const bytes = await readAt(file, at, Math.min(buffer.length, end - at), buffer);\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const pushed = pushWavFrames(view, 0, bytes.length, channels, bits / 8, sampleReader(view, format, bits)!, sink);\n if (!pushed.more || !pushed.at) return;\n at += pushed.at;\n }\n}\n\n/** The whole frames between `from` and `to`, as the channels' samples; the byte where it stopped (a frame cut off). */\nfunction pushWavFrames(view: DataView, from: number, to: number, channels: number, width: number, read: (at: number) => number, sink: SoundSink): { at: number; more: boolean } {\n const frame = width * channels;\n const parts = Array.from({ length: channels }, () => new Float32Array(PIECE_FRAMES));\n let at = from;\n while (at + frame <= to) {\n const count = Math.min(PIECE_FRAMES, Math.floor((to - at) / frame));\n for (let f = 0; f < count; f++) for (let c = 0; c < channels; c++) parts[c]![f] = read(at + (f * channels + c) * width);\n at += count * frame;\n if (!sink.push(parts, count)) return { at, more: false };\n }\n return { at, more: true };\n}\n\n// ---------- Opus (WebM, Ogg) ----------\n\n/**\n * Opus packets a demuxer keeps: as many as the longest voice note read past its limit can have, at 2.5 ms (Opus's\n * shortest packet) each. Past it a file is longer than a voice note anyway. Before, a 1 MB WebM of blocks each lacing\n * 256 empty frames held ~8 KB of heap per byte read, and took the daemon down out of memory.\n */\nexport const MAX_OPUS_PACKETS = Math.ceil((VOICE_LIMITS.maxDurationMs + PAST_LIMIT_MS) / 2.5);\n\nexport interface OpusStream {\n /** The OpusHead (RFC 7845): channels, pre-skip, channel mapping. */\n head: Uint8Array | null;\n channels: number;\n frames: Uint8Array[];\n /** Ogg's last granule position: where the sound really ends (the last frame is padded). */\n endGranule?: number;\n}\n\n/** A variable-length number in EBML: its length in bytes and value (the marker bit kept for ids, dropped for sizes). */\nfunction vint(bytes: Uint8Array, at: number, keepMarker: boolean): { length: number; value: number; unknown: boolean } | null {\n const first = bytes[at];\n if (first === undefined || first === 0) return null;\n const length = Math.clz32(first) - 23;\n if (at + length > bytes.length) return null;\n let value = keepMarker ? first : first & (0xff >> length);\n let allOnes = value === (0xff >> length);\n for (let i = 1; i < length; i++) {\n value = value * 256 + bytes[at + i]!;\n if (bytes[at + i] !== 0xff) allOnes = false;\n }\n return { length, value, unknown: !keepMarker && allOnes };\n}\n\n/** Elements whose children are read: EBML Segment, Tracks, TrackEntry, Audio, Cluster, BlockGroup. */\nconst WEBM_PARENTS = new Set([0x18538067, 0x1654ae6b, 0xae, 0xe1, 0x1f43b675, 0xa0]);\n\n/**\n * The Opus track of a WebM (Matroska) file. It reads the file in order, stepping into the elements that hold what it\n * needs rather than jumping by their sizes: MediaRecorder writes the Segment and every Cluster with an unknown size.\n */\nexport function demuxWebm(bytes: Uint8Array): OpusStream | null {\n interface Track { number: number; codec: string; head: Uint8Array | null; channels: number }\n const tracks: Track[] = [];\n const blocks: { track: number; data: Uint8Array }[] = [];\n let at = 0;\n while (at < bytes.length && blocks.length < MAX_OPUS_PACKETS) {\n const id = vint(bytes, at, true);\n if (!id) break;\n const size = vint(bytes, at + id.length, false);\n if (!size) break;\n const body = at + id.length + size.length;\n if (WEBM_PARENTS.has(id.value)) {\n if (id.value === 0xae) tracks.push({ number: 0, codec: \"\", head: null, channels: 0 });\n at = body;\n continue;\n }\n if (size.unknown) break;\n const end = Math.min(bytes.length, body + size.value);\n const data = bytes.subarray(body, end);\n const track = tracks.at(-1);\n if (id.value === 0xd7 && track) track.number = uint(data);\n else if (id.value === 0x86 && track) track.codec = ascii(data, 0, data.length);\n else if (id.value === 0x63a2 && track) track.head = data;\n else if (id.value === 0x9f && track) track.channels = uint(data);\n else if (id.value === 0xa3 || id.value === 0xa1) {\n const number = vint(data, 0, false);\n if (number) for (const frame of laced(data, number.length).slice(0, MAX_OPUS_PACKETS - blocks.length)) blocks.push({ track: number.value, data: frame });\n }\n at = end;\n }\n const opus = tracks.find((t) => t.codec === \"A_OPUS\");\n if (!opus) return null;\n return { head: opus.head, channels: opus.channels || 1, frames: blocks.filter((b) => b.track === opus.number).map((b) => b.data) };\n}\n\nfunction uint(data: Uint8Array): number {\n let value = 0;\n for (const byte of data) value = value * 256 + byte;\n return value;\n}\n\n/** The frames in a (Simple)Block after its track number: one, or several laced (Xiph, fixed-size or EBML). */\nfunction laced(data: Uint8Array, at: number): Uint8Array[] {\n const flags = data[at + 2]!;\n let pos = at + 3;\n const lacing = (flags >> 1) & 3;\n if (lacing === 0) return [data.subarray(pos)];\n const count = data[pos++]! + 1;\n const sizes: number[] = [];\n if (lacing === 1) {\n for (let i = 0; i < count - 1; i++) {\n let size = 0;\n for (let byte = 255; byte === 255; size += byte) byte = data[pos++]!;\n sizes.push(size);\n }\n } else if (lacing === 3) {\n const first = vint(data, pos, false)!;\n pos += first.length;\n sizes.push(first.value);\n for (let i = 1; i < count - 1; i++) {\n const delta = vint(data, pos, false)!;\n pos += delta.length;\n // A signed difference from the size before: the value less half its range.\n sizes.push(sizes[i - 1]! + delta.value - (2 ** (7 * delta.length - 1) - 1));\n }\n } else {\n const each = Math.floor((data.length - pos) / count);\n for (let i = 0; i < count - 1; i++) sizes.push(each);\n }\n sizes.push(data.length - pos - sizes.reduce((a, b) => a + b, 0));\n const frames: Uint8Array[] = [];\n for (const size of sizes) { frames.push(data.subarray(pos, pos + size)); pos += size; }\n return frames;\n}\n\n/** The first Opus stream of an Ogg file: its packets put back together from the pages' segments. */\nexport function demuxOgg(bytes: Uint8Array): OpusStream | null {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let serial: number | undefined;\n let head: Uint8Array | null = null;\n const frames: Uint8Array[] = [];\n let packet: Uint8Array[] = [];\n let endGranule: number | undefined;\n let at = 0;\n while (at + 27 <= bytes.length && ascii(bytes, at, 4) === \"OggS\" && frames.length < MAX_OPUS_PACKETS) {\n const segments = bytes[at + 26]!;\n const table = bytes.subarray(at + 27, at + 27 + segments);\n let pos = at + 27 + segments;\n const pageSerial = view.getUint32(at + 14, true);\n const granule = Number(view.getBigInt64(at + 6, true));\n const mine = serial === undefined ? ascii(bytes, pos, 8) === \"OpusHead\" : pageSerial === serial;\n if (mine) {\n serial = pageSerial;\n if (granule >= 0) endGranule = granule;\n for (const size of table) {\n if (frames.length >= MAX_OPUS_PACKETS) break;\n packet.push(bytes.subarray(pos, pos + size));\n pos += size;\n if (size < 255) {\n const whole = packet.length === 1 ? packet[0]! : Buffer.concat(packet);\n packet = [];\n if (!head) head = whole;\n else if (ascii(whole, 0, 8) !== \"OpusTags\") frames.push(whole);\n }\n }\n } else pos += table.reduce((a, b) => a + b, 0);\n at = pos;\n }\n if (!head) return null;\n return { head, channels: head[9] ?? 1, frames, endGranule };\n}\n\n/** Opus frames decoded at a time: about 2 s of sound at 20 ms a frame. */\nconst OPUS_BATCH = 100;\n\nasync function streamOpus(stream: OpusStream, sink: SoundSink): Promise<void> {\n const { OpusDecoder } = await import(\"opus-decoder\");\n const head = stream.head && ascii(stream.head, 0, 8) === \"OpusHead\" ? stream.head : null;\n const channels = head ? head[9]! : Math.max(1, stream.channels);\n const preSkip = head ? head[10]! | (head[11]! << 8) : 0;\n const family = head ? head[18]! : 0;\n const mapping = family !== 0 && head\n ? { streamCount: head[19]!, coupledStreamCount: head[20]!, channelMappingTable: [...head.subarray(21, 21 + channels)] }\n : { streamCount: 1, coupledStreamCount: channels - 1, channelMappingTable: channels === 1 ? [0] : [0, 1] };\n const decoder = new OpusDecoder({ channels, preSkip, ...mapping });\n await decoder.ready;\n try {\n // Ogg says where the sound ends; the rest of the last frame is padding.\n let left = stream.endGranule !== undefined && stream.endGranule > preSkip ? stream.endGranule - preSkip : Infinity;\n for (let at = 0; at < stream.frames.length && left > 0; at += OPUS_BATCH) {\n const decoded = decoder.decodeFrames(stream.frames.slice(at, at + OPUS_BATCH));\n if (!decoded.samplesDecoded) continue;\n sink.start(decoded.sampleRate);\n const length = Math.min(decoded.samplesDecoded, left);\n left -= length;\n if (!sink.push(decoded.channelData, length)) return;\n }\n } finally {\n decoder.free();\n }\n}\n\n// ---------- MP3 ----------\n\n/** MP3 bytes handed to the decoder at a time: about 16 s of a 128 kbit/s file. */\nconst MP3_PIECE = 256 * 1024;\n\n/** The MP3 in `pieces`, decoded one at a time (the decoder copies each in before the next is asked for). */\nasync function streamMp3(pieces: Iterable<Uint8Array> | AsyncIterable<Uint8Array>, sink: SoundSink): Promise<void> {\n const { MPEGDecoder } = await import(\"mpg123-decoder\");\n const decoder = new MPEGDecoder();\n await decoder.ready;\n try {\n let any = false;\n for await (const piece of pieces) {\n const decoded = decoder.decode(piece);\n if (!decoded.samplesDecoded) continue;\n any = true;\n sink.start(decoded.sampleRate);\n if (!sink.push(decoded.channelData, decoded.samplesDecoded)) return;\n }\n if (!any) throw new Error(\"no MP3 frames in it\");\n } finally {\n decoder.free();\n }\n}\n\n// ---------- ffmpeg ----------\n\n/** Anything ffmpeg reads, as a float WAV on its output (the channels kept, so they are averaged as above). */\nexport async function decodeWithFfmpeg(path: string, command = process.env.GHOSTLY_FFMPEG || \"ffmpeg\"): Promise<Sound> {\n const collector = new Collector();\n await streamFfmpeg(path, collector, command);\n return collector.sound();\n}\n\n/**\n * Anything ffmpeg reads, into `sink` as its WAV output comes: nothing kept but a frame cut between two pieces. Once\n * the sink wants no more, ffmpeg is stopped.\n */\nexport function streamFfmpeg(path: string, sink: SoundSink, command = process.env.GHOSTLY_FFMPEG || \"ffmpeg\"): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, [\"-v\", \"error\", \"-nostdin\", \"-i\", path, \"-vn\", \"-f\", \"wav\", \"-c:a\", \"pcm_f32le\", \"-\"], { stdio: [\"ignore\", \"pipe\", \"pipe\"], env: childEnv() });\n let errors = \"\", pending: Buffer = Buffer.alloc(0), header: ReturnType<typeof wavHeader> = null, done = false, failed: Error | null = null;\n let read: ((at: number) => number) | undefined, left = Infinity, timedOut = false;\n const timer = setTimeout(() => { timedOut = true; child.kill(\"SIGKILL\"); }, FFMPEG_TIMEOUT_MS);\n const stop = () => { done = true; child.stdout.removeAllListeners(\"data\"); child.kill(\"SIGKILL\"); };\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (done) return;\n pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;\n try {\n if (!header) {\n if (pending.length < 12) return;\n if (ascii(pending, 0, 4) !== \"RIFF\" || ascii(pending, 8, 4) !== \"WAVE\") throw new Error(\"ffmpeg gave no WAV\");\n header = wavHeader(pending);\n if (!header) { if (pending.length > 1024 * 1024) throw new Error(\"a WAV without sound\"); return; }\n const view = new DataView(pending.buffer, pending.byteOffset, pending.byteLength);\n if (!sampleReader(view, header.format, header.bits)) throw new Error(`a WAV in a format not read here (${header.format}, ${header.bits} bit)`);\n sink.start(header.sampleRate);\n left = header.to === Infinity ? Infinity : header.to - header.from;\n pending = pending.subarray(header.from);\n }\n const view = new DataView(pending.buffer, pending.byteOffset, pending.byteLength);\n read = sampleReader(view, header.format, header.bits)!;\n const to = Math.min(pending.length, left);\n const { at, more } = pushWavFrames(view, 0, to, header.channels, header.bits / 8, read, sink);\n if (left !== Infinity) left -= at;\n pending = Buffer.from(pending.subarray(at));\n if (!more || left <= 0) stop();\n } catch (error) {\n failed = error instanceof Error ? error : new Error(String(error));\n stop();\n }\n });\n child.stderr.on(\"data\", (chunk: Buffer) => { if (errors.length < 2000) errors += chunk.toString(); });\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n // The ffmpeg GHOSTLY_FFMPEG names not being there is the setting's fault: installing ffmpeg would not change it.\n const setting = process.env.GHOSTLY_FFMPEG;\n const missing = setting && command === setting\n ? `GHOSTLY_FFMPEG (${setting}) is not there: set it to ffmpeg's path, or unset it to use the one on the PATH`\n : \"no decoder here for this kind of audio (install ffmpeg to read it)\";\n reject(new Error(error.code === \"ENOENT\" ? missing : `ffmpeg: ${error.message}`));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n if (failed) { reject(failed); return; }\n // Stopped here because the sink had what it wanted: not a failure of ffmpeg's.\n if (done && header) { resolve(); return; }\n if (timedOut) { reject(new Error(`ffmpeg took more than ${FFMPEG_TIMEOUT_MS / 60_000} minutes to read it`)); return; }\n // ffmpeg reads any sound there is: one it could not read is none. Its first line, without the address of the\n // part that said it (\"[in#0 @ 0x57df52217c40] \"), which differs on every run.\n const said = errors.trim().split(\"\\n\")[0]!.replace(/\\[[^\\]]*@ 0x[0-9a-f]+\\]\\s*/gi, \"\");\n if (code !== 0) { reject(new NotSound(`ffmpeg could not read it${said ? `: ${said}` : \"\"}`)); return; }\n if (!header) { reject(new NotSound(\"a WAV without sound\")); return; }\n resolve();\n });\n });\n}\n","import { execFile } from \"node:child_process\";\nimport { openAsBlob } from \"node:fs\";\nimport { access, constants, copyFile, link, open, rename, rm, stat, writeFile, type FileHandle } from \"node:fs/promises\";\nimport { basename, dirname, extname, join, resolve, sep } from \"node:path\";\nimport { GROUP_FILE_LIMITS, LIMITS, NO_PICTURE_METADATA, NO_AUDIO_METADATA, NO_VIDEO_METADATA, PLAYABLE_AUDIO, VOICE_LIMITS, baseMime, claimedTime, parseVoiceMeta, randomBytes, readImageMeta, sanitizeFileName, sanitizeMime, toBase64Url, voiceDownloadName, withoutAudioMetadata, withoutPictureMetadata, withoutVideoMetadata, type VoiceMeta } from \"@ghostly/core\";\nimport { FILE_BYTES_STEP, fileBytes, fileBytesOf, type FileBytes } from \"@ghostly/browser/shared/fileBytes\";\nimport { fileStore } from \"@ghostly/browser/shared/idb\";\nimport { removeStored, waitingGroupFile } from \"@ghostly/browser/shared/storedFiles\";\nimport { replyRef } from \"@ghostly/browser/shared/replies\";\nimport type { EngineState, FileTransferView, GroupView, MessageFile, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { groupFileId, groupOfFile } from \"@ghostly/browser/engine/groupFiles\";\nimport { childEnv } from \"./childEnv\";\nimport { bool, chatOf, findChatOrGroup, keptForJoin, list, noFile, noMessage, node, num, oneOf, oneShotWaits, sentAt, state, str, waitForState, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { groupSendRefused } from \"./api\";\nimport { CliError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport { guardText } from \"./secretGuard\";\nimport { endTyping } from \"./typing\";\nimport { measureVoice } from \"./voicePeaks\";\nimport { goesOn } from \"./waits\";\n\n/**\n * Files and voice notes in a chat (WISP 1100, phase 3), as the app's composer sends them (packages/browser\n * platform/services.ts `sendFile`): the bytes go into the profile's file store first, then the engine offers them.\n * Large files follow files/3: the receiving side's person (here, a command) accepts or declines each offer.\n *\n * In a group (WISP 503 · Group Files) the file is announced as a group message, and each member's app fetches the\n * bytes from whoever holds them: by itself up to the automatic limits, on `file accept` past them.\n */\n\nconst TYPES: Record<string, string> = {\n \".png\": \"image/png\", \".jpg\": \"image/jpeg\", \".jpeg\": \"image/jpeg\", \".gif\": \"image/gif\", \".webp\": \"image/webp\",\n \".pdf\": \"application/pdf\", \".txt\": \"text/plain\", \".md\": \"text/markdown\", \".json\": \"application/json\", \".csv\": \"text/csv\",\n \".zip\": \"application/zip\", \".mp3\": \"audio/mpeg\", \".m4a\": \"audio/mp4\", \".ogg\": \"audio/ogg\", \".opus\": \"audio/ogg\", \".wav\": \"audio/wav\",\n \".aac\": \"audio/aac\", \".flac\": \"audio/flac\", \".oga\": \"audio/ogg\", \".weba\": \"audio/webm\",\n \".webm\": \"audio/webm\", \".mp4\": \"video/mp4\", \".mov\": \"video/quicktime\",\n};\n\n/** A voice note in an .mp4 is its sound in an MP4 box, as an .m4a: sent as audio/mp4, not as a video. */\nexport function mimeOf(path: string, given?: string, voice = false): string {\n const known = TYPES[extname(path).toLowerCase()];\n return sanitizeMime(given ?? (voice && known === \"video/mp4\" ? \"audio/mp4\" : known) ?? \"application/octet-stream\");\n}\n\n/**\n * The time a saved voice message is named from: its message's in the chat, as the apps' Download names it. The file's\n * own time is what its sender says (any safe integer, past Date's end too), taken only when no message is there and\n * a date can hold it; else when it was stored here.\n */\nasync function voiceTime(ctx: ApiContext, stored: { id: string; linkId: string; createdAt: number; metadata?: { timestamp: number } }): Promise<number> {\n // Past the newest, among the history's file rows only (the messages store's file index): the whole history, read for\n // each old voice message saved, held the daemon 0.8 s at 100,000 messages.\n const older = (linkId: string) => node(ctx).fileMessages(linkId);\n return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id, older))?.timestamp ?? claimedTime(stored.metadata?.timestamp) ?? stored.createdAt;\n}\n\n/**\n * The message of a chat or a group (`group:<id>`) that `test` picks: looked for among its newest first, where the one a\n * command names almost always is, then in all of them only when there are more. A whole history costs a read of every row;\n * `older` reads fewer, where the message is known to be among them.\n */\nasync function findMessage(ctx: ApiContext, linkId: string, test: (m: StoredMessage) => boolean, older?: (linkId: string) => Promise<StoredMessage[]>): Promise<StoredMessage | undefined> {\n const page = await node(ctx).messagePage({ linkId, limit: 200 });\n const newest = page.messages.find(test);\n if (newest || !page.more) return newest;\n if (older) return (await older(linkId)).find(test);\n const group = linkId.startsWith(\"group:\") ? linkId.slice(\"group:\".length) : undefined;\n return (group ? await node(ctx).groupMessages({ groupId: group }) : await node(ctx).getMessages(linkId)).find(test);\n}\n\n/** A chat's files as the timeline shows them, with where each transfer stands (`transferOf`, by file id). */\nexport function filesOf(messages: { id: string; file?: MessageFile; sender: string; timestamp: number }[], transferOf: (fileId: string) => unknown) {\n return messages.filter((m) => m.file).map((m) => ({\n messageId: m.id, from: m.sender, timestamp: m.timestamp,\n file: { id: m.file!.id, name: m.file!.name, size: m.file!.size, mime: m.file!.mime, ...(m.file!.voice ? { voice: m.file!.voice } : {}), ...(m.file!.image ? { image: m.file!.image } : {}) },\n transfer: transferOf(m.file!.id) ?? null,\n }));\n}\n\n/** A file's size as a person reads it: \"40 MB\", \"26.2 MB\". */\nconst megabytes = (size: number) => `${Math.round(size / 100_000) / 10} MB`;\n\n/**\n * Where an unfinished transfer stands, in words, for a person reading a timeout: the stage's id (\"asking\", \"waiting\")\n * stays in `details.stage` for a bot. A group's file says why it waits (`note`), as the app does.\n */\nfunction stageWords(transfer: FileTransferView): string {\n switch (transfer.stage) {\n case \"preparing\": return \"getting it ready to send\";\n case \"waiting\": return transfer.note ?? \"waiting for a connection to the contact\";\n case \"asking\": return transfer.direction === \"in\" ? \"waiting for you to take it (file accept)\" : \"waiting for the contact to take it\";\n case \"queued\": return \"waiting its turn\";\n case \"paused\": return transfer.pausedBy === \"peer\" ? \"paused by the contact\" : \"paused here (file resume)\";\n case \"verifying\": return \"every byte here, checking it\";\n default: return String(transfer.stage);\n }\n}\n\n/**\n * A transfer that waits for a person's decision (`asking`), with whose: `me` (`file accept` takes it here) or `contact`\n * (theirs). A received file's `transferring` alone read as if it were moving.\n */\nfunction withWaitingFor(transfer: FileTransferView | undefined): (FileTransferView & { waitingFor?: \"me\" | \"contact\" }) | undefined {\n if (transfer?.state !== \"transferring\" || transfer.stage !== \"asking\") return transfer;\n return { ...transfer, waitingFor: transfer.direction === \"in\" ? \"me\" : \"contact\" };\n}\n\n/** The chat or the group a file command names (`findChatOrGroup`). */\nconst chatOrGroupOf = (ctx: ApiContext, params: Params, { links, groups }: EngineState = state(ctx)) => findChatOrGroup(links, groups, str(params, \"chat\", true));\n\n/**\n * The chat or group a file belongs to: a file id starts with its chat's id (a group's file with `group-<id>-`), so it\n * may be left out; given, it must be the file's own. `where` is what the answer names it by.\n */\nfunction fileChat(ctx: ApiContext, params: Params, fileId: string): { linkId: string; where: { chat: string } | { group: string } } {\n const s = state(ctx);\n const groupId = groupOfFile(fileId, s.groups.map((g) => g.id));\n if (groupId) {\n const named = params.chat === undefined ? undefined : chatOrGroupOf(ctx, params, s);\n if (named && !(\"group\" in named && named.group.id === groupId)) throw noFile(fileId, { group: \"group\" in named, ref: str(params, \"chat\", true) });\n return { linkId: `group:${groupId}`, where: { group: groupId } };\n }\n const link = params.chat === undefined\n ? s.links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`))\n : chatOf(ctx, params, s);\n if (!link) throw noFile(fileId);\n if (!fileId.startsWith(`${link.id}-`)) throw noFile(fileId, { group: false, ref: str(params, \"chat\", true) });\n return { linkId: link.id, where: { chat: link.id } };\n}\n\nconst VOICE_MINUTES = VOICE_LIMITS.maxDurationMs / 60_000;\n\n/**\n * `--voice [ms] [--peaks …]`: the voice description, its length and waveform measured from the sound when not given.\n * A file that is not a voice note is refused naming what is wrong with it: empty, not audio, too long.\n */\nasync function voiceOf(params: Params, path: string, mime: string, size: number): Promise<{ voice?: VoiceMeta; warning?: string }> {\n if (params.voice === undefined) return {};\n const name = basename(path);\n if (!size) throw new CliError(\"bad_request\", `${name} is empty: a voice note is audio`);\n if (!PLAYABLE_AUDIO.test(baseMime(mime))) throw new CliError(\"bad_request\", `${name} is ${mime}, not audio (webm, ogg, opus, mp4, m4a, mpeg, aac, wav or flac)`);\n // Without a length or a waveform, both are measured from the sound, as the apps measure their recordings.\n const given = params.voice === true ? undefined : num(params, \"voice\", 0, { min: 1 });\n let duration = given;\n let peaks = list(params, \"peaks\").map(Number);\n let warning: string | undefined;\n if (duration === undefined || !peaks.length) {\n const measured = await measureVoice(path);\n if (\"voice\" in measured) {\n duration ??= measured.voice.duration;\n if (!peaks.length) peaks = measured.voice.peaks;\n } else if (measured.notSound) {\n // A length given for it would send a voice note that cannot play.\n throw new CliError(\"bad_request\", `${name} is not audio (${measured.problem})`);\n } else if (duration === undefined) {\n throw new CliError(\"bad_request\", `Could not measure the voice note (${measured.problem}): give its length as --voice <ms>`);\n } else warning = `Sent without a waveform: could not read the sound (${measured.problem})`;\n }\n const voice = parseVoiceMeta({ duration, peaks: peaks.length ? peaks : new Array(VOICE_LIMITS.bars).fill(0) }, mime);\n if (voice) return { voice, ...(warning ? { warning } : {}) };\n // A length past the limit (with the moment a recorder takes to stop), or else a waveform the voice note does not take.\n if (duration! > VOICE_LIMITS.maxDurationMs + 5_000) {\n throw new CliError(\"bad_request\", given === undefined\n ? `${name} is longer than ${VOICE_MINUTES} minutes: a voice note is at most ${VOICE_MINUTES}`\n : `A voice note is at most ${VOICE_MINUTES} minutes (${VOICE_LIMITS.maxDurationMs} ms), not ${given} ms`);\n }\n throw new CliError(\"bad_request\", `A voice note's waveform is 1 to ${VOICE_LIMITS.maxBars} peaks from 0 to 255`);\n}\n\n/**\n * The file at `path` as it is sent, as the apps send it (platform/services.ts `sendable`): a picture, an MP4 or\n * QuickTime video or an audio file without its metadata (where it was taken or recorded, the device, the time, an\n * audio file's tags), before its size is read and its digest computed. One whose metadata cannot be removed is\n * refused, never sent as it was. A voice note is a file made anywhere, so its tags go too.\n */\nasync function sendable(path: string, mime: string): Promise<Blob> {\n const source = await openAsBlob(path, { type: mime });\n try {\n return await withoutPictureMetadata(source, mime) ?? await withoutVideoMetadata(source, mime) ?? await withoutAudioMetadata(source, mime) ?? source;\n } catch (error) {\n if (error instanceof Error && [NO_PICTURE_METADATA, NO_VIDEO_METADATA, NO_AUDIO_METADATA].includes(error.message)) throw new CliError(\"refused\", error.message);\n throw error;\n }\n}\n\n/**\n * A read of the file at `path` through the Blob `openAsBlob` gave it. Node refuses every read of that Blob once the file\n * changed on disk (it grew, shrank or was written again: a log still written to, a file being saved), with a bare\n * DOMException \"The blob could not be read\" that named neither the file nor why, as `engine`. Said with its path, as\n * `unavailable`: sent again once nothing writes to it, it goes, and nothing of this try was kept (`stage` removes its copy).\n */\nasync function whileUnchanged<T>(path: string, read: () => Promise<T>): Promise<T> {\n try { return await read(); } catch (error) {\n if (error && typeof error === \"object\" && (error as { name?: unknown }).name === \"NotReadableError\") {\n throw new CliError(\"unavailable\", `${path} changed while it was being sent: send it again once nothing is writing to it`, { reason: \"file_changed\", path });\n }\n throw error;\n }\n}\n\n/**\n * The file copied into the profile (`stage`) for a send whose client is still there to hear of it (`CallScope.gone`).\n * Ctrl-C on `file send` through a daemon, while a large file was copied in (seconds per GiB), said \"stopped before the\n * command answered\"; the daemon went on, and the file went to the contact a moment later. Sent again, it went twice.\n * The copy stops at its next step, and what was copied is removed: nothing is in the chat, nothing goes.\n */\nasync function stageWhileAsked(bytes: FileBytes, id: string, path: string, source: Blob, gone: AbortSignal | undefined): Promise<string> {\n const stillAsked = () => {\n if (gone?.aborted) throw new CliError(\"interrupted\", \"The file was not sent: the command that sent it went away before it was copied in\");\n };\n const digest = await whileUnchanged(path, () => bytes.stage(id, source, stillAsked));\n // Gone after the last step: the whole copy is there, and goes too.\n if (gone?.aborted) await bytes.remove(id).catch(() => {});\n stillAsked();\n return digest;\n}\n\n/**\n * A file announced in a group (WISP 503): its bytes staged under a group file id with their digest, as a chat's are, then\n * the announcement. This device is its first holder and serves the members who ask.\n */\nasync function sendToGroup(ctx: ApiContext, params: Params, group: GroupView, path: string, name: string, picked: number, gone: AbortSignal | undefined) {\n if (picked > GROUP_FILE_LIMITS.maxBytes) throw new CliError(\"refused\", `Too large for a group (at most ${GROUP_FILE_LIMITS.maxBytes} bytes)`);\n if (!picked) throw new CliError(\"refused\", \"An empty file cannot go to a group\");\n const mime = mimeOf(path, str(params, \"mime\"), params.voice !== undefined);\n const replyTo = str(params, \"reply\");\n if (replyTo) {\n if (!await findMessage(ctx, `group:${group.id}`, (m) => m.id === replyTo || replyRef(m) === replyTo)) throw noMessage(replyTo, { group: true, ref: str(params, \"chat\", true) }, { tail: \", or it cannot be replied to\" });\n }\n // A send the group would refuse anyway (its files of the minute are taken, or this device is not in it) is refused\n // before a byte is copied in: a retry loop writes nothing. The announcement checks again.\n const check = await node(ctx).groupFileCheck({ groupId: group.id });\n if (check.error) throw check.refused ? new CliError(\"refused\", check.error) : groupSendRefused(check.error);\n const { voice, warning } = await voiceOf(params, path, mime, picked);\n const source = await whileUnchanged(path, () => sendable(path, mime));\n const size = source.size;\n const image = voice ? undefined : await whileUnchanged(path, () => readImageMeta(source, mime));\n const fileId = groupFileId(group.id, \"out\");\n const file: MessageFile = { id: fileId, name, size, mime, ...(voice ? { voice } : {}), ...(image ? { image } : {}) };\n const timestamp = Date.now();\n const bytes = await fileBytes();\n const digest = await stageWhileAsked(bytes, fileId, path, source, gone);\n await fileStore.put({\n id: fileId, linkId: `group:${group.id}`, bytes: bytes.kind, digest, createdAt: timestamp, direction: \"out\",\n metadata: { name: file.name, size, mime, timestamp, ...(voice ? { voice } : {}), ...(image ? { image } : {}) },\n transfer: { state: \"transferring\", transferred: 0, size },\n });\n endTyping(ctx, { groupId: group.id }, false);\n const result = await node(ctx).sendGroupFile({ groupId: group.id, file, ...(replyTo ? { replyTo } : {}) });\n if (result.error) {\n // Not announced: nothing is in the group, so the staged copy goes too.\n await removeStored(fileId).catch(() => {});\n throw result.refused ? new CliError(\"refused\", result.error) : groupSendRefused(result.error);\n }\n return { group: group.id, messageId: result.messageId ?? null, file: { id: fileId, name: file.name, size, mime, ...(voice ? { voice: true } : {}), ...(image ? { image } : {}) }, ...(warning ? { warning } : {}) };\n}\n\n/** Bytes a file system takes in one name: 255 on ext4, btrfs, APFS (NTFS counts 255 UTF-16 units, within this too). */\nconst NAME_BYTES = 255;\n\n/**\n * `name` as an entry of a folder: an app's name may have 200 characters, which in UTF-8 can be 800 bytes. The end of\n * its stem goes until it fits, its extension stays (as `sanitizeFileName` shortens it), so \"文…文.txt\" is saved as a text.\n */\nexport function fitName(name: string): string {\n const fits = (candidate: string) => Buffer.byteLength(candidate) <= NAME_BYTES;\n if (fits(name)) return name;\n const extension = /\\.[^.\\s]{1,15}$/u.exec(name)?.[0] ?? \"\";\n const stem = [...name.slice(0, name.length - extension.length)];\n while (stem.length && !fits(stem.join(\"\").trimEnd() + extension)) stem.pop();\n return (stem.join(\"\").trimEnd() || \"file\") + extension;\n}\n\n/**\n * The name `file save --dir` writes a file under. Its sender chose it, and the folder is one scripts and people run\n * tools in: a name that starts with a dash is an option to the tool a `*` hands it to (\"-rf\", \"--checkpoint-action=…\"),\n * so it gets a `_` first, as a Windows device name does in `sanitizeFileName`.\n */\nexport function saveName(name: string): string {\n const clean = sanitizeFileName(name);\n return fitName(clean.startsWith(\"-\") ? `_${clean}` : clean);\n}\n\n/**\n * Gives the whole file at `partial` the name `target`: over a file there when `force`, else never (EEXIST). Where the\n * file system has no hard links (exFAT, some network shares), it is copied under the name, still never over a file.\n */\nasync function place(partial: string, target: string, force: boolean): Promise<void> {\n if (force) return rename(partial, target);\n try { await link(partial, target); } catch (error) {\n if (![\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"].includes((error as NodeJS.ErrnoException).code ?? \"\")) throw error;\n await copyFile(partial, target, constants.COPYFILE_EXCL);\n }\n}\n\n/**\n * Marks a saved copy of a contact's file as downloaded, as a browser and Ghostly Desktop (`file_store.rs`\n * `mark_downloaded`) do, so the system checks it when it is opened: Gatekeeper's \"downloaded from the internet\" on\n * macOS, SmartScreen and Office's Protected View on Windows. Node has no extended attributes, so macOS's own `xattr`\n * writes `com.apple.quarantine`; on Windows it is the file's `Zone.Identifier` stream. Best effort: a file system that\n * cannot hold the mark still gets the file.\n */\nasync function markDownloaded(path: string): Promise<void> {\n if (process.platform === \"darwin\") {\n // Flags 0x0001 (downloaded) and 0x0080, as browsers write them; then time and agent.\n const value = `0081;${Math.floor(Date.now() / 1000).toString(16).padStart(8, \"0\")};Ghostly;`;\n await new Promise<void>((done) => execFile(\"/usr/bin/xattr\", [\"-w\", \"com.apple.quarantine\", value, path], { timeout: 10_000, env: childEnv() }, () => done()));\n } else if (process.platform === \"win32\") {\n await writeFile(`${path}:Zone.Identifier`, \"[ZoneTransfer]\\r\\nZoneId=3\\r\\n\").catch(() => {});\n }\n}\n\nconst ACTIONS = [\"accept\", \"decline\", \"pause\", \"resume\", \"cancel\", \"resend\", \"request\"] as const;\n\n/**\n * `file wait`: until a transfer ends: done answers, failed is an `engine` error with the transfer's words (and whether\n * `file resend` can go on). A file whose transfer this run has not seen answers from the file store. `stopping`: the\n * daemon's stop ends it as well (`waitForState`), for `file send --wait`, which answers with what it knows then.\n */\nasync function waitForFile(ctx: ApiContext, params: Params, stopping?: AbortSignal) {\n const fileId = str(params, \"file\", true);\n const { where } = fileChat(ctx, params, fileId);\n const stored = await fileStore.get(fileId);\n if (!stored && !state(ctx).transfers[fileId]) throw noFile(fileId);\n const ms = num(params, \"timeout\", 300, { min: 1, max: 86_400 }) * 1000;\n // A received file that waits for this person's `file accept` (over 25 MiB, or a group's file that did not come by\n // itself) does not move however long this waits: said at once, naming the command. Before, it waited out its\n // timeout and answered \"0 of 40000000 bytes, asking\", as if the contact were slow.\n const transfer = await waitForState(ctx, (s) => {\n const now = s.transfers[fileId] ?? stored?.transfer;\n return now && (now.state === \"done\" || now.state === \"failed\" || (now.stage === \"asking\" && now.direction === \"in\")) ? now : undefined;\n }, ms, `file ${fileId} to arrive`, stopping).catch((error: unknown) => {\n const now = state(ctx).transfers[fileId];\n if (error instanceof CliError && error.code === \"timeout\" && now) throw new CliError(\"timeout\", `${error.message} (${now.transferred} of ${now.size} bytes${now.stage ? `, ${stageWords(now)}` : \"\"})`, { file: fileId, transferred: now.transferred, size: now.size, stage: now.stage ?? null, ...(error.details?.reason ? { reason: error.details.reason } : {}) });\n throw error;\n });\n if (transfer.state === \"failed\") throw new CliError(\"engine\", transfer.error ?? \"The transfer failed\", { file: fileId, ...where, retry: !!transfer.retry });\n if (transfer.state !== \"done\") throw waitsForYou((stored ?? await fileStore.get(fileId).catch(() => undefined))?.metadata?.name, fileId, where, transfer.size);\n return { ...where, file: fileId, state: \"done\", size: transfer.size };\n}\n\n/**\n * `file accept` of a file that does not fit the room left beside the files still coming (`FileDesk.accept`), in this\n * CLI's MB: the engine's line gave the room in binary MB beside a size in decimal ones, and neither the files still\n * coming that take the rest nor the way out.\n */\nfunction noRoomWords(fileId: string, name: string | undefined, size: number, room: number, coming: number): string {\n const rest = coming > 0 ? `, and ${megabytes(coming)} of files still coming need it first` : \"\";\n return `${name ?? \"The file\"} (${megabytes(size)}) does not fit: ${megabytes(room)} free${rest}. Free some space, then ghostly file accept ${fileId} again (or file decline)`;\n}\n\n/** A received file that waits for this person's `file accept` (`file wait`, `file save`): said naming the command. */\nfunction waitsForYou(name: string | undefined, fileId: string, where: { chat: string } | { group: string } | undefined, size: number): CliError {\n return new CliError(\"confirm\", `${name ?? \"The file\"} (${megabytes(size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, { file: fileId, ...where, size, stage: \"asking\" });\n}\n\nexport const FILE_METHODS: Record<string, Method> = {\n async \"file.send\"(ctx, params, call) {\n const path = resolve(str(params, \"path\", true));\n // The contact (or every member) reads its name as a message's text (docs/CLI.md § Safety): the name that goes out,\n // the file's own without --name, read once cleaned (a key split by a `:` or a line break the cleaning drops is whole).\n const name = sanitizeFileName(str(params, \"name\") ?? basename(path));\n guardText(name, bool(params, \"force\"), \"file's name\", \"send it\");\n const target = chatOrGroupOf(ctx, params);\n let info;\n try { info = await stat(path); } catch { throw new CliError(\"not_found\", `No file ${path}`); }\n if (!info.isFile()) throw new CliError(\"bad_request\", `${path} is not a file`);\n // A file this user may not read: refused with its path (errors.ts), not the engine's \"The blob could not be read\" later.\n await access(path, constants.R_OK);\n // A one-shot leaves once its command is done, and the transfer with it: in a chat it stays until the contact has the\n // whole file, as `send` stays until its message went out. Before, it left in under a second with nothing sent, and\n // the contact saw the file only with a later command that stayed online long enough. A group's file, or one to a chat\n // nobody joined yet: none.\n const wait = oneOf(params, \"wait\", \"group\" in target ? [\"none\"] as const : [\"none\", \"sent\"] as const, !(\"group\" in target) && oneShotWaits(ctx, target.link.id) ? \"sent\" : \"none\");\n const seconds = num(params, \"timeout\", 300, { min: 1, max: 86_400 });\n if (\"group\" in target) return sendToGroup(ctx, params, target.group, path, name, info.size, call?.gone);\n const { link } = target;\n if (link.profile && link.dataLink === \"open\" && !link.capabilities?.files) throw new CliError(\"unavailable\", \"The contact's app takes no files\");\n // Only a session open now says what the contact's app takes: with none (the contact away), the file waits and goes\n // as files/3 on the next one (the engine's `sendWaitingFile`), as the app's composer sends it.\n if (link.dataLink === \"open\" && !link.capabilities?.largeFiles && info.size > LIMITS.maxFileBytes) throw new CliError(\"refused\", `Too large for the contact's app (at most ${LIMITS.maxFileBytes} bytes)`);\n if (typeof link.peerFileRoom === \"number\" && info.size > link.peerFileRoom) throw new CliError(\"refused\", `Not enough space on the contact's device (${link.peerFileRoom} bytes free)`);\n const mime = mimeOf(path, str(params, \"mime\"), params.voice !== undefined);\n // A reply names a message of this chat, as `send --reply` does: checked before anything is stored.\n const replyTo = str(params, \"reply\");\n if (replyTo) {\n if (!await findMessage(ctx, link.id, (m) => m.id === replyTo || replyRef(m) === replyTo)) throw noMessage(replyTo, { group: false, ref: str(params, \"chat\", true) }, { tail: \", or it cannot be replied to\" });\n }\n const { voice, warning } = await voiceOf(params, path, mime, info.size);\n const source = await whileUnchanged(path, () => sendable(path, mime));\n // A picture goes with its size, read from its first bytes as the apps read it (PNG, JPEG, GIF, WebP).\n const image = voice ? undefined : await whileUnchanged(path, () => readImageMeta(source, mime));\n const wireId = toBase64Url(randomBytes(12));\n const file: MessageFile = { id: `${link.id}-out-${wireId}`, name, size: source.size, mime, ...(voice ? { voice } : {}), ...(image ? { image } : {}) };\n const timestamp = sentAt();\n const bytes = await fileBytes();\n const digest = await stageWhileAsked(bytes, file.id, path, source, call?.gone);\n await fileStore.put({\n id: file.id, linkId: link.id, bytes: bytes.kind, digest, createdAt: timestamp, direction: \"out\", wireId,\n metadata: { name: file.name, size: file.size, mime: file.mime, timestamp, ...(voice ? { voice } : {}), ...(image ? { image } : {}) },\n transfer: { state: \"transferring\", transferred: 0, size: file.size },\n });\n endTyping(ctx, { linkId: link.id }, true);\n try {\n await node(ctx).sendFile({ linkId: link.id, file, timestamp, ...(replyTo ? { replyTo } : {}) });\n } catch (error) {\n // Refused before it started (offline, a stopped chat, a contact whose app takes no files): nothing is in the chat,\n // so the staged copy goes too.\n await removeStored(file.id).catch(() => {});\n throw new CliError(\"refused\", error instanceof Error ? error.message : String(error));\n }\n // The message's id, as a group's file and `send` answer it: what `message delete`, `react`, `pin` and `--reply` take.\n // The engine names a sent file's row after its time (node.ts `sendFile`), the one given here.\n const messageId = `me_${timestamp}`;\n // A wait that ends short (its time, or the daemon's stop: a restart) leaves the file in the chat, going on as a text\n // does (waits.ts): said so, with its ids. A stop ended the connection under it before, with no id to look for.\n if (wait === \"sent\") await waitForFile(ctx, { chat: link.id, file: file.id, timeout: seconds }, ctx.stopping).catch((error: unknown) => {\n if (!(error instanceof CliError) || error.code !== \"timeout\") throw error;\n throw new CliError(\"timeout\", `${error.message}. It is kept here and ${goesOn(ctx, link.id)}`, { ...error.details, chat: link.id, messageId, file: file.id });\n });\n return {\n chat: link.id, messageId, file: { id: file.id, name: file.name, size: file.size, mime: file.mime, ...(voice ? { voice: true } : {}), ...(image ? { image } : {}) }, ...(warning ? { warning } : {}),\n ...keptForJoin(ctx, link.id, \"the file\"),\n };\n },\n\n async \"file.list\"(ctx, params) {\n const target = chatOrGroupOf(ctx, params);\n const views = state(ctx).transfers;\n // A file that finished before this run has no transfer in the engine's state: its record says it is done. Nor has a\n // group's file waiting for a Download: its record says it is not here. Nor has a chat's file sent to a contact who is\n // away, until they are back: its record says how far it went, and it waits for them.\n const keptOf = async (linkId: string) => new Map((await fileStore.listForLink(linkId).catch(() => [])).flatMap((f) => {\n const kept = f.transfer?.state === \"done\" ? { ...f.transfer, direction: f.direction }\n : !(\"group\" in target) && f.transfer?.state === \"transferring\" && f.direction === \"out\" ? { ...f.transfer, direction: f.direction, stage: \"waiting\" as const, waitingFor: \"contact\" as const }\n : waitingGroupFile(f);\n return kept ? [[f.id, kept] as const] : [];\n }));\n // The history's file rows only (the messages store's file index): a bot polling this in a chat of 9,000 texts read\n // every one of them each time (75 ms), with the daemon's other calls waiting behind it.\n const linkId = \"group\" in target ? `group:${target.group.id}` : target.link.id;\n const kept = await keptOf(linkId);\n const files = filesOf(await node(ctx).fileMessages(linkId), (id) => withWaitingFor(views[id] ?? kept.get(id)));\n return \"group\" in target ? { group: target.group.id, files } : { chat: target.link.id, files };\n },\n\n /**\n * files/3: answer an offer, or pause, resume or cancel a transfer, either way; `resend` a file sent from here that\n * stopped moving (or failed), `request` again one that stopped arriving. Without a chat, the file's id names it.\n * A group's file (WISP 503) takes `accept` (download one this device did not fetch by itself), `request`, and `cancel`,\n * `decline`, `pause` and `resume` for one that is coming.\n */\n async \"file.action\"(ctx, params) {\n const fileId = str(params, \"file\", true);\n const { linkId, where } = fileChat(ctx, params, fileId);\n const action = oneOf(params, \"action\", ACTIONS, \"accept\");\n // One all here has no transfer in the engine's state, only its record; the engine takes any action on it and does nothing.\n const refuseAllHere = async () => {\n if ((state(ctx).transfers[fileId] ?? (await fileStore.get(fileId).catch(() => undefined))?.transfer)?.state === \"done\") throw new CliError(\"refused\", action === \"accept\" || action === \"request\" || action === \"resume\" ? \"Nothing to ask for: the file is all here\" : \"Nothing to stop: the file is all here\");\n };\n if (\"group\" in where) {\n if (action === \"resend\") throw new CliError(\"bad_request\", \"A group's file is downloaded (file accept) or asked for again (file request)\");\n await refuseAllHere();\n try { await node(ctx).fileAction({ linkId, fileId, action }); } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n return { ...where, file: fileId, action, transfer: state(ctx).transfers[fileId] ?? null };\n }\n // No longer here (its sender deleted it for everyone, its message was deleted here) or never was: no transfer and\n // no record. Said as `file save` and `file wait` say it; `request` read the missing transfer as \"all here\" before,\n // and the other actions answered the engine's \"No such file transfer\".\n if (!state(ctx).transfers[fileId] && !(await fileStore.get(fileId).catch(() => undefined))) throw noFile(fileId);\n if (action === \"resend\" || action === \"request\") {\n const outgoing = fileId.startsWith(`${linkId}-out-`);\n if (outgoing !== (action === \"resend\")) throw new CliError(\"bad_request\", outgoing ? \"A file sent from here is sent again: file resend\" : \"A received file is asked for again: file request\");\n const transfer = state(ctx).transfers[fileId];\n if (!transfer || transfer.state === \"done\") throw new CliError(\"refused\", outgoing ? \"Nothing to send again: it arrived whole\" : \"Nothing to ask for: the file is all here\");\n if (transfer.state === \"failed\" && (!outgoing || !transfer.retry)) throw new CliError(\"refused\", `It ended: ${transfer.error ?? \"failed\"}`);\n } else {\n const outgoing = fileId.startsWith(`${linkId}-out-`);\n if (outgoing && (action === \"accept\" || action === \"decline\")) throw new CliError(\"bad_request\", \"A file sent from here is not accepted or declined: file cancel stops it\");\n await refuseAllHere();\n // One that ended (cancelled, declined, failed): the engine takes the action and does nothing, as for one all here.\n const transfer = state(ctx).transfers[fileId] ?? (await fileStore.get(fileId).catch(() => undefined))?.transfer;\n // Being checked (sent: the contact checks it; received: its digest here): the engine takes no pause and it ends done.\n if (action === \"pause\" && transfer?.stage === \"verifying\") throw new CliError(\"refused\", \"Too late to pause: it is being checked\");\n if (transfer?.state === \"failed\") throw new CliError(\"refused\", `It ended: ${transfer.error ?? \"failed\"}${outgoing && transfer.retry ? \" (file resend sends it again)\" : \"\"}`);\n // Sent whole (the engine's `sentWhole`): the engine takes no cancel or pause and it ends done, so it is refused, not echoed.\n const whole = outgoing && transfer?.state === \"transferring\" && (transfer.stage === \"verifying\"\n || (transfer.size > 0 && transfer.transferred >= transfer.size && transfer.stage !== \"asking\" && transfer.stage !== \"queued\" && transfer.stage !== \"paused\"));\n if (whole && action === \"cancel\") throw new CliError(\"refused\", \"Too late to cancel: it arrived whole, and the contact keeps it\");\n if (whole && action === \"pause\") throw new CliError(\"refused\", \"Too late to pause: it arrived whole, and the contact keeps it\");\n }\n // Paused by the contact: only their resume moves it. The engine takes these and does nothing, and it stays paused.\n const view = state(ctx).transfers[fileId];\n if ((action === \"resume\" || action === \"request\" || action === \"resend\") && view?.stage === \"paused\" && view.pausedBy === \"peer\") {\n throw new CliError(\"refused\", \"Paused by the contact: it goes on when they resume it\");\n }\n // Offered here and not taken yet: the engine takes these and does nothing, and it still waits for the answer.\n if ((action === \"pause\" || action === \"resume\" || action === \"request\") && view?.stage === \"asking\" && view.direction === \"in\") {\n throw new CliError(\"refused\", \"Not taken yet: it waits for you to take it (file accept, or file decline)\");\n }\n // Larger than the room this device has left now (`FileDesk.accept`): not started, it keeps waiting for the answer.\n try {\n await node(ctx).fileAction({ linkId, fileId, action });\n } catch (error) {\n const { room, size, coming } = (error ?? {}) as { room?: unknown; size?: unknown; coming?: unknown };\n if (action === \"accept\" && error instanceof Error && typeof room === \"number\" && error.message.startsWith(\"No room on this device\")) {\n throw new CliError(\"refused\", noRoomWords(fileId, (await fileStore.get(fileId).catch(() => undefined))?.metadata?.name, typeof size === \"number\" ? size : view?.size ?? 0, room, typeof coming === \"number\" ? coming : 0), { reason: \"no_room\", room });\n }\n throw error;\n }\n return { ...where, file: fileId, action, transfer: state(ctx).transfers[fileId] ?? null };\n },\n\n async \"file.wait\"(ctx, params) {\n return waitForFile(ctx, params);\n },\n\n /**\n * Writes a received (or sent) file to disk: into `dir` under its own name (`saveName`), a voice message under the one\n * Ghostly makes for it as the apps' Download does (`voiceDownloadName`, never the sender's; \"<name> (2)\" when taken),\n * or to `path`. Never over a file unless `force`.\n */\n async \"file.save\"(ctx, params) {\n const fileId = str(params, \"file\", true);\n if (params.chat !== undefined) fileChat(ctx, params, fileId);\n // A sent file is all here (below): --wait waited for the contact's download, and failed with their decline.\n if (bool(params, \"wait\") && (await fileStore.get(fileId))?.direction !== \"out\") await FILE_METHODS[\"file.wait\"](ctx, { file: fileId, timeout: params.timeout });\n const stored = await fileStore.get(fileId);\n if (!stored?.metadata) throw noFile(fileId);\n if (stored.leftOut) throw new CliError(\"not_found\", \"Not in this backup: the light backup this profile was restored from left the file out\");\n // A sent file's bytes were staged whole at send: its transfer is the contact's download, not bytes missing here.\n // A group's file waiting for a Download has no transfer in the engine's state: its record says it waits.\n const transfer = stored.direction === \"out\" ? undefined : state(ctx).transfers[fileId] ?? waitingGroupFile(stored) ?? stored.transfer;\n // One that ended will not come: its partial bytes were dropped, so \"not all here yet\" would have a script wait for good.\n if (transfer?.state === \"failed\") throw new CliError(\"refused\", `It ended: ${transfer.error ?? \"failed\"}`);\n // Nor will one that waits for `file accept`: said naming it, as --wait does. It answered \"not all here yet (0 of N\n // bytes)\" before, and a script retried it for good.\n if (transfer?.state === \"transferring\" && transfer.stage === \"asking\" && transfer.direction === \"in\") {\n let where;\n try { where = fileChat(ctx, params, fileId).where; } catch { /* a chat no longer here: the file's id names it */ }\n throw waitsForYou(stored.metadata.name, fileId, where, transfer.size);\n }\n if (transfer && transfer.state !== \"done\") throw new CliError(\"unavailable\", `The file is not all here yet (${transfer.transferred} of ${transfer.size} bytes)`);\n const named = str(params, \"path\") ? resolve(str(params, \"path\", true)) : join(resolve(str(params, \"dir\") ?? \".\"), saveName(stored.metadata.voice ? voiceDownloadName(stored.metadata.mime, await voiceTime(ctx, stored)) : stored.metadata.name));\n const force = bool(params, \"force\");\n // A --path that ends in a separator names a folder: resolve() dropped the slash, and \"--path downloads/\" with no\n // downloads folder left a file named downloads. A folder that is there is answered below, as without the slash. One\n // that is not hints no --dir: before, it hinted --dir <that folder>, and that failed \"No such file or folder\".\n const path = str(params, \"path\");\n if (path && (path.endsWith(\"/\") || path.endsWith(sep))) {\n const there = await stat(named).catch(() => undefined);\n if (!there) throw new CliError(\"not_found\", `No such folder: ${named} (make it first, or name a file in a folder that is there)`);\n if (!there.isDirectory()) throw new CliError(\"not_found\", `${named} is a file, not a folder: name a file in a folder that is there`);\n }\n // A voice message's name is Ghostly's, down to the second its sender claims: two of one second took one name, and\n // the --force the confirm hinted at replaced the first recording with the other. In --dir it steps to a free\n // \"<name> (2)\", as a browser's Download does; a --path the user named is never renamed.\n const free = !force && !str(params, \"path\") && !!stored.metadata.voice;\n const ext = extname(named), stem = named.slice(0, named.length - ext.length);\n // The next \"<name> (n)\" a voice message steps to.\n let next = 2;\n // What is at `target` that the save may not go over, as the error that says so; nothing when it may.\n const taken = async (target: string, code?: string): Promise<CliError | undefined> => {\n const there = await stat(target).catch(() => undefined);\n // A folder there is no file to replace: before, it asked for --force, and the --force then failed \"is a folder\".\n // A voice message in --dir steps past it as past a file: before, it stopped there and named that folder for --dir.\n if (there?.isDirectory() && free && next <= 1000) return new CliError(\"confirm\", `${target} is a folder`);\n if (there?.isDirectory()) return new CliError(\"bad_request\", `${target} is a folder: name a file, or use --dir ${shellWord(target, \"<the one in details.dir>\")} (dir over the socket)`, { dir: target });\n if (!((there && !force) || code === \"EEXIST\")) return;\n const replace = `${target} exists: pass --force (force: true over the socket) to replace it`;\n if (path) return new CliError(\"confirm\", replace);\n // A voice message steps on to the next name: no hint is shown. Before, each step looked for one from \"(2)\" anyway,\n // ~k²/2 stats at k copies of its name (12-16 s at 999).\n if (free && next <= 1000) return new CliError(\"confirm\", replace);\n // In --dir the name is its sender's: two files of one name are two files. Before, --force was the one way out\n // named, and it replaced the other. The next free \"<name> (2)\" is offered, never taken unasked.\n let n = 2;\n while (n <= 1000 && (await stat(`${stem} (${n})${ext}`).catch(() => undefined))) n += 1;\n const other = `${stem} (${n})${ext}`;\n return new CliError(\"confirm\", `${replace}, or --path ${shellWord(other, \"<the one in details.path>\")} (path over the socket) to keep both`, { path: other });\n };\n let target = named;\n for (let refused = await taken(target); refused; refused = await taken(target)) {\n if (!free || refused.code !== \"confirm\" || next > 1000) throw refused;\n target = `${stem} (${next})${ext}`;\n next += 1;\n }\n // The bytes go beside it first and take its name only once whole: a save that fails (the bytes not on this device, a\n // full disk) leaves no file, and with --force the one it was to replace as it was. Before, --force emptied that file\n // as it opened it, and the failure removed it.\n const partial = join(dirname(target), `.ghostly-save-${process.pid}-${toBase64Url(randomBytes(6))}.partial`);\n // That name is the save's own: never typed, new on every try, gone after. An error on it (a folder it may not write,\n // a full disk) names `where` instead, the folder or the file asked for. Before, the answer and its `details.path`\n // named the hidden file.\n const asked = (error: unknown, where: string): unknown => {\n const failed = error as NodeJS.ErrnoException;\n if (failed instanceof Error && failed.path === partial) {\n failed.path = where;\n failed.message = failed.message.replaceAll(partial, where);\n }\n return error;\n };\n let out: FileHandle | null;\n try { out = await open(partial, \"wx\", 0o600); } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n // The folder it goes in is what is missing (or a file): named alone, as `listen --cursor` names its own. Before,\n // Node's whole path (\"No such file or folder: <folder>/<name>\") read as if the received file were gone.\n if (code === \"ENOENT\" || code === \"ENOTDIR\") {\n const folder = dirname(target), there = await stat(folder).catch(() => undefined);\n if (!there) throw new CliError(\"not_found\", `No such file or folder: ${folder}`);\n if (!there.isDirectory()) throw new CliError(\"not_found\", `${folder} is a file, not a folder`);\n }\n // Not made at all: the folder refused it.\n throw asked(error, dirname(target));\n }\n let written = 0, complete = false;\n try {\n const backend = stored.bytes ? await fileBytesOf(stored.bytes) : null;\n if (backend) {\n const size = await backend.size(fileId);\n if (size === null) throw new CliError(\"not_found\", \"The file's bytes are not on this device\");\n for (let offset = 0; offset < size; offset += FILE_BYTES_STEP) {\n const chunk = await backend.read(fileId, offset, FILE_BYTES_STEP);\n await out.write(chunk);\n written += chunk.length;\n }\n } else if (stored.blob) {\n const chunk = new Uint8Array(await stored.blob.arrayBuffer());\n await out.write(chunk);\n written = chunk.length;\n } else throw new CliError(\"not_found\", \"The file's bytes are not on this device\");\n await out.close();\n out = null;\n // --force over what is there. Else never over a file that appeared meanwhile: a voice message steps on to a free name.\n // It steps on from where the names above left it, never back to \"(2)\".\n while (!complete) try { await place(partial, target, force); complete = true; } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n const refused = code === \"EEXIST\" || code === \"EISDIR\" || code === \"ENOTEMPTY\" ? await taken(target, code) : undefined;\n if (free && refused?.code === \"confirm\" && next <= 1000) { target = `${stem} (${next})${ext}`; next += 1; continue; }\n throw refused ?? error;\n }\n // A contact chose its bytes and its name (`.command`, `.lnk`): marked as downloaded. Every save is, as Desktop's:\n // one sent from here may be a contact's forwarded (`copyForForward`), its record \"out\" with nothing of where it came from.\n await markDownloaded(target);\n } catch (error) {\n throw asked(error, target);\n } finally {\n await out?.close();\n await rm(partial, { force: true });\n }\n return { file: fileId, path: target, size: written, name: stored.metadata.name, mime: stored.metadata.mime };\n },\n};\n","import { MESSAGE_CLOCK_SKEW_MS, STATUS_CARD_LIMITS, cardLine, checkStatusCard, randomBytes, statusCardBytes, toBase64Url, type StatusCard } from \"@ghostly/core\";\nimport type { StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { bool, chatOrGroup, keptForJoin, node, num, oneOf, oneShotWaits, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError, asCliError } from \"./errors\";\nimport { checkTextSize } from \"./textSize\";\nimport { waitForEdit, waitForGroupFrame, waitForMessage } from \"./waits\";\n\n/*\n * Status cards (WISP 405 · Status Cards): a bot's task or routine, sent as a message with a card and kept current by\n * editing it. A routine's run (`run`) becomes its last run and the newest of its recent runs.\n * The engine checks every card by the sender's rule and writes its fallback text; this is the bot's side of it: a card\n * built from flags or JSON, found again by its id, merged with an update, and paced, one update per card every\n * `CARD_UPDATE_GAP_MS`. An update that comes sooner is merged into the next one, which goes when the time is up.\n */\n\n/** A card's updates go at most this often: the rest merge into the next, so a chatty bot spends few edits. */\nexport const CARD_UPDATE_GAP_MS = 2_500;\n\ntype Kind = StatusCard[\"kind\"];\ntype Target = { id: string; linkId: string; group: boolean };\n\n/** Per card (its message): when its last update went, what waits to go next, and how to send it now. */\n/** `text`: the newest waiting update's `--text`, which goes with `next`. */\ninterface Pace { last: number; next?: Record<string, unknown>; text?: string; timer?: ReturnType<typeof setTimeout>; flushed?: Promise<void>; flush?: () => void }\nconst paces = new WeakMap<ApiContext, Map<string, Pace>>();\n\nfunction paceOf(ctx: ApiContext, key: string): Pace {\n let map = paces.get(ctx);\n if (!map) paces.set(ctx, (map = new Map()));\n let pace = map.get(key);\n if (!pace) map.set(key, (pace = { last: 0 }));\n return pace;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** The fields a command gave: an object, or a usage error that says so. */\nfunction fieldsOf(params: Params): Record<string, unknown> {\n const fields = params.card ?? {};\n if (!isObject(fields)) throw new CliError(\"bad_request\", \"card must be an object of the card's fields\");\n return fields;\n}\n\n/**\n * An update merged over a card: fields given replace those there, `pr` field by field, and a field given as null goes\n * (`--json '{\"step\":null}'`). The kind and the id never change. A task says how far it is one way: a percent given\n * replaces the steps there and steps given the percent, unless the update gives both. Before, `--steps 4/5` over an\n * earlier `--progress 90` showed \"90% · 4 of 5 steps\", its bar at 90: a card's own percent wins over its steps.\n */\nexport function mergeCard(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...base };\n if (base.kind === \"task\") {\n const given = (key: string) => patch[key] !== undefined && patch[key] !== null;\n const steps = given(\"done\") || given(\"total\");\n if (given(\"progress\") && !steps) { delete out.done; delete out.total; }\n else if (steps && !given(\"progress\")) delete out.progress;\n }\n for (const [key, value] of Object.entries(patch)) {\n if (key === \"kind\" || key === \"id\") continue;\n if (value === null) { delete out[key]; continue; }\n if (key === \"pr\" && isObject(value) && isObject(base.pr)) {\n const pr: Record<string, unknown> = { ...base.pr };\n for (const [k, v] of Object.entries(value)) { if (v === null) delete pr[k]; else pr[k] = v; }\n out.pr = pr;\n continue;\n }\n out[key] = value;\n }\n return out;\n}\n\n/**\n * A routine's run from the command (`run: {result, summary?}`), as its last run and the first of its recent runs,\n * `STATUS_CARD_LIMITS.runs` kept. Undefined when the command names none.\n */\nexport function withRun(fields: Record<string, unknown>, params: Params, now = Date.now()): Record<string, unknown> {\n const run = params.run;\n if (run === undefined) return fields;\n if (!isObject(run) || typeof run.result !== \"string\") throw new CliError(\"bad_request\", \"run is {result: ok|failed|skipped, summary?}\");\n const lastRun = { at: now, result: run.result, ...(typeof run.summary === \"string\" && run.summary ? { summary: run.summary } : {}) };\n const before = Array.isArray(fields.runs) ? fields.runs : [];\n return { ...fields, lastRun, runs: [lastRun, ...before].slice(0, STATUS_CARD_LIMITS.runs) };\n}\n\n/**\n * A card checked by the sender's rule, or a `bad_request` that says what is wrong: with the card, unless the card is\n * what is too big (its size and the bound, not kilobytes of it echoed back).\n */\nfunction checked(card: Record<string, unknown>): StatusCard {\n const result = checkStatusCard(card);\n if (\"error\" in result) {\n const bytes = statusCardBytes(card);\n throw new CliError(\"bad_request\", `Status card: ${result.error}`, bytes > STATUS_CARD_LIMITS.bytes ? { bytes, max: STATUS_CARD_LIMITS.bytes } : { card });\n }\n return result.card;\n}\n\n/** Every text in a card's fields (title, step, items, runs, links…), as the contact's app may show it. */\nfunction cardTexts(value: unknown, out: string[] = []): string[] {\n if (typeof value === \"string\") out.push(value);\n else if (Array.isArray(value)) for (const item of value) cardTexts(item, out);\n else if (isObject(value)) for (const item of Object.values(value)) cardTexts(item, out);\n return out;\n}\n\n/**\n * The first text in `value` (a card's fields, a message's text…) that looks like a seed, a private key or a Cashu token,\n * read as given and as a card carries it (`cardLine`).\n */\nexport function secretIn(value: unknown): ReturnType<typeof findSecret> {\n for (const text of cardTexts(value)) {\n const secret = findSecret(text) ?? findSecret(cardLine(text, Infinity) ?? \"\");\n if (secret) return secret;\n }\n return null;\n}\n\n/**\n * The secret guard `send` has (docs/CLI.md § Safety): a card whose text looks like a seed, a private key or a Cashu\n * token goes only with `--force`. `fields` are what this command gives (an update's own, not the card it merges over).\n * A card's text is read as given and as the card carries it (`cardLine`): a line loses its invisible characters on the\n * way, so a key one of them broke in two is whole again on the card. The fallback text goes as it is, as `send`'s, and\n * one past 16 KiB is refused first, with its size, `--force` or not (`checkTextSize`).\n */\nfunction guardSecrets(fields: unknown, params: Params, verb: string): void {\n if (typeof params.text === \"string\") checkTextSize(params.text);\n if (bool(params, \"force\")) return;\n const check = (text: string) => {\n const secret = findSecret(text);\n if (secret) throw new CliError(\"confirm\", `The card's text looks like ${secretWords(secret)}; ${verb} it with --force if you mean to`, { kind: secret.kind });\n };\n for (const text of cardTexts([fields, params.run])) { check(text); check(cardLine(text, Infinity) ?? \"\"); }\n if (typeof params.text === \"string\") check(params.text);\n}\n\n/** How many cards a process remembers the message of; one past them is found in the history again. */\nexport const CARDS_REMEMBERED = 1_000;\n\n/** Per card (its chat or group, its kind and its id): the message of mine that carries it, as this process last saw it. */\nconst carriers = new WeakMap<ApiContext, Map<string, string>>();\nconst carrierKey = (linkId: string, kind: string, id: string) => `${linkId}\\n${kind}\\n${id}`;\n\nfunction carriersOf(ctx: ApiContext): Map<string, string> {\n let map = carriers.get(ctx);\n if (map) return map;\n carriers.set(ctx, (map = new Map()));\n const cards = map;\n // A newer card of mine stands for its id from the moment it is stored, whoever sent it (`engine call` too).\n ctx.hub.onEvent((event) => {\n if (event.type !== \"message.sent\" && event.type !== \"group.sent\") return;\n const message = event.message as { id?: unknown; card?: { kind?: unknown; id?: unknown } } | undefined;\n const card = message?.card;\n if (typeof message?.id !== \"string\" || typeof card?.id !== \"string\" || (card.kind !== \"task\" && card.kind !== \"routine\" && card.kind !== \"usage\")) return;\n carried(cards, carrierKey(event.type === \"group.sent\" ? `group:${String(event.group)}` : String(event.chat), card.kind, card.id), message.id);\n });\n return map;\n}\n\nfunction carried(cards: Map<string, string>, key: string, messageId: string): void {\n cards.delete(key);\n cards.set(key, messageId);\n if (cards.size > CARDS_REMEMBERED) cards.delete(cards.keys().next().value!);\n}\n\n/**\n * The latest message of mine in this chat or group with a card of this kind and id: the one an update edits. A card\n * this process sent or found before is read by its message's key, so its updates cost the same in a long chat as in a\n * short one; only a card not seen yet (the first update after a start, a one-shot) is looked for in the whole history.\n */\nasync function cardMessage(ctx: ApiContext, target: Target, kind: Kind, id: string): Promise<StoredMessage> {\n const cards = carriersOf(ctx), key = carrierKey(target.linkId, kind, id);\n const carries = (message: StoredMessage | undefined): message is StoredMessage => message?.sender === \"me\" && message.card?.kind === kind && message.card.id === id;\n const known = cards.get(key);\n if (known !== undefined) {\n const message = await node(ctx).getMessage(target.linkId, known);\n if (carries(message)) return message;\n // Deleted since, or it carries another card now: the history says which message stands for the id.\n cards.delete(key);\n }\n const messages = target.group ? await node(ctx).groupMessages({ groupId: target.id }) : await node(ctx).getMessages(target.linkId);\n // A card stored while the history was read is newer than what was read: that one stands for the id.\n if (cards.has(key)) return cardMessage(ctx, target, kind, id);\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n if (!carries(message)) continue;\n carried(cards, key, message.id);\n return message;\n }\n throw new CliError(\"not_found\", `No ${kind} ${JSON.stringify(id)} of yours in this ${target.group ? \"group\" : \"chat\"}: send it first with ghostly ${kind} send`);\n}\n\nfunction answer(target: Target, kind: Kind, id: string, messageId: string, extra: Record<string, unknown>): Record<string, unknown> {\n return { [target.group ? \"group\" : \"chat\"]: target.id, [kind]: id, messageId, ...extra };\n}\n\n/**\n * A task's parent is another task of mine in the same chat or group (WISP 405 · Status Cards § A task): one that is\n * not there is refused here, with its name, rather than sent to stand alone on every board (a reader keeps the field\n * and shows the task ungrouped). Send the parent first.\n */\nasync function parentThere(ctx: ApiContext, target: Target, card: StatusCard): Promise<void> {\n if (card.kind !== \"task\" || !card.parent) return;\n const parent = card.parent;\n await cardMessage(ctx, target, \"task\", parent).catch(() => {\n throw new CliError(\"not_found\", `--parent: no task ${JSON.stringify(parent)} of yours in this ${target.group ? \"group\" : \"chat\"}: send the parent first`);\n });\n}\n\n/** A new card: a message whose text is written from it, in a chat or a group. */\nasync function sendCard(ctx: ApiContext, params: Params, kind: Kind): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const fields = fieldsOf(params);\n guardSecrets(fields, params, \"send\");\n const now = Date.now();\n const id = typeof fields.id === \"string\" && fields.id ? fields.id : `${kind}-${toBase64Url(randomBytes(6))}`;\n const card = checked(withRun({\n ...(kind === \"task\" ? { status: \"running\", startedAt: now, updatedAt: now } : kind === \"routine\" ? { state: \"active\" } : {}),\n ...fields, kind, id,\n }, params, now));\n await parentThere(ctx, target, card);\n const text = str(params, \"text\") ?? \"\";\n // A one-shot leaves once its command is done, and the card with it: in a chat it stays until it went out, as `send`.\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, oneShotWaits(ctx, target.linkId) ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n if (target.group) {\n const result = await node(ctx).sendGroupMessage({ groupId: target.id, text, card });\n if (result.error || !result.messageId) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error ?? \"Nothing to send\");\n carried(carriersOf(ctx), carrierKey(target.linkId, kind, id), result.messageId);\n const edges = wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, result.messageId, undefined, ms) : undefined;\n return answer(target, kind, id, result.messageId, { card, ...(edges !== undefined && { edges }) });\n }\n const result = await node(ctx).sendMessage({ linkId: target.linkId, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n if (!result.messageId) throw new CliError(\"bad_request\", \"Nothing to send\");\n carried(carriersOf(ctx), carrierKey(target.linkId, kind, id), result.messageId);\n let message = await node(ctx).getMessage(target.linkId, result.messageId);\n if (wait !== \"none\") message = await waitForMessage(ctx, target.linkId, result.messageId, wait, ms);\n return answer(target, kind, id, result.messageId, { card, delivery: message?.delivery ?? null, ...keptForJoin(ctx, target.linkId, \"the card\") });\n}\n\n/**\n * A card's own kept times (a task's start, a routine's runs) later than the sender's rule takes: the device's clock\n * went back since they were set. Said as that, not as a time the person gave in the future; fields the update gives\n * are checked as given.\n */\nfunction clockWentBack(base: Record<string, unknown>, patch: Record<string, unknown>, kind: Kind): void {\n const latest = Date.now() + MESSAGE_CLOCK_SKEW_MS;\n const ahead = (value: unknown) => typeof value === \"number\" && value > latest;\n const at = (run: unknown) => isObject(run) && ahead(run.at);\n const field = kind === \"task\" ? (patch.startedAt === undefined && ahead(base.startedAt) ? \"startedAt\" : undefined)\n : kind === \"routine\" ? (patch.lastRun === undefined && at(base.lastRun) ? \"lastRun.at\"\n : patch.runs === undefined && Array.isArray(base.runs) && base.runs.some(at) ? \"runs[].at\" : undefined)\n : undefined;\n if (field) throw new CliError(\"bad_request\", `This device's clock went back since the ${kind} was sent: its ${field} is later than now. Update it once the clock is right, or start a new card with ghostly ${kind} send`, { field, now: Date.now() });\n}\n\n/** Edits the card's message with its merged card, now. */\nasync function editCard(ctx: ApiContext, target: Target, messageId: string, card: StatusCard, text: string): Promise<void> {\n const result = await node(ctx).editMessage({ linkId: target.linkId, messageId, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n}\n\n/**\n * An update of a card of mine: the fields given, merged over its latest state (what waits to go included). It goes at\n * once when the card's last update is `CARD_UPDATE_GAP_MS` old; otherwise it waits for that, merged with any update\n * that comes meanwhile (`queued: true`). A one-shot command waits the time out itself: it has no daemon to wait in.\n */\nasync function updateCard(ctx: ApiContext, params: Params, kind: Kind): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const id = str(params, kind, true);\n const patch = fieldsOf(params);\n guardSecrets(patch, params, \"update\");\n const message = await cardMessage(ctx, target, kind, id);\n // A card message takes `STATUS_CARD_LIMITS.edits` updates (WISP 405 · Status Cards); past them, a new card goes on.\n if ((message.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits)\n throw new CliError(\"refused\", `This ${kind}'s message took ${STATUS_CARD_LIMITS.edits} updates, the most one takes: start a new card with ghostly ${kind} send (a new --id, or the same one: the newest card of an id stands for it)`, { messageId: message.id, edits: message.edit!.seq });\n const pace = paceOf(ctx, `${target.linkId}\\n${message.id}`);\n const base = pace.next ?? (message.card as unknown as Record<string, unknown>);\n clockWentBack(base, patch, kind);\n // A clock set back a little leaves the card's start ahead of now: its update is never before it.\n const startedAt = typeof base.startedAt === \"number\" && patch.startedAt === undefined ? base.startedAt : 0;\n const merged = withRun(mergeCard(base, { ...patch, ...(kind === \"task\" && { updatedAt: Math.max(Date.now(), startedAt) }) }), params);\n const card = checked(merged);\n if (isObject(patch) && patch.parent !== undefined) await parentThere(ctx, target, card);\n const text = str(params, \"text\") ?? \"\";\n // In a chat a one-shot stays until the contact confirmed the update, as `edit`: the process leaving took it along.\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"confirmed\"] as const, oneShotWaits(ctx, target.linkId) ? \"confirmed\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const last = Math.max(pace.last, message.edit?.at ?? message.timestamp);\n // Never more than the gap: a last update ahead of now is the clock gone back, not one to wait the jump out for.\n const due = Math.min(last + CARD_UPDATE_GAP_MS - Date.now(), CARD_UPDATE_GAP_MS);\n let queued = false;\n if (due > 0 && ctx.mode === \"daemon\") {\n // Merged into what goes next; the first update in the gap sets the timer, the later ones only change what it sends.\n pace.next = card as unknown as Record<string, unknown>;\n // Its text too: the first update's went with the merged card, a \"done\" card under \"Working: 10%\".\n pace.text = text;\n queued = true;\n if (!pace.timer) pace.flushed = new Promise<void>((resolve) => {\n const send = () => {\n const next = pace.next, nextText = pace.text ?? \"\";\n clearTimeout(pace.timer);\n pace.timer = undefined; pace.next = undefined; pace.text = undefined; pace.flush = undefined; pace.last = Date.now();\n void (next ? editCard(ctx, target, message.id, next as unknown as StatusCard, nextText) : Promise.resolve()).catch(() => {}).finally(resolve);\n };\n pace.flush = send;\n pace.timer = setTimeout(send, due);\n });\n if (wait !== \"none\") await pace.flushed;\n } else {\n if (due > 0) await new Promise((resolve) => setTimeout(resolve, due));\n pace.last = Date.now();\n await editCard(ctx, target, message.id, card, text);\n }\n let edited = await node(ctx).getMessage(target.linkId, message.id);\n if (wait === \"confirmed\" && edited?.edit?.pending) edited = await waitForEdit(ctx, target.linkId, message.id, ms);\n const edges = wait === \"sent\" && edited?.edit ? await waitForGroupFrame(ctx, target.id, message.id, edited.edit.seq, ms) : undefined;\n return answer(target, kind, id, message.id, {\n card, queued, edits: edited?.edit?.seq ?? 0,\n // An update still waiting for its time went nowhere yet: it is not confirmed, whatever the message's last edit says.\n ...(target.group ? { ...(edges !== undefined && { edges }) } : { confirmed: (!queued || wait !== \"none\") && !!edited && !edited.edit?.pending, ...keptForJoin(ctx, target.linkId, \"the update\") }),\n });\n}\n\n/**\n * Sends now every update still waiting for its time: the daemon is stopping, and the update it answered `queued` for\n * (often a task's last one, done or failed) would otherwise go with it, leaving the card running for good. Called\n * while the engine can still store the edit; it goes to the contact as any edit does, now or once they are back.\n */\nexport async function flushCardUpdates(ctx: ApiContext): Promise<void> {\n const waiting = [...(paces.get(ctx)?.values() ?? [])].filter((pace) => pace.flush);\n for (const pace of waiting) pace.flush!();\n await Promise.all(waiting.map((pace) => pace.flushed));\n}\n\n/** A usage card's fields: all of them are said again by each report, so one not given goes from the card. */\nconst USAGE_FIELDS = [\"left\", \"used\", \"limit\", \"label\", \"account\", \"window\", \"resetsAt\", \"updatedAt\", \"windows\"] as const;\n\n/** The id a bot's usage card goes by when it names none: one live card per chat. */\nexport const USAGE_CARD_ID = \"usage\";\n\n/**\n * One chat's usage report (WISP 405 § Usage): the bot's usage card there, kept as one message. The first report sends\n * it; every later one edits it in place (quiet: no sound, no unread, no move in the list), paced as a task's updates.\n * A report is whole: what it does not say goes from the card. A card at its edits' cap gives way to a new message.\n */\nasync function reportUsage(ctx: ApiContext, ref: string, fields: Record<string, unknown>, params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, ref);\n const id = typeof fields.id === \"string\" && fields.id ? fields.id : USAGE_CARD_ID;\n const report = { updatedAt: Date.now(), ...fields, kind: \"usage\", id };\n checked(report);\n const sent = await cardMessage(ctx, target, \"usage\", id).catch(() => undefined);\n // A one-shot's report in a chat stays until it went out (a new card) or the contact confirmed it (an update).\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\"] as const, !target.group && oneShotWaits(ctx, target.linkId) ? \"sent\" : \"none\");\n if (!sent || (sent.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits) {\n const answer = await sendCard(ctx, { ...params, chat: ref, card: report, wait }, \"usage\");\n return { ...answer, updated: false };\n }\n const patch: Record<string, unknown> = {};\n for (const key of USAGE_FIELDS) patch[key] = report[key as keyof typeof report] ?? null;\n const answer = await updateCard(ctx, { ...params, chat: ref, usage: id, card: patch, wait: wait === \"none\" ? \"none\" : target.group ? \"sent\" : \"confirmed\" }, \"usage\");\n return { ...answer, updated: true };\n}\n\n/**\n * `usage send`: one chat or group, or (`all`) every 1:1 chat with a contact; a chat that refuses is said (its\n * `{code, message}`), not fatal, unless every chat refused: then nothing was reported and the call fails.\n */\nasync function sendUsage(ctx: ApiContext, params: Params): Promise<Record<string, unknown>> {\n const fields = fieldsOf(params);\n if (!bool(params, \"all\")) return reportUsage(ctx, str(params, \"chat\", true), fields, params);\n if (str(params, \"chat\")) throw new CliError(\"bad_request\", \"Name a chat or --all, not both\");\n checked({ updatedAt: Date.now(), ...fields, kind: \"usage\", id: typeof fields.id === \"string\" && fields.id ? fields.id : USAGE_CARD_ID });\n if (typeof params.text === \"string\") checkTextSize(params.text);\n // The person's mistake, said once: before, each chat refused it on its own and the call still answered.\n oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\");\n num(params, \"timeout\", 30, { min: 1, max: 3600 });\n const chats = state(ctx).links.filter((link) => link.profile && link.peerPubKeyZ32);\n const results: Record<string, unknown>[] = [];\n const failed: { chat: string; error: CliError }[] = [];\n for (const link of chats) {\n try { results.push(await reportUsage(ctx, link.id, fields, params)); }\n catch (error) {\n const refusal = { chat: link.id, error: asCliError(error) };\n failed.push(refusal);\n results.push({ chat: link.id, error: refusal.error.toJSON() });\n }\n }\n if (failed.length && failed.length === chats.length) {\n const codes = new Set(failed.map((f) => f.error.code));\n throw new CliError(codes.size === 1 ? failed[0]!.error.code : \"refused\", `No chat took the usage card: ${failed.map((f) => `${f.chat}: ${f.error.message}`).join(\"; \")}`, { chats: results });\n }\n return { chats: results };\n}\n\nexport const STATUS_CARD_METHODS: Record<string, Method> = {\n /** WISP 405 · Status Cards: a task card in a chat or a group; the answer names the task's id and its message. */\n \"task.send\": (ctx, params) => sendCard(ctx, params, \"task\"),\n /** A task's update: the fields given, merged over its latest state, paced one per `CARD_UPDATE_GAP_MS`. */\n \"task.update\": (ctx, params) => updateCard(ctx, params, \"task\"),\n /** A routine card (its schedule, state, runs); `run` records one. */\n \"routine.send\": (ctx, params) => sendCard(ctx, params, \"routine\"),\n /** A routine's update, as a task's; `run` records a run as its last and the newest of its recent ones. */\n \"routine.update\": (ctx, params) => updateCard(ctx, params, \"routine\"),\n /** WISP 405 § Usage: how much of a quota the bot has left, kept as one card per chat; `all` for every 1:1 chat. */\n \"usage.send\": sendUsage,\n};\n","import { readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { LinkView } from \"@ghostly/browser/shared/types\";\nimport { node, state, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\n\n/**\n * `chat disconnect --hold <minutes>`: a chat kept off its direct link for a while. It is the chat's own \"DHT only\"\n * choice (WISP 400: either side choosing it keeps both off the live link, so the contact's app does not redial),\n * taken back when the time is up. Text still goes over the DHT (short texts), files wait. The holds are kept in\n * the profile folder: a daemon that restarts takes back the ones whose time is up, and never a DHT only the chat had\n * chosen before (that one is not a hold).\n */\nexport const HOLD_MAX_MINUTES = 7 * 24 * 60;\n\ninterface Hold { until: number; since: number }\ntype Holds = Record<string, Hold>;\n\n/** Per chat held: what stops its wait (the timer, or the wait for the chat to open: `expire`). */\nconst timers = new WeakMap<ApiContext, Map<string, () => void>>();\n\nfunction holdsFile(ctx: ApiContext): string {\n return join(ctx.runtime.paths.dir, \"holds.json\");\n}\n\nfunction readHolds(ctx: ApiContext): Holds {\n try { return JSON.parse(readFileSync(holdsFile(ctx), \"utf8\")) as Holds; } catch { return {}; }\n}\n\nfunction writeHolds(ctx: ApiContext, holds: Holds): void {\n const file = holdsFile(ctx);\n writeFileSync(file + \".tmp\", JSON.stringify(holds) + \"\\n\", { mode: 0o600 });\n renameSync(file + \".tmp\", file);\n}\n\n/**\n * Changes one chat's entry: the file is read again right here and written back in the same step, with no wait in\n * between, so what another chat's hold, expiry or release wrote meanwhile stays. Each call read the file before its\n * engine call and wrote that copy back after it: two holds at once on a daemon (which serves its connections at once)\n * kept only one, and the other chat stayed on DHT only for good; an expiry meanwhile brought an ended hold back.\n * Only one process writes the file: a command goes through the profile's daemon when one runs, and otherwise holds\n * the profile itself.\n */\nfunction editHold(ctx: ApiContext, linkId: string, hold: Hold | null): void {\n const holds = readHolds(ctx);\n if (hold) holds[linkId] = hold;\n else if (holds[linkId]) delete holds[linkId];\n else return;\n writeHolds(ctx, holds);\n}\n\n/** Per profile folder and chat, the last change to its hold under way: changes to one chat's hold go one after another. */\nconst queues = new Map<string, Promise<unknown>>();\n\n/**\n * Runs `task` once the changes to this chat's hold started before it are done (failed or not). A hold and an expiry,\n * a release or a removal of the same chat no longer run into each other; other chats' run meanwhile.\n */\nfunction inTurn<T>(ctx: ApiContext, linkId: string, task: () => Promise<T>): Promise<T> {\n const key = `${ctx.runtime.paths.dir}\\0${linkId}`;\n const run = (queues.get(key) ?? Promise.resolve()).then(task, task);\n const settled = run.then(() => {}, () => {});\n queues.set(key, settled);\n void settled.then(() => { if (queues.get(key) === settled) queues.delete(key); });\n return run;\n}\n\nfunction timersOf(ctx: ApiContext): Map<string, () => void> {\n let map = timers.get(ctx);\n if (!map) timers.set(ctx, (map = new Map()));\n return map;\n}\n\nfunction stopWait(ctx: ApiContext, linkId: string): void {\n timersOf(ctx).get(linkId)?.();\n timersOf(ctx).delete(linkId);\n}\n\n/**\n * The longest a hold's timer waits before it reads the wall clock again. Timers run on a clock that stops while the\n * machine sleeps: one timer for the whole hold, after a sleep past its end, kept the chat on DHT only for as long again\n * as the hold had left when the machine went to sleep, while `holdOf` no longer reported it.\n */\nconst HOLD_CHECK_MS = 60_000;\n\nfunction schedule(ctx: ApiContext, linkId: string, until: number): void {\n stopWait(ctx, linkId);\n const timer = setTimeout(() => {\n timersOf(ctx).delete(linkId);\n if (until > Date.now()) schedule(ctx, linkId, until);\n else expire(ctx, linkId);\n }, Math.min(HOLD_CHECK_MS, Math.max(0, until - Date.now())));\n // A one-shot leaves when its command is done; the next start takes the hold back.\n timer.unref?.();\n timersOf(ctx).set(linkId, () => clearTimeout(timer));\n}\n\n/**\n * Whether the chat leaves DHT only in this run: the engine switches only a chat it opened (`runnableTransports` is\n * there once it did). A one-shot that only reads opens none, and one about another chat not this one.\n */\nconst switchable = (link: LinkView | undefined): boolean => !link || link.deliveryMode !== \"dht\" || !!link.runnableTransports;\n\n/**\n * A hold whose time is up ends. On a chat this run has not opened it ends once the chat opens, or at the next start\n * that opens it; it is no longer reported meanwhile (`holdOf`). Each read said on stderr that it \"could not end:\n * Delivery method unavailable.\" and kept its past `heldUntil`.\n */\nfunction expire(ctx: ApiContext, linkId: string): void {\n const opened = (links: readonly LinkView[]) => switchable(links.find((l) => l.id === linkId));\n if (!opened(state(ctx).links)) {\n const off = ctx.hub.onState((s) => { if (opened(s.links)) { stopWait(ctx, linkId); expire(ctx, linkId); } });\n timersOf(ctx).set(linkId, off);\n return;\n }\n void releaseHold(ctx, linkId, \"expired\").catch((error: unknown) => process.stderr.write(`ghostly: the hold on ${linkId} could not end: ${error instanceof Error ? error.message : String(error)}\\n`));\n}\n\n/** When the chat's hold ends, or null (its time is up, also while it waits for the chat to open: `expire`). */\nexport function holdOf(ctx: ApiContext, linkId: string): number | null {\n const until = readHolds(ctx)[linkId]?.until;\n return until !== undefined && until > Date.now() ? until : null;\n}\n\n/**\n * When the chat's hold ends, or null for none, as what waits in a held chat reads it: also a hold whose time is up and\n * that has not ended yet (its release is under way, or waits for the chat to open: `expire`), which `holdOf` no longer\n * reports while the chat is still on DHT only. Read as no hold, a text or edit waiting through it was said to wait\n * for a transport to be chosen, and it goes by itself.\n */\nexport function holdEnds(ctx: ApiContext, linkId: string): number | null {\n return readHolds(ctx)[linkId]?.until ?? null;\n}\n\n/** Keeps the chat off its direct link for `minutes` (again: from now). */\nexport function holdChat(ctx: ApiContext, link: LinkView, minutes: number): Promise<number> {\n return inTurn(ctx, link.id, async () => {\n // As the chat is now: a change to its hold that ran first may have moved it.\n const now = state(ctx).links.find((l) => l.id === link.id) ?? link;\n const held = readHolds(ctx)[link.id];\n if (now.deliveryMode === \"dht\" && !held) throw new CliError(\"refused\", \"This chat is on DHT only already, by its own choice: chat transport auto leaves it\");\n if (!now.profile) throw new CliError(\"unavailable\", \"A chat of the older protocol has no DHT only\");\n const until = Date.now() + minutes * 60_000;\n // The hold before DHT only, taken back if the switch fails: the store never has the chat on DHT only while\n // holds.json has no hold to end it (a profile backup reads that file again after the store).\n editHold(ctx, link.id, { until, since: held?.since ?? Date.now() });\n if (now.deliveryMode !== \"dht\") {\n try { await node(ctx).setChatTransport({ linkId: link.id, transport: \"dht\" }); } catch (error) {\n editHold(ctx, link.id, held ?? null);\n throw new CliError(\"unavailable\", error instanceof Error ? error.message : String(error));\n }\n }\n schedule(ctx, link.id, until);\n ctx.hub.emit(\"chat.held\", `chat.held:${link.id}:${until}`, { chat: link.id, until });\n return until;\n });\n}\n\n/**\n * Ends a hold: the chat leaves DHT only, unless someone chose otherwise meanwhile. Whether there was one. `reason`:\n * expired, connect (`chat connect`) or lifted (`--hold 0`, or `chat transport`: `chosen`, the chat's transport was\n * just chosen, and stays as chosen).\n */\nexport function releaseHold(ctx: ApiContext, linkId: string, reason: \"expired\" | \"connect\" | \"lifted\", chosen = false): Promise<boolean> {\n return inTurn(ctx, linkId, async () => {\n if (!readHolds(ctx)[linkId]) return false;\n stopWait(ctx, linkId);\n const link = state(ctx).links.find((l) => l.id === linkId);\n if (!chosen && link?.deliveryMode === \"dht\") await node(ctx).setDeliveryMode({ linkId, mode: \"stream\" });\n editHold(ctx, linkId, null);\n ctx.hub.emit(\"chat.released\", `chat.released:${linkId}:${Date.now()}`, { chat: linkId, reason });\n return true;\n });\n}\n\n/**\n * A removed chat's hold goes with it, with no release said: it stayed in the folder until its time was up (and in a\n * backup made meanwhile), a chat joined again from the same invite showed its `heldUntil`, and its end said\n * `chat.released` for a chat that was gone.\n */\nexport function forgetHold(ctx: ApiContext, linkId: string): Promise<void> {\n return inTurn(ctx, linkId, async () => {\n stopWait(ctx, linkId);\n editHold(ctx, linkId, null);\n });\n}\n\n/**\n * At start: holds whose time is up end now, the others are timed again. A hold whose chat the store does not have is\n * dropped, with no release said: a profile restored from a backup taken while that chat was removed (the backup reads\n * holds.json before and after its store) had it, and its end said `chat.released` for a chat it never had.\n */\nexport function resumeHolds(ctx: ApiContext): void {\n const chats = new Set(state(ctx).links.map((link) => link.id));\n const holds = readHolds(ctx), gone = Object.keys(holds).filter((linkId) => !chats.has(linkId));\n for (const linkId of gone) delete holds[linkId];\n if (gone.length) writeHolds(ctx, holds);\n for (const [linkId, hold] of Object.entries(holds)) schedule(ctx, linkId, hold.until);\n}\n","import { groupMemberOfLink, groupPayLineId, groupPayTwin } from \"@ghostly/browser/shared/groupPayNotes\";\nimport type { GroupPayNote, GroupView, LinkView, MessageFile, PaymentView, PinView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport type { StatusCard } from \"@ghostly/core\";\n\n/**\n * The JSON shapes the CLI and the daemon answer with. They are the contract bots code against (WISP 1100), kept\n * apart from the engine's views: those change with the app, these only by adding fields.\n */\n\nexport interface ChatJson {\n id: string;\n /** The label set here, else the name the contact gave, else null. */\n name: string | null;\n label: string | null;\n peerName: string | null;\n /** The contact's key for this chat (z-base-32). */\n peer: string;\n createdAt: number;\n /** When its latest message came, or null before the first (the engine keeps 0). */\n lastMessageAt: number | null;\n /** A live session carries the chat now, in this run (text, files, payments go at once). */\n live: boolean;\n /** The transport of the live session, or null. */\n transport: string | null;\n /** How text goes now: `stream` (live), `dht` (the DHT floor, 256 bytes), `hold`, or `unavailable`. */\n text: string;\n /** The pairing's state: connecting, negotiating, confirm, waiting, ready, or error (`connectionError` says why). */\n pairing: string | null;\n /**\n * Why the chat cannot connect, or its texts cannot go, as the app's connection panel says it: the pairing's failure,\n * or on a chat whose text goes by the DHT the DHT delivery's (its relays refusing the publish). Null when none.\n */\n connectionError: string | null;\n /** How far the first pairing got (publishing, waiting, resolving, on-dht, live, …), while it is under way. */\n stage: string | null;\n verified: boolean;\n /**\n * The invite this side made for the chat, while it waits for the contact: `<hidden>` unless asked for\n * (`--show-secret`), since whoever reads the code can take the chat. Null once the chat is paired, or without one.\n */\n invite: string | null;\n /** A chat of the older protocol (WISP 402). */\n compatibility: boolean;\n /** The contact sent a picture (checked by the engine; `engine getState` has it). */\n peerPicture: boolean;\n}\n\n/**\n * A live session carries the chat now, in this run: its link is open and, on a paired chat, the session authenticated\n * on a transport. The engine's own rule for a chat's connection line (`observeTransport`). `textDelivery` alone says\n * how a text would go, and nothing the engine remembers from an earlier run (a chat that was live when the app last\n * ran, WISP 100) counts: until the contact answers again the link is not open and the pairing is `connecting`.\n */\nexport function isLive(link: LinkView): boolean {\n if (link.textDelivery !== \"stream\" || link.dataLink !== \"open\") return false;\n return !link.profile || (link.pairing?.status === \"ready\" && !!link.pairing.transport);\n}\n\n/**\n * The app's connection failure (ChatConnection's `connectionFailure`), with the relays' words made plain: the engine's\n * \"Publish failed on every relay: Error: http://… responded 503\" reads as the CLI failing, a class name per relay.\n */\nfunction connectionError(link: LinkView): string | null {\n const pair = link.pairing;\n const dht = link.deliveryMode === \"dht\" || link.textDelivery === \"dht\";\n const detail = pair?.transitionError || (pair?.status === \"error\" ? pair.error : \"\") || (dht ? link.dhtDelivery?.error : \"\");\n if (!detail) return null;\n const at = detail.indexOf(\"Publish failed on every relay:\");\n if (at < 0) return detail;\n const tail = detail.slice(at);\n const hosts = [...new Set([...tail.matchAll(/\\bhttps?:\\/\\/[^\\s;,]+/g)].map(([url]) => URL.canParse(url) ? new URL(url).host : url))];\n // A relay that answered with an error status took the request: \"did not answer\" would not be true of it.\n const said = / responded \\d{3}\\b/.test(tail) ? `${at ? \"n\" : \"N\"}o relay took it` : `${at ? \"n\" : \"N\"}o relay answered`;\n return `${detail.slice(0, at)}${said}${hosts.length ? ` (${hosts.join(\", \")})` : \"\"}`;\n}\n\nexport function chatJson(link: LinkView, showSecret?: boolean): ChatJson {\n const label = link.label?.trim() || null;\n const peerName = link.peerNick?.trim() || null;\n const live = isLive(link);\n return {\n id: link.id,\n name: label ?? peerName,\n label,\n peerName,\n peer: link.peerPubKeyZ32,\n createdAt: link.createdAt,\n lastMessageAt: link.lastMessageAt || null,\n live,\n transport: live ? (link.pairing?.transport ?? link.pairingProgress?.transport ?? null) : null,\n text: link.textDelivery ?? (link.profile ? \"unavailable\" : \"dht\"),\n pairing: link.pairing?.status ?? null,\n connectionError: connectionError(link),\n stage: link.pairingProgress?.stage ?? null,\n verified: !!link.peerVerified,\n invite: link.pairing?.status === \"ready\" || !link.inviteCode ? null : showSecret === true ? link.inviteCode : \"<hidden>\",\n compatibility: !link.profile,\n peerPicture: !!link.peerAvatar,\n };\n}\n\n/**\n * What is pinned at the top of a chat or a group (WISP 400 § Pinned message), as `chat.pinned` / `group.pinned` say it:\n * `messageId` the row here (null when it is not here), `ref` the id both sides know it by, `by` (`me`, `peer` or a\n * member key) and `at`, when it came here. Null when nothing is pinned, or it was unpinned.\n */\nexport function pinJson(pin: PinView | undefined) {\n return pin?.id ? { messageId: pin.messageId ?? null, ref: pin.id, by: pin.by, at: pin.at } : null;\n}\n\n/** A chat's details: the summary plus what its connection panel shows, and its pin. */\nexport function chatDetailsJson(link: LinkView, showSecret?: boolean) {\n return {\n ...chatJson(link, showSecret),\n progress: link.pairingProgress ?? null,\n transports: { mine: link.availableTransports ?? [], peer: link.peerTransports ?? [], preferred: link.preferredTransport ?? null, fallback: link.transportFallback ?? null, automatic: link.transportAutomatic ?? null, relayed: link.relayedTransports ?? [] },\n wait: link.transportWait ?? null,\n lastAttempt: link.liveAttempt ?? null,\n liveSince: link.transportLive?.since ?? null,\n rttMs: link.transportRttMs ?? null,\n relays: link.transportRelayed?.relays ?? null,\n deliveryMode: link.deliveryMode ?? null,\n // The contact's own choice, from its last envelope: `dht` keeps the chat off any live session until it chooses again.\n peerDeliveryMode: link.dhtDelivery?.peerMode ?? null,\n capabilities: link.capabilities ?? null,\n hold: link.hold ?? null,\n peerOnline: link.peerOnline,\n peerLastSeenAt: link.peerLastSeenAt || null,\n history: link.transportHistory ?? null,\n errors: link.transportErrors ?? null,\n comparisonCode: link.pairing?.code ?? null,\n pin: pinJson(link.pin),\n };\n}\n\nexport interface MessageJson {\n id: string;\n chat: string;\n /** `system`: a line of the group's own (`event`: created, joined, renamed…), whoever's key is on it; nobody wrote it. */\n from: \"me\" | \"peer\" | \"system\";\n text: string;\n /** Its place in the history, which is ordered by it: when I sent it, or when it came here (never the sender's clock). */\n timestamp: number;\n /** Received: when its sender says it was sent, by its own clock. */\n sentAt?: number;\n delivery: string | null;\n deliveryError: string | null;\n via: string;\n nick: string | null;\n member?: string;\n mentions?: { key: string; offset: number; length: number }[];\n mentioned?: boolean;\n /** A file or voice message: its id is what `file wait`, `file save` and the `file.*` events name. */\n file?: { id: string; name: string; size: number; mime: string; voice?: { duration: number; peaks?: number[] }; image?: { width: number; height: number } };\n paymentId?: string;\n event?: unknown;\n /**\n * The message this one answers (WISP 400 § Replies). `id`: the original's message id here when it is in this chat\n * (`found`), else the id the reply named. `from`: null when nothing says (only the id came, over the DHT).\n */\n replyTo?: { id: string; snippet: string; from: \"me\" | \"peer\" | null; member?: string; found: boolean; deleted?: true; button?: string };\n /** Reactions to it, one per person (WISP 400 § Reactions): `by` is `me`, `peer` or a member's key. */\n reactions?: { by: string; emoji: string; at: number }[];\n /** An edited text (WISP 400 § Edits): `text` is the latest version, `edits` its number, `editedAt` when it was made. */\n edits?: number;\n editedAt?: number;\n /** Mine: the contact has not confirmed the latest edit yet. */\n editPending?: boolean;\n /** A forwarded message (WISP 400 § Forwards): how many times it has been forwarded. Never who wrote it first. */\n forwarded?: number;\n /** A bot's task or routine (WISP 405 · Status Cards), as its version says it; `text` is its fallback. Or its buttons. */\n card?: StatusCard;\n /**\n * A reply that pressed a button of a message of mine (WISP 406 · Message Buttons), as this side's engine took it:\n * `messageId` the question here, `button` its id, `label`, `inferred` when only the text named it.\n */\n press?: { messageId: string; button: string; label: string; inferred?: true };\n /** A group's payment note (`gpay:<id>`, WISP 902 § Payments): who pays whom, how much, over what, and how it stands now. */\n groupPay?: GroupPayJson;\n /**\n * A payment of this profile in a group (`paymentId`) that a payment note of the group is about: the id of that\n * note's line. The same payment, said twice; the app draws only this one, with the note under it.\n */\n twinOf?: string;\n}\n\n/**\n * A group payment note as `group history` says it. `from` is the payer's member key, or `*` for a request any member\n * may pay once; `to` the payee's. `amount` in the unit's smallest denomination (`decimals` of them make one), as a\n * string. `state`: `open`, `sent` (a payer says it paid, the payee has not confirmed), `paid`, or `closed` (failed,\n * refused or taken back). `by`: who paid it, null when nobody can tell; `claims`: the members who said they paid it.\n */\nexport interface GroupPayJson {\n id: string;\n kind: GroupPayNote[\"kind\"];\n from: string;\n to: string;\n by: string | null;\n claims: string[];\n amount: string;\n decimals: number;\n unit: string;\n rail: GroupPayNote[\"rail\"];\n state: GroupPayNote[\"state\"];\n test: boolean;\n}\n\nexport function groupPayJson(note: GroupPayNote): GroupPayJson {\n // A request to the group paid through an invoice names nobody: its payee cannot tell who paid, and the app says\n // no name (a note an older app kept may still carry one).\n const by = note.from === \"*\" && note.rail === \"lightning\" ? null : note.by ?? null;\n return { id: note.id, kind: note.kind, from: note.from, to: note.to, by, claims: [...(note.claims ?? [])], amount: note.amount,\n decimals: note.decimals, unit: note.unit, rail: note.rail, state: note.state, test: !!note.test };\n}\n\nexport function messageJson(message: StoredMessage): MessageJson {\n return {\n id: message.id,\n chat: message.linkId,\n // The engine keeps a group's own lines as the peer's, mine with my key: a bot reading others' words by `from` took them for a member's.\n from: message.event ? \"system\" : message.sender,\n text: message.text,\n timestamp: message.timestamp,\n ...(message.sentAt !== undefined ? { sentAt: message.sentAt } : {}),\n // A received message is delivered by definition; one of mine without a state went before states existed.\n delivery: message.delivery ?? (message.sender === \"peer\" ? null : \"sent\"),\n deliveryError: message.deliveryError ?? null,\n via: message.via,\n nick: message.nick ?? null,\n ...(message.member ? { member: message.member } : {}),\n ...(message.mentions?.length ? { mentions: message.mentions.map((m) => ({ key: m.k, offset: m.o, length: m.l })) } : {}),\n ...(message.mentioned ? { mentioned: true } : {}),\n ...(message.file ? { file: fileJson(message.file) } : {}),\n ...(message.paymentId ? { paymentId: message.paymentId } : {}),\n ...(message.event ? { event: message.event } : {}),\n ...(message.replyTo ? { replyTo: { id: message.replyTo.messageId ?? message.replyTo.id, snippet: message.replyTo.snippet, from: message.replyTo.from ?? null,\n ...(message.replyTo.member ? { member: message.replyTo.member } : {}), found: !!message.replyTo.messageId,\n ...(message.replyTo.button ? { button: message.replyTo.button } : {}) } } : {}),\n ...(reactionsJson(message).length ? { reactions: reactionsJson(message) } : {}),\n ...(message.edit ? { edits: message.edit.seq, editedAt: message.edit.at, ...(message.edit.pending ? { editPending: true } : {}) } : {}),\n ...(message.forwarded ? { forwarded: message.forwarded } : {}),\n ...(message.card ? { card: message.card } : {}),\n ...(message.press ? { press: { messageId: message.press.messageId, button: message.press.button, label: message.press.label, ...(message.press.inferred ? { inferred: true as const } : {}) } } : {}),\n ...(message.groupPay ? { groupPay: groupPayJson(message.groupPay) } : {}),\n };\n}\n\n/**\n * A message's file; a voice note's length (ms) and loudness bars ride along (older releases said only `voice: true`),\n * and a picture's size as it is shown when its sender sent it.\n */\nexport function fileJson(file: MessageFile): NonNullable<MessageJson[\"file\"]> {\n return {\n id: file.id, name: file.name, size: file.size, mime: file.mime,\n ...(file.voice ? { voice: { duration: file.voice.duration, ...(file.voice.peaks?.length ? { peaks: [...file.voice.peaks] } : {}) } } : {}),\n ...(file.image ? { image: { width: file.image.width, height: file.image.height } } : {}),\n };\n}\n\n/** A message's reactions shown now (taken-back ones left out), oldest first. */\nexport function reactionsJson(message: StoredMessage): { by: string; emoji: string; at: number }[] {\n return Object.entries(message.reactions ?? {}).filter(([, r]) => r.e).sort(([, a], [, b]) => a.at - b.at).map(([by, r]) => ({ by, emoji: r.e, at: r.at }));\n}\n\n/**\n * A 1:1 chat's message with its author named: the engine keeps a contact's message without a name (the name rides on\n * the chat), so the name the contact gave fills `nick`, as a group's roster does. Mine keep null. Before, `nick` was\n * always null in a 1:1 chat, and so was an agent turn's `untrusted.name`.\n */\nexport function chatMessageJson(message: StoredMessage, link: Pick<LinkView, \"peerNick\"> | undefined): MessageJson {\n const json = messageJson(message);\n if (json.nick || message.sender !== \"peer\") return json;\n const nick = link?.peerNick?.trim();\n return nick ? { ...json, nick } : json;\n}\n\n/**\n * A group's message with its author named: mesh and community messages are kept with the member's key only (the\n * name rides on the edge or the roster), so the roster fills `nick` when the message has none, and for an author no\n * longer in it (removed, or back with a new member key) the name the group knew them by. A group's own line written\n * before that name came (\"Member a4w9nb5y joined\") says it, as the app draws it; before, it kept the key for good.\n * `twinOf`: the line of the payment note this message is the twin of (`groupPayTwins`).\n */\nexport function groupMessageJson(message: StoredMessage, group: Pick<GroupView, \"members\" | \"formerNames\"> | undefined, twinOf?: string): MessageJson {\n const json = twinOf ? { ...messageJson(message), twinOf } : messageJson(message);\n if (!message.member) return json;\n const nick = json.nick ?? group?.members.find((m) => m.key === message.member)?.nick ?? group?.formerNames?.[message.member];\n if (!nick) return json;\n // The engine names a member it has no name for yet `Member <first 8 of the key>` (groups.ts, community.ts).\n const placeholder = `Member ${message.member.slice(0, 8)}`;\n const text = message.event && json.text.startsWith(`${placeholder} `) ? `${nick}${json.text.slice(placeholder.length)}` : json.text;\n return { ...json, nick, text };\n}\n\n/**\n * Which payment lines of a group's history are twins of a payment note's line, by message id, as the app's group page\n * tells them (`groupPayTwin`): the requester's own request, the request as it came over the edge, a payment answering\n * it. Only for a note whose line is in `notes` (the group's, by note id): a twin of nothing is no twin.\n */\nexport function groupPayTwins(messages: readonly StoredMessage[], notes: ReadonlyMap<string, GroupPayNote>, payments: Readonly<Record<string, Pick<PaymentView, \"kind\" | \"requestId\" | \"linkId\"> | undefined>>,\n group: Pick<GroupView, \"members\" | \"myKey\"> | undefined): Map<string, string> {\n const twins = new Map<string, string>();\n for (const m of messages) {\n if (!m.paymentId || m.groupPay) continue;\n const note = groupPayTwin(m, payments[m.paymentId], (id) => notes.get(id), group?.myKey, (linkId) => groupMemberOfLink(group, linkId));\n if (note && notes.has(note)) twins.set(m.id, groupPayLineId(note));\n }\n return twins;\n}\n\n/**\n * A group as the CLI prints it. The entry link lets anyone who reads it join, so it is `<hidden>` unless asked for\n * (`--show-secret`, or `group link`); null when the group has none.\n */\nexport function groupJson(group: GroupView, showSecret = false) {\n return {\n id: group.id,\n name: group.name,\n profile: group.profile,\n status: group.status ?? (group.invitation ? \"invited\" : null),\n statusReason: group.statusReason ?? null,\n admin: group.isAdmin,\n me: group.myKey ?? null,\n canSend: group.canSend,\n link: group.entryLink ? (showSecret ? group.entryLink : \"<hidden>\") : null,\n lastMessageAt: group.lastMessageAt || null,\n // Past 16 members with hubs (WISP 902 · Group Mesh § Hubs): who is one, who is reached through them, what the admin chose.\n members: group.members.map((m) => ({ key: m.key, name: m.nick ?? null, role: m.role, me: m.me, online: m.online,\n ...(m.hub ? { hub: true } : {}), ...(m.viaHub ? { viaHub: true } : {}), ...(m.hubRole ? { hubRole: m.hubRole } : {}) })),\n ...(group.hubs ? { hubs: group.hubs } : {}),\n // A join nobody answered (the knocks stopped: `group accept` knocks again) and an invitation its sender took back\n // (`group accept` refuses it) said, as the app's card does: before, both read as a live \"invited\", stage \"knocked\".\n invitation: group.invitation ? { chat: group.invitation.linkId, accepted: group.invitation.accepted, viaLink: !!group.invitation.viaLink, stage: group.invitation.stage ?? null,\n ...(group.invitation.unanswered ? { unanswered: true } : {}), ...(group.invitation.takenBack ? { takenBack: true } : {}) } : null,\n // Other groups that came under this id (a contact's invitation, with the chat it came over, or a link opened): kept\n // beside it until the person picks (`engine keepGroup {groupId}`, or `engine switchGroup {groupId, to: <chat or link>}`).\n ...(group.others?.length ? { others: group.others.map((o) => (\"link\" in o ? { link: showSecret ? o.link : \"<hidden>\" } : { chat: o.linkId, name: o.name, members: o.members })) } : {}),\n community: group.community ?? null,\n picture: !!group.picture,\n // The node that forwards a community group's calls, as its admin named it, and whether its media is sealed end to end\n // (WISP 602; `group call`).\n call: group.call ? { sfu: group.call.sfu, e2ee: group.call.e2ee === 1 } : null,\n pin: pinJson(group.pin),\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { MAX_AVATAR_LENGTH, MAX_AVATAR_SIDE, MAX_GROUP_CALL_SFU, NO_PICTURE_METADATA, groupCallSfu, sanitizeAvatar, stripPictureMetadata } from \"@ghostly/core\";\nimport type { GroupView } from \"@ghostly/browser/shared/types\";\nimport { bool, contactKeyOf, groupById, groupNameOf, groupOf, node, notInYet, ownChatOf, settingsOf, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError, localFileError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport { guardText } from \"./secretGuard\";\nimport { groupJson } from \"./views\";\nimport { outOf } from \"./waits\";\n\n/**\n * Group administration and pictures (WISP 1100, phase 3): what the app's group menu and profile screen do. The\n * engine enforces who may do what (the admin); these check the arguments and name members.\n */\n\n/**\n * A member by key, unique key prefix or name; never this profile itself (`myName`: its name, which its own row lacks).\n * A whole key is that member, whatever another member calls itself; a prefix and a name stand side by side (two\n * members is an error, not a guess). For a grant (`byKeyOnly`: admin, a pinned hub) a member found only by the name it\n * gave itself is refused, with its key: another member could call itself that name while the one meant is away, as\n * `findOwnNamedChat` refuses a contact's own name.\n */\nexport function findMember(group: GroupView, ref: string, myName?: string, byKeyOnly = false) {\n const lower = ref.toLowerCase();\n // A ref shaped as a key (a line break, a space or capitals left on it too) is only ever that key, never a name.\n const asKey = contactKeyOf(ref);\n if (asKey !== undefined) {\n const member = group.members.find((m) => !m.me && m.key === asKey);\n if (member) return member;\n throw noMember(group, asKey, myName);\n }\n const others = group.members.filter((m) => !m.me);\n const byKey = others.filter((m) => m.key === ref);\n const matches = byKey.length ? byKey : others.filter((m) => m.key.startsWith(ref) || m.nick?.trim().toLowerCase() === lower);\n if (matches.length === 1) {\n if (byKeyOnly && !matches[0].key.startsWith(ref)) {\n throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names a member only by the name it gave itself: use its key`, { member: matches[0].key, name: matches[0].nick ?? null });\n }\n return matches[0];\n }\n throw matches.length ? new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one member`) : noMember(group, ref, myName);\n}\n\n/**\n * A ref no other member answers to. When it is this profile's own key (or a prefix of it), or its own name, it says\n * so: \"No member\" read as if this profile were not in the group.\n */\nexport function noMember(group: GroupView, ref: string, myName?: string): CliError {\n const mine = !!myName?.trim() && myName.trim().toLowerCase() === ref.toLowerCase();\n if (mine || group.members.some((m) => m.me && m.key.startsWith(ref))) return new CliError(\"bad_request\", `${JSON.stringify(ref)} is you: name another member of ${group.name}`);\n return new CliError(\"not_found\", `No member ${JSON.stringify(ref)} in ${group.name}`);\n}\n\n/**\n * A picture as Ghostly sends it: a square JPEG data URL, checked as a contact would check it. The app scales and\n * crops any image to 128×128; here the file must already be a JPEG within the bounds (no image library on Node).\n * It goes without its metadata (where it was taken, the device, the time), as the app's re-encoded one does; a\n * picture whose metadata cannot be removed is refused, never sent as it was.\n */\nexport async function pictureFrom(path: string): Promise<string> {\n let bytes: Buffer;\n // A folder or a file this user may not read is named as such, not \"No file\" for a path that is there.\n try { bytes = await readFile(resolve(path)); } catch (error) { throw localFileError(error, path) ?? new CliError(\"not_found\", `No file ${path}`); }\n let parts: Uint8Array[] | undefined;\n try {\n // Told apart by its bytes, not a type: a file that is no picture at all stays the bad_request below.\n parts = stripPictureMetadata(bytes, \"application/octet-stream\");\n } catch (error) {\n if (error instanceof Error && error.message === NO_PICTURE_METADATA) throw new CliError(\"refused\", NO_PICTURE_METADATA);\n throw error;\n }\n const url = `data:image/jpeg;base64,${(parts ? Buffer.concat(parts) : bytes).toString(\"base64\")}`;\n const checked = sanitizeAvatar(url);\n const bounds = `a JPEG of at most ${MAX_AVATAR_SIDE}×${MAX_AVATAR_SIDE} px and about ${Math.floor(MAX_AVATAR_LENGTH * 0.74 / 1000)} KB (128×128 is what the app sends)`;\n // A PNG, even 1×1, is not too big: resizing it would not help.\n if (!checked && !(bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)) throw new CliError(\"bad_request\", `${path} is not a JPEG: convert it to ${bounds}`);\n if (!checked) throw new CliError(\"bad_request\", `A picture is ${bounds}: resize it first`);\n return checked;\n}\n\nasync function picture(params: Params): Promise<string | null> {\n // Refused as the command line refuses `--clear` with a <jpeg>: before, `clear` won and the picture went, exit 0.\n if (bool(params, \"clear\") && str(params, \"path\") !== undefined) throw new CliError(\"bad_request\", \"clear removes the picture: not with path\");\n if (bool(params, \"clear\")) return null;\n return pictureFrom(str(params, \"path\", true));\n}\n\n/**\n * The node a group's calls go through (WISP 602): an https origin in its one spelling, refused here before anything is\n * signed. A URL that names an https origin in another spelling (a path, a trailing `/`, capitals, `:443`) is told that\n * origin, and an origin past the limit is told the limit: before, both were told of a path, query or `/` it may not have.\n */\nfunction callNode(raw: string, ref: string, groupId: string): string {\n const sfu = groupCallSfu(raw);\n if (sfu) return sfu;\n let origin: string | undefined;\n try {\n const url = new URL(raw);\n if (url.protocol === \"https:\") origin = url.origin;\n } catch { /* no URL at all */ }\n const quoted = JSON.stringify(raw);\n if (!origin) throw new CliError(\"bad_request\", `${quoted} is not an https origin: a call node is like https://call.example.com`);\n if (origin.length > MAX_GROUP_CALL_SFU) throw new CliError(\"bad_request\", `${quoted} is too long: a call node is an https origin of at most ${MAX_GROUP_CALL_SFU} characters`);\n throw new CliError(\"bad_request\", `${quoted} is not in its one spelling (lower case, no default port, path, query or trailing /): ghostly group call ${shellWord(ref, groupId)} --sfu ${origin}`);\n}\n\n/**\n * A group this profile administers or is in, not only an invitation: before, the engine answered `group rename`,\n * `picture`, `link`, `rotate` and `invite` on an invitation not yet joined with \"Group not found\" (engine, exit 1),\n * while `group show` listed it, and `remove`/`admin` said \"No member\" of a member list it had not received yet.\n */\nfunction joined(ctx: ApiContext, params: Params, twin?: string): GroupView {\n const group = groupOf(ctx, params, twin);\n const yet = notInYet(group, str(params, \"group\", true));\n if (yet) throw new CliError(\"refused\", yet);\n return group;\n}\n\n/** The member `params.member` names in `group`, this profile's own name said to be it; by its key only for a grant. */\nconst member = (ctx: ApiContext, group: GroupView, params: Params, grant = false) => findMember(group, str(params, \"member\", true), settingsOf(ctx).nick, grant);\n\n/** Where the app opens a group's link, as its Share gives it (WISP 903: `https://…/#/join/group2/…`). */\nexport const GROUP_LINK_ORIGIN = \"https://app.ghostly.tools\";\n\n/**\n * A group's link and the address that opens it in the app, as `invite create` answers `invite` and `link`. Only the\n * token (`group2/…`) was given: pasted in a chat it is no link anyone can tap, and the app's own Share link is this one.\n */\nexport const withUrl = (group: string, link: string | null) => ({ group, link, ...(link && { url: `${GROUP_LINK_ORIGIN}/#/join/${link}` }) });\n\nconst view = (ctx: ApiContext, id: string, params: Params) => groupJson(groupOf(ctx, { group: id }), bool(params, \"showSecret\"));\n\nexport const GROUP_ADMIN_METHODS: Record<string, Method> = {\n async \"group.invite\"(ctx, params) {\n const group = joined(ctx, params);\n // The one invited reads the group from then on: a contact's own name or a prefix of its id never names it.\n const link = ownChatOf(ctx, params);\n await node(ctx).inviteToGroup({ groupId: group.id, linkId: link.id });\n return view(ctx, group.id, params);\n },\n async \"group.remove\"(ctx, params) {\n const group = joined(ctx, params);\n const removed = member(ctx, group, params);\n await node(ctx).removeGroupMember({ groupId: group.id, key: removed.key });\n // While the link is on, whoever holds it joins (WISP 902 § Entry link), the member just removed too: said as the\n // app's Remove dialog says it.\n const linkOn = !!(groupById(ctx, group.id) ?? group).entryLink;\n return { ...view(ctx, group.id, params),\n ...(linkOn && { warning: `${removed.nick ?? \"They\"} can still join again with the group's link: ghostly group link ${group.id} --reset gives it a new one and keeps them out` }) };\n },\n async \"group.admin\"(ctx, params) {\n const group = joined(ctx, params);\n await node(ctx).makeGroupAdmin({ groupId: group.id, key: member(ctx, group, params, true).key });\n return view(ctx, group.id, params);\n },\n async \"group.hub\"(ctx, params) {\n const group = joined(ctx, params);\n const role = str(params, \"role\") ?? \"auto\";\n if (![\"pin\", \"exclude\", \"auto\"].includes(role)) throw new CliError(\"bad_request\", \"role is pin, exclude or auto\");\n await node(ctx).setGroupHub({ groupId: group.id, key: member(ctx, group, params, role === \"pin\").key, role: role === \"auto\" ? null : role as \"pin\" | \"exclude\" });\n return view(ctx, group.id, params);\n },\n async \"group.rename\"(ctx, params) {\n const group = joined(ctx, params, \"chat rename <chat> <name...>\");\n const name = groupNameOf(params);\n // Every member reads it, and a community's anyone who opens its link (docs/CLI.md § Safety).\n guardText(name, bool(params, \"force\"), \"group's name\", \"rename it\");\n await node(ctx).renameGroup({ groupId: group.id, name });\n return view(ctx, group.id, params);\n },\n async \"group.rotate\"(ctx, params) {\n const group = joined(ctx, params);\n await node(ctx).rotateGroup({ groupId: group.id });\n return view(ctx, group.id, params);\n },\n async \"group.link\"(ctx, params) {\n const group = joined(ctx, params);\n // A member removed (or gone) is refused as `group send` is: before, it got the link it held when it was removed,\n // exit 0, though `group show` said link null and the admin may have reset it or turned it off since.\n const out = outOf(group);\n if (out) throw new CliError(\"refused\", out);\n // On unless `on` says otherwise; an `on` that is no boolean (\"false\", 0) is refused, never read as on.\n const on = params.on === undefined || bool(params, \"on\"), reset = bool(params, \"reset\");\n if (!on && reset) throw new CliError(\"bad_request\", \"on: false turns the link off: not with reset\");\n if (!on) {\n await node(ctx).disableGroupLink({ groupId: group.id });\n return { group: group.id, link: null };\n }\n const { link } = await node(ctx).enableGroupLink({ groupId: group.id, ...(reset ? { reset: true } : {}) });\n return withUrl(group.id, link);\n },\n async \"group.picture\"(ctx, params) {\n const group = joined(ctx, params);\n await node(ctx).setGroupPicture({ groupId: group.id, picture: await picture(params) });\n return { group: group.id, picture: !bool(params, \"clear\") };\n },\n async \"group.call\"(ctx, params) {\n const group = joined(ctx, params);\n if (group.profile !== \"community\") throw new CliError(\"refused\", `${group.name} is a private group: only a community group has calls through a node`);\n // A profile out of the group (removed, or the admin who left) is told why, as the engine's rename and picture say\n // it: before, \"Only the admin\" to them all.\n const out = outOf(group);\n if (out) throw new CliError(\"refused\", out);\n if (!group.isAdmin) throw new CliError(\"refused\", `Only the admin of ${group.name} sets its call node`);\n const ref = str(params, \"group\", true), raw = str(params, \"sfu\");\n const e2ee = params.e2ee === undefined || params.e2ee === null ? undefined : bool(params, \"e2ee\");\n let sfu: string | null;\n // Refused as the command line refuses them with `--clear`: before, `clear` won and the node went, exit 0.\n if (bool(params, \"clear\") && raw !== undefined) throw new CliError(\"bad_request\", \"clear removes the call node: not with sfu\");\n if (bool(params, \"clear\") && e2ee !== undefined) throw new CliError(\"bad_request\", \"clear removes the call node: not with e2ee\");\n if (bool(params, \"clear\")) sfu = null;\n // An empty `--sfu` (\"$NODE\" unset) is refused with `--e2ee` too: before, it read as no --sfu and signed the old node again.\n else if ((params.sfu !== undefined && params.sfu !== null) || e2ee === undefined) sfu = callNode(str(params, \"sfu\", true), ref, group.id);\n // `--e2ee` alone turns sealed media on or off for the node the group names already.\n else if (group.call) sfu = group.call.sfu;\n else throw new CliError(\"refused\", `${group.name} has no call node: ghostly group call ${shellWord(ref, group.id)} --sfu <https origin>${e2ee ? \" --e2ee\" : \"\"}`);\n await node(ctx).setGroupCall({ groupId: group.id, sfu, ...(sfu !== null && e2ee !== undefined && { e2ee }) });\n return view(ctx, group.id, params);\n },\n async \"profile.picture\"(ctx, params) {\n const avatar = await picture(params);\n await node(ctx).updateSettings({ settings: { avatar: avatar ?? \"\" } });\n return { picture: avatar !== null };\n },\n};\n","import { identityStatement, type IdentityBinding, type IdentityStatement } from \"@ghostly/core\";\nimport { IDENTITY_PROVIDERS } from \"@ghostly/browser/proofs/registry\";\nimport { parseProofBunker } from \"@ghostly/browser/proofs/nostr\";\nimport { SignerTimeout, type IdentityProofProvider, type IdentitySigner, type SignerField, type SignerInstructions } from \"@ghostly/browser/proofs/contract\";\nimport type { IdentityProofView } from \"@ghostly/browser/shared/types\";\nimport { IDENTITY_DRAFT_TTL_MS, IDENTITY_MAX_DRAFTS } from \"@ghostly/browser/engine/identities\";\nimport { chatOf, node, num, ownChatOf, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError } from \"./errors\";\n\n/**\n * Identity proofs (WISP 300, WISP 1100 phase 3b), as the Identities page makes them: the engine draws the proof key\n * and the statement; a signer of the provider makes the evidence; the engine checks it as a contact would before it\n * keeps it. Signers run here, where the app runs them in its page:\n *\n * - `external-tool` (ssh-keygen, gpg, a Bitcoin wallet): `identity add` prints the statement and what to run, and\n * `identity complete` takes what the tool printed. Between the two the draft lives in the daemon's memory.\n * - `publish` (a DNS record, a file on a domain): the same, and `complete` asks the engine to look it up.\n * - `in-app` (a Nostr signer over NIP-46, Pubky): one `identity add`, with the signer's fields; a link or code the\n * signer waits on is reported as an `identity.approval` event, live only (never journaled or replayed), and printed\n * by the command.\n * - `redirect` (OpenID Connect), and the in-app signers that live in the page (a NIP-07 extension, an AT Protocol\n * sign-in window), need a browser window: app only.\n */\n\ninterface Draft { draftId: string; provider: string; signer: string; binding: IdentityBinding; createdAt: number }\n/**\n * Drafts per daemon: a proof made in two steps needs the same process for both. Kept as long as the engine keeps them,\n * and the oldest dropped when a fifth begins as the engine drops it, so what `identity add` promises still completes.\n */\nconst drafts = new Map<string, Draft>();\nconst NO_DRAFT = `No such draft here: it is kept by the daemon that made it, for ${IDENTITY_DRAFT_TTL_MS / 60_000} minutes and while fewer than ${IDENTITY_MAX_DRAFTS} newer ones wait`;\n\n/** The provider `id` names; a one-shot `identity add` asks before the profile opens (main.ts `identityAddCommand`). */\nexport function identityProvider(id: string): IdentityProofProvider {\n const found = IDENTITY_PROVIDERS.find((p) => p.id === id);\n if (!found) throw new CliError(\"not_found\", `No identity provider ${id} (ghostly identity providers)`);\n return found;\n}\n\n/**\n * A signer that runs in this process: not a browser sign-in, and not one that says it cannot run here (a NIP-07\n * extension, an AT Protocol sign-in window: neither exists outside the app's page).\n */\nfunction headless(s: IdentitySigner<unknown>): boolean {\n if (s.kind === \"redirect\") return false;\n try { return s.available?.() ?? true; } catch { return false; }\n}\n\nfunction signerOf(p: IdentityProofProvider, id?: string): IdentitySigner<unknown> {\n const usable = p.signers.filter(headless);\n const found = id ? p.signers.find((s) => s.id === id) : usable[0];\n if (!found) throw new CliError(id ? \"not_found\" : \"unavailable\", id ? `${p.label} has no signer ${id}` : `${p.label}: this kind of proof needs a browser window, make it in the app`);\n if (!headless(found)) {\n const instead = usable.length ? ` (here: --signer ${usable.map((s) => s.id).join(\" or \")})` : \"\";\n throw new CliError(\"unavailable\", `${found.label} needs a browser window: make this proof in the app${instead}`);\n }\n return found as IdentitySigner<unknown>;\n}\n\nconst keep = (verb: string) => (verb[0] === verb[0].toUpperCase() ? \"Keep\" : \"keep\");\n/**\n * The app's words for its own Check button and paste field, in the CLI's: what was pasted is kept for the last step,\n * `identity complete`. The steps stay the app's otherwise (a wallet's \"paste the statement\" is the wallet's field).\n */\nconst APP_WORDS: [RegExp, (...m: string[]) => string][] = [\n [/press Check/g, () => \"finish it with the last step\"],\n [/\\b(paste|copy) (it|the [\\w ]+?) into Ghostly/gi, (_, verb, what) => `${keep(verb)} ${what} for the last step`],\n [/\\b(paste) (?=what it prints|the whole signature it prints|the <file>\\.sig it writes)/gi, (_, verb) => `${keep(verb)} `],\n];\nconst inCliWords = (text: string) => APP_WORDS.reduce((t, [pattern, words]) => t.replace(pattern, words), text);\n\n/** The signer's steps, then the CLI's own last one: `identity complete` with this draft, then `identity share`. */\nfunction instructionsJson(signer: IdentitySigner<unknown>, i: SignerInstructions, draftId: string) {\n const share = \"It answers the proof; show it to a contact with ghostly identity share <chat> <id>.\";\n const last = signer.kind === \"publish\"\n ? { text: `Once it is published, check it from here: the engine looks it up. ${share}`, copy: `ghostly identity complete ${draftId}` }\n : { text: `Then finish it with what you kept${i.paste ? ` (${i.paste.label})` : \"\"}, from a file or piped to it (… | ghostly identity complete ${draftId}). ${share}`, copy: `ghostly identity complete ${draftId} --evidence-file <file>` };\n return {\n steps: [...i.steps.map((s) => ({ text: inCliWords(s.text), ...(s.copy ? { copy: s.copy } : {}) })), last],\n ...(i.paste ? { paste: i.paste.label } : {}),\n };\n}\n\nexport function proofJson(p: IdentityProofView) {\n return {\n id: p.id, provider: p.provider, subject: p.subject, verified: p.verified, issuedAt: p.issuedAt, expiresAt: p.expiresAt,\n sharedWith: p.sharedWith, ...(p.publicUri ? { publicUri: p.publicUri } : {}),\n };\n}\n\n/** Where the CLI takes a signer's field: a secret (a bunker:// link) on stdin first, kept out of ps and the shell's history. */\nfunction howToGive(field: SignerField): string {\n const stdin = `on stdin (--stdin, a ${field.name}=... line)`, flag = `--field ${field.name}=...`;\n return field.kind === \"secret\" ? `give it ${stdin}, or ${flag}` : `give it with ${flag}, or ${stdin}`;\n}\n\nfunction pruneDrafts(now = Date.now()) {\n for (const [id, draft] of drafts) if (now - draft.createdAt > IDENTITY_DRAFT_TTL_MS) drafts.delete(id);\n}\n\nasync function begin(ctx: ApiContext, p: IdentityProofProvider, subject: string, params: Params) {\n let normalized: string;\n try { normalized = p.subject?.normalize ? p.subject.normalize(subject) : subject; } catch (error) {\n throw new CliError(\"bad_request\", error instanceof Error ? error.message : String(error));\n }\n if (!normalized) throw new CliError(\"bad_request\", `Not a ${p.subject?.label ?? \"subject\"} ${p.label} takes`);\n const days = params.days === undefined ? undefined : num(params, \"days\", 0, { min: 1, max: p.validity.maxDays, whole: true });\n return node(ctx).beginIdentityProof({ provider: p.id, subject: normalized, ...(days ? { validityDays: days } : {}) });\n}\n\nexport const IDENTITY_METHODS: Record<string, Method> = {\n async \"identity.providers\"() {\n return {\n providers: IDENTITY_PROVIDERS.map((p) => ({\n id: p.id, label: p.label, category: p.category, subject: p.subject ? { label: p.subject.label, placeholder: p.subject.placeholder ?? null } : null,\n signers: p.signers.map((s) => ({ id: s.id, kind: s.kind, label: s.label, headless: headless(s),\n ...(s.kind === \"in-app\" && s.fields ? { fields: s.fields.map((f) => ({ name: f.name, label: f.label, kind: f.kind, optional: !!f.optional })) } : {}) })),\n })),\n };\n },\n\n async \"identity.list\"(ctx) {\n return { proofs: state(ctx).identityProofs.map(proofJson) };\n },\n\n /** Starts a proof. In-app signers finish it here; the others return the statement and what to do with it. */\n async \"identity.add\"(ctx, params) {\n pruneDrafts();\n const p = identityProvider(str(params, \"provider\", true));\n const signer = signerOf(p, str(params, \"signer\"));\n if (signer.kind === \"in-app\") {\n const values = (params.fields ?? {}) as Record<string, string>;\n if (typeof values !== \"object\" || Array.isArray(values) || Object.values(values).some((v) => typeof v !== \"string\")) throw new CliError(\"bad_request\", \"fields must be an object of strings\");\n for (const field of signer.fields ?? []) if (!field.optional && !values[field.name]) throw new CliError(\"usage\", `${signer.label} needs ${field.name} (${field.label}): ${howToGive(field)}`);\n // A NIP-46 link read as the signer will read it: one it refuses is the user's input, not an engine failure.\n const bunker = signer.fields?.find((f) => f.name === \"bunker\");\n if (bunker && values.bunker) {\n try { parseProofBunker(values.bunker); } catch (error) {\n throw new CliError(\"bad_request\", `${bunker.name} (${bunker.label}): ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n // The signer waits as long (a NIP-46 signer's own 2 minutes are the app's), or at most what it can (Pubky's relay).\n const most = signer.maxWaitMs ? Math.floor(signer.maxWaitMs / 1000) : 3600;\n if (typeof params.timeout === \"number\" && params.timeout > most) throw new CliError(\"bad_request\", `timeout must be a number from 5 to ${most}: ${signer.label} waits at most ${most} s for an approval`);\n const seconds = num(params, \"timeout\", Math.min(300, most), { min: 5, max: most });\n const signal = AbortSignal.timeout(seconds * 1000);\n // Once the signer's last step answered, nothing waits on the person any more: what fails after it (the engine's\n // check, which runs to its end past the deadline) is said as it is, never as a wait that ran out.\n let signed = false;\n // The caller's own id for this call, in each of its events: two proofs waiting on one daemon are told apart by it.\n const request = str(params, \"request\");\n const tag = { provider: p.id, ...(request ?{ request } : {}) };\n const proof = await signer.run({\n values, signal, waitMs: seconds * 1000,\n // A link or code to approve with holds the request's secret (contract.ts): to the listeners live, never the journal.\n onAuthUrl: (url) => { ctx.hub.emitLive(\"identity.approval\", `identity.approval:${Date.now()}`, { ...tag, url }); },\n onProgress: (message) => { ctx.hub.emit(\"identity.progress\", `identity.progress:${Date.now()}`, { ...tag, message }); },\n onApproval: (request) => {\n if (request) ctx.hub.emitLive(\"identity.approval\", `identity.approval:${Date.now()}`, { ...tag, ...(request.qr ? { qr: request.qr.value, label: request.qr.label } : {}), notes: request.notes ?? [] });\n },\n }, async (session) => {\n const { draftId, binding } = await begin(ctx, p, await session.subject(), params);\n try {\n const evidence = await session.sign(identityStatement(binding));\n signed = true;\n return await node(ctx).completeIdentityProof({ draftId, evidence });\n } catch (error) {\n try { await node(ctx).cancelIdentityProof({ draftId }); } catch { /* already gone */ }\n throw error;\n }\n }).catch((error: unknown) => {\n // The signer gives up with the signal's own words (\"The operation was aborted due to timeout\"), or its own wait's\n // at the same time (\"Signer timed out\"): an engine failure to a bot. Only while it was still waited on.\n if (signed || !(signal.aborted || error instanceof SignerTimeout) || error instanceof CliError) throw error;\n throw new CliError(\"timeout\", `Timed out after ${seconds} s waiting for ${signer.label} to approve the ${p.label} proof: --timeout <seconds> waits longer`);\n });\n return { done: true, proof: proofJson(proof) };\n }\n if (signer.kind === \"redirect\") throw new CliError(\"unavailable\", `${signer.label} needs a browser window: make this proof in the app`);\n const subject = str(params, \"subject\");\n // In the provider's words and where it goes: `identity add <provider> [subject]` shows it optional (in-app signers bring theirs).\n if (!subject) {\n const what = p.subject ? `, its ${p.subject.label.toLowerCase()}${p.subject.placeholder ? ` (${p.subject.placeholder})` : \"\"}` : \"\";\n throw new CliError(\"bad_request\", `${p.label} takes a subject${what}: ghostly identity add ${p.id} <subject>`);\n }\n const { draftId, binding } = await begin(ctx, p, subject, params);\n const statement = identityStatement(binding);\n while (drafts.size >= IDENTITY_MAX_DRAFTS) drafts.delete(drafts.keys().next().value!);\n drafts.set(draftId, { draftId, provider: p.id, signer: signer.id, binding, createdAt: Date.now() });\n return { done: false, draft: draftId, provider: p.id, signer: signer.id, statement: statement.text, instructions: instructionsJson(signer, signer.instructions(statement), draftId),expiresInSeconds: IDENTITY_DRAFT_TTL_MS / 1000 };\n },\n\n /** Finishes a two-step proof: what the tool printed (external-tool), or nothing (publish: the engine looks it up). */\n async \"identity.complete\"(ctx, params) {\n pruneDrafts();\n const draft = drafts.get(str(params, \"draft\", true));\n if (!draft) throw new CliError(\"not_found\", NO_DRAFT);\n const p = identityProvider(draft.provider);\n const signer = signerOf(p, draft.signer);\n const statement: IdentityStatement = identityStatement(draft.binding);\n let evidence: unknown;\n try {\n if (signer.kind === \"external-tool\") {\n // Said where the CLI takes it, not as the API's `evidence`; `details.needs`: the CLI reads a pipe then.\n const output = str(params, \"evidence\");\n if (!output?.trim()) throw new CliError(\"usage\", `Missing what ${signer.label} printed: give it from a file (--evidence-file f) or on stdin (… | ghostly identity complete ${draft.draftId})`, { needs: \"evidence\" });\n evidence = await signer.parse(output, statement);\n } else if (signer.kind === \"publish\") evidence = await signer.evidence(statement);\n else throw new CliError(\"bad_request\", \"This draft needs no completion\");\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError(\"bad_request\", error instanceof Error ? error.message : String(error));\n }\n const proof = await node(ctx).completeIdentityProof({ draftId: draft.draftId, evidence });\n drafts.delete(draft.draftId);\n return { done: true, proof: proofJson(proof) };\n },\n\n async \"identity.cancel\"(ctx, params) {\n const draftId = str(params, \"draft\", true);\n // As `identity.complete` says it: a draft that is not here was never made, is done, or is another daemon's.\n if (!drafts.delete(draftId)) throw new CliError(\"not_found\", NO_DRAFT);\n await node(ctx).cancelIdentityProof({ draftId });\n return { cancelled: draftId };\n },\n\n async \"identity.remove\"(ctx, params) {\n const id = str(params, \"id\", true);\n // The engine removes nothing for an id it does not know, and says nothing.\n if (!state(ctx).identityProofs.some((p) => p.id === id)) throw new CliError(\"not_found\", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);\n await node(ctx).removeIdentityProof({ id });\n return { removed: id };\n },\n\n async \"identity.share\"(ctx, params) {\n // The contact keeps the proof: a contact's own name or a prefix of its id never names the chat.\n const s = state(ctx);\n const link = ownChatOf(ctx, params, s);\n const id = str(params, \"id\", true);\n if (!s.identityProofs.some((p) => p.id === id)) throw new CliError(\"not_found\", `No identity proof ${JSON.stringify(id)} (ghostly identity list)`);\n await node(ctx).shareIdentityProof({ linkId: link.id, id });\n return { chat: link.id, shared: id };\n },\n\n async \"identity.withdraw\"(ctx, params) {\n // As `identity.share`: a contact's own name or a prefix of its id never names the chat.\n const link = ownChatOf(ctx, params);\n const id = str(params, \"id\", true);\n if (!link.identities?.shared.some((s) => s.id === id)) throw new CliError(\"not_found\", `No identity proof ${JSON.stringify(id)} shared in this chat (ghostly identity contact ${link.id})`);\n await node(ctx).withdrawIdentityProof({ linkId: link.id, id });\n return { chat: link.id, withdrawn: id };\n },\n\n /** What a contact shared in a chat, as this device checked it, and what this side shares there. */\n async \"identity.contact\"(ctx, params) {\n const link = chatOf(ctx, params);\n const view = link.identities;\n return {\n chat: link.id, support: view?.support ?? false,\n received: (view?.received ?? []).map((r) => ({ id: r.id, provider: r.provider, subject: r.subject, status: r.status, verified: r.verified, verifiedAt: r.verifiedAt, checkedAt: r.checkedAt, expiresAt: r.expiresAt, error: r.error ?? null, recheckDue: r.recheckDue, ...(r.publicProfile ? { publicProfile: r.publicProfile } : {}) })),\n shared: view?.shared ?? [],\n };\n },\n\n async \"identity.recheck\"(ctx, params) {\n const link = chatOf(ctx, params);\n const id = str(params, \"id\", true);\n if (!link.identities?.received.some((r) => r.id === id)) throw new CliError(\"not_found\", `No identity proof ${JSON.stringify(id)} from this contact (ghostly identity contact ${link.id})`);\n await node(ctx).recheckIdentityProof({ linkId: link.id, id });\n return IDENTITY_METHODS[\"identity.contact\"](ctx, { chat: link.id });\n },\n};\n","import { bool, node, str, type Method } from \"./apiKit\";\nimport { CliError } from \"./errors\";\n\n/**\n * x401 credentials (WISP 3xx): the holder keys and issued credentials a bot keeps to show a website who stands behind\n * it. Here only keeping them: `x401 fetch`, which presents one, comes later. Claim values are printed only with\n * `--show-secret`; the credential itself and the holder keys never leave the profile.\n */\n\n/** The engine's refusals (a credential that does not read, expired, bound to another key) are the caller's to fix. */\nasync function engine<T>(work: () => Promise<T>): Promise<T> {\n try { return await work(); } catch (error) {\n throw new CliError(\"bad_request\", error instanceof Error ? error.message : String(error));\n }\n}\n\nexport const X401_METHODS: Record<string, Method> = {\n /** `dropped`: the oldest key still waiting, gone for this one (a profile keeps the 8 newest waiting). */\n async \"x401.key.new\"(ctx) {\n const { id, jwk, dropped } = await node(ctx).newX401HolderKey();\n return { key: id, jwk, ...(dropped ? { dropped } : {}) };\n },\n\n async \"x401.credential.add\"(ctx, params) {\n const label = str(params, \"label\");\n return { credential: await engine(() => node(ctx).addX401Credential({ credential: str(params, \"credential\", true), ...(label ? { label } : {}) })) };\n },\n\n async \"x401.credential.list\"(ctx, params) {\n return { credentials: await node(ctx).x401Credentials({ values: bool(params, \"showSecret\") }) };\n },\n\n async \"x401.credential.remove\"(ctx, params) {\n const id = str(params, \"id\", true);\n if (!(await node(ctx).removeX401Credential({ id }))) throw new CliError(\"not_found\", `No x401 credential ${JSON.stringify(id)} (ghostly x401 credential list)`);\n return { removed: id };\n },\n};\n","import { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { GhostlyHttpError, LIMITS, parseLocalTarget, VIEWER_PERMISSIONS_POLICY, type ClientRequest, type ClientResponse, type LocalFetch } from \"@ghostly/core\";\nimport { bool, chatOf, nameKey, node, num, ownChatOf, settingsOf, shownName, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { isLive } from \"./views\";\n\n/**\n * Shared services (WISP 700/701, WISP 1100 phase 3b): a web app on this machine a contact may open over the chat's live\n * link, and a contact's app opened here on a loopback port. As on the Desktop: only loopback is reached, redirects are\n * handed back rather than followed, and a service is shared with each contact by name, never by default.\n */\n\nconst LOOPBACK = new Set([\"127.0.0.1\", \"localhost\", \"[::1]\", \"::1\"]);\n\n/** The engine's way to reach a shared app: loopback only, no redirect followed, no cookies (Node sends none). */\nexport const nodeLocalFetch: LocalFetch = async (request) => {\n const url = new URL(request.url);\n if (![\"http:\", \"https:\"].includes(url.protocol) || !(LOOPBACK.has(url.hostname) || /^127\\.\\d+\\.\\d+\\.\\d+$/.test(url.hostname))) {\n throw new Error(\"Shared services are reached on this machine only\");\n }\n const response = await fetch(url, { method: request.method, headers: request.headers, body: request.body as BodyInit | null, signal: request.signal, redirect: \"manual\", ...(request.body ? { duplex: \"half\" } : {}) } as RequestInit);\n const headers: [string, string][] = [];\n response.headers.forEach((value, name) => headers.push([name, value]));\n return {\n status: response.status, headers,\n body: response.body ? (async function* () {\n const reader = response.body!.getReader();\n try { for (;;) { const { done, value } = await reader.read(); if (done) return; if (value?.length) yield value; } } finally { reader.cancel().catch(() => {}); }\n })() : null,\n };\n};\n\n/**\n * Contact services open on loopback ports, by `<peer>/<service>`, while this process runs: each as soon as it starts\n * opening, so a second `service open` meanwhile answers the same one. A server that could not open is taken out.\n */\nconst open = new Map<string, Promise<OpenedService>>();\nconst MAX_RESPONSE_BYTES = 32 * 1024 * 1024;\n/** Cookie names an opened service may set and have passed back (browsers keep about 180 per host). */\nconst MAX_COOKIE_NAMES = 256;\n\n/**\n * The cookie that shows a browser was given this service's link here. It is this machine's, never the contact's:\n * it is not passed on to the contact, and a `Set-Cookie` from the contact by that name is dropped.\n */\nexport const OPEN_COOKIE = \"ghostly_open\";\n/** The link `service open` prints: it sets `OPEN_COOKIE` and sends the browser on to `/`. */\nconst OPEN_PATH = \"/.ghostly-open/\";\n\n/**\n * Only the cookies this service set itself (by name, from its own `Set-Cookie`) go on to the contact; any other a\n * browser sends (one set for localhost by another app here, this machine's `OPEN_COOKIE`) stays here.\n */\nexport function ownCookies(header: string, names: ReadonlySet<string>): string | null {\n const kept = header.split(\";\").map((pair) => pair.trim()).filter((pair) => {\n const at = pair.indexOf(\"=\");\n const name = at > 0 ? pair.slice(0, at).trim() : \"\";\n return !!name && name !== OPEN_COOKIE && names.has(name);\n });\n return kept.length ? kept.join(\"; \") : null;\n}\n\n/** The cookie a `Set-Cookie` sets, by name. */\nexport function setCookieName(value: string): string | null {\n const at = value.indexOf(\"=\"), end = value.indexOf(\";\");\n if (at <= 0 || (end !== -1 && end < at)) return null;\n return value.slice(0, at).trim() || null;\n}\n\n/**\n * A contact's `Set-Cookie` as this machine passes it to the browser: without `Domain`, so the cookie stays on the\n * service's own host name (not every *.localhost). Null for one this machine does not take (`OPEN_COOKIE`, no name).\n */\nexport function hostOnlyCookie(value: string): string | null {\n const name = setCookieName(value);\n if (!name || name === OPEN_COOKIE) return null;\n return value.split(\";\").filter((part, i) => i === 0 || !/^\\s*domain\\s*(=|$)/i.test(part)).join(\";\");\n}\n\n/** A cookie's values in a `Cookie` header, by name (a page may set another by the same name on a narrower path). */\nfunction cookieValues(header: string | undefined, name: string): string[] {\n return (header ?? \"\").split(\";\").flatMap((pair) => {\n const at = pair.indexOf(\"=\");\n return at > 0 && pair.slice(0, at).trim() === name ? [pair.slice(at + 1).trim()] : [];\n });\n}\n\nfunction sameSecret(a: string, b: string): boolean {\n return a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));\n}\n\n/** How an opened service reaches the contact's app: the engine's `request` for that contact and service. */\nexport type ServiceSend = (request: ClientRequest) => Promise<ClientResponse>;\n\nexport interface OpenedService {\n server: Server;\n /** The link to open: it hands the browser this service's cookie, then shows `/`. */\n url: string;\n /** The service's own host name, `<random>.localhost:<port>`: any other `Host` is not this service. */\n host: string;\n}\n\n/**\n * Added to every answer of a contact's app, next to any policy the contact sends (a browser enforces both): its\n * requests (fetch, XHR, beacons, WebSockets, EventSource) and forms reach only its own origin, the contact's server;\n * its scripts, pictures, frames, fonts, media, styles and workers its own origin and https sites (and inline, data:\n * and blob: content), never plain http. The page is served from `<random>.localhost`, which Chrome counts as this\n * machine, so its own guard for requests to local addresses (Local Network Access) would not ask before the page\n * reached another service on 127.0.0.1 or the local network, and a policy cannot tell a public https site from one\n * here or on the local network with a trusted certificate: requests that can read an answer or post go nowhere else.\n * Inline scripts and styles stay allowed: this policy bounds where the page reaches, not how the app is written. A\n * top-level navigation is not covered: no browser lets a policy bound it.\n */\nexport const OPENED_SERVICE_CSP = \"default-src 'self' https: data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; form-action 'self'\";\n\n/**\n * The policy while Hide my IP from contacts is on (`relayOnly`): no `https:`, so the page loads nothing but its own\n * origin. A picture or script from a server the contact names would show that server this machine's address.\n */\nexport const OPENED_SERVICE_CSP_RELAY_ONLY = \"default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; form-action 'self'\";\n\n/**\n * The contact's headers that are not passed on: each makes the browser send something to a place it names, outside\n * `connect-src` (violation and network-error reports, and the endpoints they go to; `Link` preloads, prefetches and\n * early connections). Only the contact's server is reached.\n */\nexport const OPENED_SERVICE_DROPPED_HEADERS = [\"content-security-policy-report-only\", \"reporting-endpoints\", \"report-to\", \"nel\", \"link\"];\n\n/**\n * A contact's headers that would set the page's browser features (camera, microphone, location, a device): the\n * viewer's own `VIEWER_PERMISSIONS_POLICY` takes their place, as in the extension's viewer (core `withViewerPolicy`).\n */\nconst OPENED_SERVICE_FEATURE_HEADERS = [\"permissions-policy\", \"feature-policy\"];\n\n/** The directives of a contact's policy that send reports to a URL it names, dropped from it. */\nexport const OPENED_SERVICE_DROPPED_DIRECTIVES = [\"report-uri\", \"report-to\"];\n\n/** A contact's `Content-Security-Policy` value (one policy or several joined by commas) without its report directives. */\nexport function withoutReports(value: string): string {\n return value.split(\",\")\n .map((policy) => policy.split(\";\").filter((directive) => !OPENED_SERVICE_DROPPED_DIRECTIVES.includes(directive.trim().split(/\\s+/)[0].toLowerCase())).join(\";\").trim())\n .filter((policy) => policy.replaceAll(\";\", \"\").trim())\n .join(\", \");\n}\n\n/** `service open` while Hide my IP from contacts is on (as the browser extension refuses to open one). */\nexport const SERVICE_OPEN_OFF_RELAY_ONLY = \"A contact's app does not open here while Hide my IP from contacts is on: a browser tab cannot keep its page off WebRTC\";\n\n/** `service open` or `service close` in a one-shot: only the daemon keeps a contact's app open on a port. */\nexport const SERVICE_NEEDS_DAEMON = \"An opened service lives in the daemon: start `ghostly daemon --detach` first\";\n\nfunction plain(response: ServerResponse, status: number, text: string, headers: Record<string, string> = {}): void {\n response.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\", \"cache-control\": \"no-store\", ...headers });\n response.end(text);\n}\n\n/**\n * A contact's app on a loopback port of this machine, under a host name of its own (`<random>.localhost`): its\n * cookies and storage are its own, apart from any other app on 127.0.0.1 or localhost, and a name that merely\n * resolves here (DNS rebinding) is not it. Only a browser given the link (which sets `OPEN_COOKIE`) is served; anyone\n * else on this machine who finds the port gets 404. The body streams through, bounded by `MAX_RESPONSE_BYTES`.\n * `relayOnly`: Hide my IP from contacts was on when it opened (`OPENED_SERVICE_CSP_RELAY_ONLY`).\n */\nexport async function openServiceServer(send: ServiceSend, port = 0, { relayOnly = false }: { relayOnly?: boolean } = {}): Promise<OpenedService> {\n const policy = relayOnly ? OPENED_SERVICE_CSP_RELAY_ONLY : OPENED_SERVICE_CSP;\n const name = `${randomBytes(16).toString(\"hex\")}.localhost`;\n const token = randomBytes(32).toString(\"hex\");\n const cookies = new Set<string>();\n let host = \"\", portless = \"\";\n const server = createServer((request, response) => {\n const asked = request.headers.host?.toLowerCase();\n if (!asked || (asked !== host && asked !== portless)) return plain(response, 404, \"Not found\");\n const path = request.url ?? \"/\";\n if (path.startsWith(OPEN_PATH)) {\n if (!sameSecret(path.slice(OPEN_PATH.length), token)) return plain(response, 404, \"Not found\");\n return plain(response, 303, \"\", { location: \"/\", \"referrer-policy\": \"no-referrer\", \"set-cookie\": `${OPEN_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax` });\n }\n if (!cookieValues(request.headers.cookie, OPEN_COOKIE).some((value) => sameSecret(value, token))) return plain(response, 404, \"Not found\");\n const chunks: Buffer[] = [];\n let size = 0, refused = false;\n request.on(\"data\", (chunk: Buffer) => {\n if (refused) return;\n size += chunk.length;\n if (size > LIMITS.maxRequestBodyBytes) {\n refused = true;\n chunks.length = 0;\n plain(response, 413, \"The request body is too large\", { connection: \"close\" });\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => { if (!refused) void proxy(request, response, chunks, send, cookies, policy); });\n });\n await new Promise<void>((resolve, reject) => { server.once(\"error\", reject); server.listen(port, \"127.0.0.1\", () => { server.off(\"error\", reject); resolve(); }); });\n const on = (server.address() as AddressInfo).port;\n host = `${name}:${on}`;\n // On port 80 a browser leaves the port out of Host (`new URL(\"http://a.localhost:80/\").host` is `a.localhost`).\n if (on === 80) portless = name;\n return { server, host, url: `http://${host}${OPEN_PATH}${token}` };\n}\n\nasync function proxy(request: IncomingMessage, response: ServerResponse, chunks: Buffer[], send: ServiceSend, cookies: Set<string>, policy: string): Promise<void> {\n // A browser that goes away stops the contact's answer too.\n const stop = new AbortController();\n response.on(\"close\", () => { if (!response.writableFinished) stop.abort(); });\n try {\n const headers = Object.entries(request.headers).flatMap(([name, value]) => (Array.isArray(value) ? value.map((v) => [name, v] as [string, string]) : value === undefined ? [] : [[name, value] as [string, string]]))\n .flatMap(([name, value]): [string, string][] => {\n if (name.toLowerCase() !== \"cookie\") return [[name, value]];\n const own = ownCookies(value, cookies);\n return own ? [[name, own]] : [];\n });\n const answer = await send({ method: request.method ?? \"GET\", path: request.url ?? \"/\", headers, body: chunks.length ? new Uint8Array(Buffer.concat(chunks)) : null, maxResponseBytes: MAX_RESPONSE_BYTES, signal: stop.signal });\n const out: Record<string, string | string[]> = {};\n for (const [name, value] of answer.headers) {\n const lower = name.toLowerCase();\n if (lower === \"transfer-encoding\" || lower === \"connection\" || OPENED_SERVICE_DROPPED_HEADERS.includes(lower) || OPENED_SERVICE_FEATURE_HEADERS.includes(lower)) continue;\n if (lower === \"set-cookie\") {\n const cookie = hostOnlyCookie(value);\n if (!cookie) continue;\n if (cookies.size < MAX_COOKIE_NAMES) cookies.add(setCookieName(cookie)!);\n out[lower] = [...((out[lower] as string[] | undefined) ?? []), cookie];\n } else if (lower === \"content-security-policy\") {\n const policy = withoutReports(value);\n if (policy) out[lower] = [...((out[lower] as string[] | undefined) ?? []), policy];\n } else out[lower] = value;\n }\n out[\"content-security-policy\"] = [...((out[\"content-security-policy\"] as string[] | undefined) ?? []), policy];\n out[\"permissions-policy\"] = VIEWER_PERMISSIONS_POLICY;\n response.writeHead(answer.status, out);\n // Streamed, not gathered: past the cap (or when the contact drops it) the body stops and the connection closes.\n await pipeline(Readable.from(answer.body, { objectMode: false }), response);\n } catch (error) {\n // Once the status line is out, a second one cannot follow: the response is cut, and the browser sees it end short.\n if (response.headersSent) { response.destroy(); return; }\n const gone = error instanceof GhostlyHttpError && [\"unreachable\", \"timeout\", \"closed\", \"offline\"].includes(error.code);\n plain(response, gone ? 503 : 502, gone ? \"This service is not reachable. Services exist while their ghost is online.\" : `The request failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * The service a command names, by its id: one of this profile's. The engine changes nothing for an id it does not\n * know and says nothing, so a mistyped id read as done (\"shared\": true, with a contact).\n */\nfunction serviceOf(ctx: ApiContext, params: Params): string {\n const serviceId = str(params, \"service\", true);\n const { services } = state(ctx);\n if (!services.some((s) => s.id === serviceId)) throw noService(serviceId, servicesNamed(services, serviceId));\n return serviceId;\n}\n\n/** The ids of the services `given` names by their name, compared as a chat's label is (`nameKey`: one case, one form). */\nfunction servicesNamed(services: readonly { id: string; name: string }[], given: string): string[] {\n const key = nameKey(given);\n return key ? services.filter((s) => nameKey(s.name) === key).map((s) => s.id) : [];\n}\n\n/**\n * No service of that id. A service's name given instead (`service add \"My App\"` makes `my-app`) is told which id to\n * use: before, it read \"No service\" of a service `service list` shows by that very name. Same code and exit either way.\n */\nfunction noService(given: string, named: readonly string[]): CliError {\n const quoted = JSON.stringify(given);\n if (!named.length) return new CliError(\"not_found\", `No service ${quoted} (ghostly service list)`);\n const which = named.length === 1 ? `${named[0]}: use its id` : `${named.length} services, ${named.slice(0, -1).join(\", \")} and ${named.at(-1)}: use one of their ids`;\n return new CliError(\"not_found\", `No service with id ${quoted}. ${quoted} is the name of ${which} (ghostly service list)`);\n}\n\n/**\n * On, unless `off`; or as the answer's own key (`shared`, `enabled`) says, when a socket client sends it back. Before,\n * only `off` was read, so `{\"shared\": false}` shared the service with the contact and `{\"enabled\": false}` turned it on.\n * Both, saying the opposite, are refused: neither is guessed.\n */\nfunction onUnlessOff(params: Params, key: string): boolean {\n const on = !bool(params, \"off\");\n if (params[key] === undefined || params[key] === null) return on;\n const said = bool(params, key);\n if (params.off !== undefined && params.off !== null && said !== on) throw new CliError(\"bad_request\", `${key}: ${said} and off: ${!on} say the opposite: give one of them`);\n return said;\n}\n\n/**\n * A port the person chose that could not be taken, in words that name it. Before, one in use was Node's EADDRINUSE as\n * `engine`, and one not allowed read as a file (`localFileError`): \"Not allowed to write or read the path\".\n */\n/** As long as the engine keeps a service's name (node.ts addService) and the Desktop's form takes it (Services.tsx). */\nconst MAX_SERVICE_NAME_LENGTH = 48;\n\n/**\n * The `name` of `service add`, refused as a chat's or the profile's name is (`shownName`), before anything is made.\n * Before, one of spaces was the engine's plain error as `engine` (exit 1), and a longer one was cut with exit 0.\n */\nfunction serviceNameOf(params: Params): string {\n const name = shownName(str(params, \"name\", true), MAX_SERVICE_NAME_LENGTH, \"A service's name\");\n // The engine cuts at 48 UTF-16 units, where a character of two units (most emoji) counts as 2.\n if (name.length > MAX_SERVICE_NAME_LENGTH) {\n throw new CliError(\"bad_request\", `A service's name is up to ${MAX_SERVICE_NAME_LENGTH} characters as stored, an emoji counting as 2 (this one is ${name.length})`, { length: name.length, max: MAX_SERVICE_NAME_LENGTH });\n }\n return name;\n}\n\n/** `service add`'s name and target, checked with no profile open (api.ts `refuseBeforeStart`). */\nexport function serviceShape(params: Params): { name: string; target: string } {\n const name = serviceNameOf(params);\n const target = str(params, \"target\", true);\n // The engine's own check of the target (core http.ts `parseLocalTarget`), the only one: a query, a fragment, a user\n // and password or a scheme other than http(s) is the person's input to fix, `bad_request` naming it. Thrown by the\n // engine, they were plain errors, `engine` (exit 1): \"the engine failed\" (agents#894). A check of its own here\n // read `localhost:8080` as the scheme `localhost:`, refused `127.0.0.1:8080` as no URL, and let `127.0.0.2` through\n // for the engine to refuse in other words.\n try { parseLocalTarget(target); } catch (error) {\n const said = error instanceof Error ? error.message : String(error);\n // Read as the engine reads it (no scheme is http) and named without its user, password, query and fragment: the\n // parts refused here can hold a secret (a token). One that is no URL at all (a mistyped port) is not repeated: it\n // has no parts to tell apart, and a token or password in it would be said whole.\n const text = target.trim();\n let shown = \"\";\n try {\n const url = new URL(/^[a-z][a-z0-9+.-]*:\\/\\//i.test(text) ? text : `http://${text}`);\n shown = `: ${url.protocol}//${url.host}${url.pathname}`;\n } catch { /* Not a URL: not repeated. */ }\n throw new CliError(/^Only services on this machine/.test(said) ? \"refused\" : \"bad_request\", `${said}${shown}`);\n }\n return { name, target };\n}\n\nfunction portError(error: unknown, port: number): unknown {\n const { code } = (error ?? {}) as { code?: unknown };\n if (port && code === \"EADDRINUSE\") return new CliError(\"busy\", `Port ${port} is in use on this machine: choose another, or leave out --port`);\n if (port && (code === \"EACCES\" || code === \"EPERM\")) return new CliError(\"refused\", `Port ${port} is not allowed for this user: choose another, or leave out --port`);\n return error;\n}\n\nexport const SERVICE_METHODS: Record<string, Method> = {\n async \"service.list\"(ctx) {\n return { services: state(ctx).services.map((s) => ({ id: s.id, name: s.name, target: s.target, enabled: s.enabled, sharedWith: s.sharedWith ?? [], requests: s.requests })) };\n },\n async \"service.add\"(ctx, params) {\n const { name, target } = serviceShape(params);\n // `service`, as the rest of the family answers it; `serviceId` (the engine's key) stays beside it for a release.\n const { serviceId } = node(ctx).addService({ name, target });\n return { service: serviceId, serviceId };\n },\n async \"service.remove\"(ctx, params) {\n const serviceId = serviceOf(ctx, params);\n await node(ctx).removeService({ serviceId });\n return { removed: serviceId };\n },\n async \"service.enable\"(ctx, params) {\n const enabled = onUnlessOff(params, \"enabled\");\n const serviceId = serviceOf(ctx, params);\n await node(ctx).setServiceEnabled({ serviceId, enabled });\n return { service: serviceId, enabled };\n },\n async \"service.share\"(ctx, params) {\n // A grant the contact keeps using: only what this side chose names its chat, as for `call auto --from`.\n const link = ownChatOf(ctx, params);\n const shared = onUnlessOff(params, \"shared\");\n const serviceId = serviceOf(ctx, params);\n await node(ctx).setServiceShared({ serviceId, peerPubKeyZ32: link.peerPubKeyZ32, shared });\n return { service: serviceId, chat: link.id, shared };\n },\n /** What a contact shares with this profile (while its app is live). */\n async \"service.peer\"(ctx, params) {\n const link = chatOf(ctx, params);\n return { chat: link.id, live: isLive(link), services: link.peerServices ?? [] };\n },\n /** A contact's shared app on a loopback port of this machine, as the Desktop opens it in a window. */\n async \"service.open\"(ctx, params) {\n if (ctx.mode !== \"daemon\") throw new CliError(\"unavailable\", SERVICE_NEEDS_DAEMON);\n // Hide my IP from contacts: the app would run in an ordinary browser tab, where nothing keeps its page off WebRTC\n // (a STUN server the contact names would see this machine's address), so none opens while it is on.\n if (settingsOf(ctx).relayOnly === true) throw new CliError(\"unavailable\", SERVICE_OPEN_OFF_RELAY_ONLY);\n const link = chatOf(ctx, params);\n const service = str(params, \"service\", true);\n const key = `${link.peerPubKeyZ32}/${service}`;\n const port = num(params, \"port\", 0, { min: 0, max: 65535, whole: true });\n // One still opening counts: before, two opens at once each made a server, and `service close` closed only the second.\n const already = await open.get(key)?.catch(() => undefined);\n if (already) {\n // Another port asked for: the link on this one, with exit 0, left a script that was told a port on the wrong one.\n const on = (already.server.address() as AddressInfo).port;\n if (port && port !== on) throw new CliError(\"busy\", `That service is open here on port ${on}: ghostly service close ${link.id} ${service} first, or leave out --port`);\n return { chat: link.id, service, url: already.url };\n }\n if (!link.peerServices?.some((s) => s.id === service)) throw new CliError(\"not_found\", `The contact shares no service ${service} (or is not live)`);\n const peer = link.peerPubKeyZ32;\n // Another open began while this one waited: it answers that one.\n if (open.has(key)) return SERVICE_METHODS[\"service.open\"](ctx, params);\n const opening = openServiceServer((request) => node(ctx).request(peer, service, request), port).catch((error: unknown) => {\n if (open.get(key) === opening) open.delete(key);\n throw portError(error, port);\n });\n open.set(key, opening);\n const opened = await opening;\n return { chat: link.id, service, url: opened.url };\n },\n async \"service.close\"(ctx, params) {\n // A one-shot has none open: it said \"not open here\" of one the daemon has.\n if (ctx.mode !== \"daemon\") throw new CliError(\"unavailable\", SERVICE_NEEDS_DAEMON);\n const link = chatOf(ctx, params);\n const key = `${link.peerPubKeyZ32}/${str(params, \"service\", true)}`;\n const pending = open.get(key);\n open.delete(key);\n const entry = await pending?.catch(() => undefined);\n if (!entry) throw new CliError(\"not_found\", \"That service is not open here\");\n await closeOpened(entry);\n return { closed: key };\n },\n};\n\n/**\n * Closed means closed: an answer still streaming (a page's EventSource) kept `close` waiting for good, and kept coming.\n * Each connection's end stops the contact's answer too (`proxy`).\n */\nfunction closeOpened(entry: OpenedService): Promise<void> {\n return new Promise<void>((resolve) => {\n entry.server.close(() => resolve());\n entry.server.closeAllConnections();\n });\n}\n\n/**\n * `chat remove`: the services opened from a contact no chat here has any more. Before, they stayed on their ports, each\n * request a 503, and `service close` answered `No chat` for good.\n */\nexport async function closeServicesOf(ctx: ApiContext, peer: string): Promise<void> {\n if (state(ctx).links.some((link) => link.peerPubKeyZ32 === peer)) return;\n const keys = [...open.keys()].filter((key) => key.startsWith(`${peer}/`));\n await Promise.all(keys.map(async (key) => {\n const pending = open.get(key);\n open.delete(key);\n const entry = await pending?.catch(() => undefined);\n if (entry) await closeOpened(entry);\n }));\n}\n","import { bool, list, str, type Method } from \"../apiKit\";\n\n/** Voice calls (WISP 1100 § Calls): the API methods. The audio itself goes over each call's own socket. */\nexport const CALL_METHODS: Record<string, Method> = {\n async \"call.start\"(ctx, params) {\n return ctx.calls.start(str(params, \"chat\", true), { rate: params.rate });\n },\n async \"call.answer\"(ctx, params) {\n return ctx.calls.answer(str(params, \"call\"), { rate: params.rate });\n },\n async \"call.hangup\"(ctx, params) {\n return ctx.calls.hangup(str(params, \"call\"));\n },\n async \"call.list\"(ctx) {\n return { calls: ctx.calls.list(), autoAnswer: ctx.calls.getAuto(), available: ctx.runtime.callsUnavailable === null, ...(ctx.runtime.callsUnavailable ? { unavailable: ctx.runtime.callsUnavailable } : {}) };\n },\n async \"call.get\"(ctx, params) {\n return ctx.calls.get(str(params, \"call\"));\n },\n async \"call.flush\"(ctx, params) {\n return ctx.calls.flush(str(params, \"call\"));\n },\n async \"call.auto\"(ctx, params) {\n if (params.on === undefined) return { autoAnswer: ctx.calls.getAuto() };\n return { autoAnswer: ctx.calls.setAuto({ on: bool(params, \"on\"), from: list(params, \"from\"), rate: params.rate }) };\n },\n};\n","import { readFileSync, renameSync, statSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { appCardUrl, appRef, isAppRef, isAppUrl, type AppPermission } from \"@ghostly/core\";\nimport { list, node, str, type ApiContext, type Method } from \"./apiKit\";\nimport { isAppFetchUrl } from \"@ghostly/browser/engine/appFetch\";\nimport { checkedBundle } from \"./apps\";\nimport { CliError, shownValue } from \"./errors\";\n\n/*\n * `app serve` (WISP 1200 § A bot on the other side): the apps this profile speaks for, in chats, as a bot. No app runs\n * here: a program of the bot's own speaks the app's messages. An app is served from its signed bundle, checked as a\n * client checks one, and each permission its manifest asks is answered on the command line, never by itself. The list\n * is kept in the profile folder (`apps.json`); the engine offers apps/1 to contacts only while it holds an app, which\n * it reads when it starts.\n */\n\n/** The permissions a bot can be granted: `internet` and `files` are a page's, and no page runs here. */\nconst GRANTABLE: readonly AppPermission[] = [\"chat\", \"name\"];\n\nexport interface ServedApp {\n ref: string;\n title: string;\n version: string;\n sequence: number;\n digest: string;\n /** Where a contact's app fetches the bundle (the app card's `url`), when one is known. */\n url?: string;\n /** What the manifest asks, and what this profile granted of it. */\n permissions: AppPermission[];\n granted: AppPermission[];\n servedAt: number;\n}\n\nconst servedFile = (dir: string) => join(dir, \"apps.json\");\n\n/** The apps a profile serves, by its folder: none when the file is missing or not a list of them. */\nexport function servedApps(dir: string): ServedApp[] {\n try {\n const read = JSON.parse(readFileSync(servedFile(dir), \"utf8\")) as unknown;\n return Array.isArray(read) ? read.filter((app): app is ServedApp => !!app && typeof app === \"object\" && isAppRef((app as ServedApp).ref)) : [];\n } catch { return []; }\n}\n\n/** Writes of the list by this process: a stamp taken before one never matches one taken after, whatever the clock. */\nlet writes = 0;\n\n/**\n * What changes whenever `apps.json` does, for a reader that keeps what it learned from the list until then: this\n * process's writes, and the file's inode, size and change times (a one-shot `app serve` writes it from another process).\n * Cheaper than a read: no parse.\n */\nexport function servedStamp(dir: string): string {\n try {\n const s = statSync(servedFile(dir), { bigint: true });\n return `${writes} ${s.ino} ${s.size} ${s.mtimeNs} ${s.ctimeNs}`;\n } catch { return `${writes} none`; }\n}\n\nfunction writeServed(dir: string, apps: ServedApp[]): void {\n const file = servedFile(dir);\n writeFileSync(file + \".tmp\", JSON.stringify(apps, null, 2) + \"\\n\", { mode: 0o600 });\n renameSync(file + \".tmp\", file);\n writes++;\n}\n\n/** A served app by its reference or, when only one has it, its name. */\nexport function servedApp(apps: readonly ServedApp[], ref: string): ServedApp {\n const matches = apps.filter((a) => a.ref === ref || a.ref.split(\"/\")[1] === ref);\n if (matches.length !== 1) throw new CliError(matches.length ? \"bad_request\" : \"not_found\", matches.length ? `${JSON.stringify(ref)} names more than one served app: give its whole reference` : `No served app ${JSON.stringify(ref)}: app serve its bundle first`);\n return matches[0];\n}\n\n/** A link a contact's app reads a card's bundle from. */\nconst readable = (url: string | undefined): url is string => isAppFetchUrl(url) && appCardUrl(url) !== undefined;\n\n/** Whether this engine offers apps/1 now: it read the list when it started, so the first app served waits for a restart. */\nconst offered = (ctx: ApiContext, apps: ServedApp[]) => ({ offered: ctx.runtime.apps, ...(apps.length > 0 && !ctx.runtime.apps && { restart: true }) });\n\nexport const APP_SERVE_METHODS: Record<string, Method> = {\n async \"app.serve\"(ctx, params) {\n const source = str(params, \"bundle\", true);\n const grant = list(params, \"grant\");\n if (grant.includes(\"internet\")) throw new CliError(\"refused\", \"internet cannot be granted here: no app's page runs on the CLI, and a bot reaches the network as its own program\");\n if (grant.includes(\"files\")) throw new CliError(\"refused\", \"files cannot be granted here: no app's page runs on the CLI to ask a person for a file, and a bot reads files as its own program\");\n const ungrantable = grant.filter((p) => !(GRANTABLE as readonly string[]).includes(p));\n if (ungrantable.length) throw new CliError(\"bad_request\", `grant takes ${GRANTABLE.join(\" or \")}, not ${ungrantable.map((p) => shownValue(p)).join(\", \")}`);\n const given = str(params, \"url\");\n if (given !== undefined && !isAppUrl(given)) throw new CliError(\"bad_request\", \"url is where a contact's app reads the bundle: https only, no user or password, jsDelivr only at a full commit\");\n if (given !== undefined && /[?#]/.test(given)) throw new CliError(\"bad_request\", \"url goes to contacts on the app's card: no query or fragment (a private repository's token rides there); publish the app in a public repository\");\n // A contact's app installs a card's app only from the hosts it reads from (isAppFetchUrl), and a card's link has no\n // space or control character (appCardUrl): any other link went on the card, or off it without a word.\n if (given !== undefined && !readable(given)) throw new CliError(\"bad_request\", \"url is where a contact's app reads the bundle: raw.githubusercontent.com, or cdn.jsdelivr.net at a full commit, with no port and no space\");\n const { bundle, url } = await checkedBundle(source);\n const m = bundle.manifest;\n if (!m.permissions.includes(\"chat\")) throw new CliError(\"refused\", `${m.title} does not ask for chat: it talks to no contact, so a bot has nothing to speak for it`);\n const extra = grant.filter((p) => !m.permissions.includes(p as AppPermission));\n if (extra.length) throw new CliError(\"bad_request\", `${m.title} does not ask for ${extra.join(\" or \")}: grant only what its manifest asks (${m.permissions.join(\", \")})`);\n const missing = m.permissions.filter((p) => GRANTABLE.includes(p) && !grant.includes(p));\n if (missing.length)\n throw new CliError(\"confirm\", `${m.title} asks for ${missing.join(\" and \")}: serve it with ${missing.map((p) => `--grant ${p}`).join(\" \")} to allow that`, { asks: m.permissions, missing });\n const ref = appRef(m.publisher, m.name);\n // The card's link never carries the query of the URL the bundle was read from (a private file's token). Without\n // --url, the first link a contact's app can read from: where the bundle was read, else the manifest's sources.\n const cardUrl = appCardUrl(given ?? [url, ...(m.sources ?? [])].find(readable));\n const app: ServedApp = {\n ref, title: m.title, version: m.version, sequence: m.sequence, digest: bundle.digest, ...(cardUrl !== undefined && { url: cardUrl }),\n permissions: m.permissions, granted: m.permissions.filter((p) => grant.includes(p)), servedAt: Date.now(),\n };\n const apps = servedApps(ctx.runtime.paths.dir);\n const held = apps.find((a) => a.ref === ref);\n // Rollback, as a client's (WISP 1200 § Updates and rollback): never a lower sequence over a higher one, nor another\n // bundle under the same sequence.\n if (held && app.sequence < held.sequence) throw new CliError(\"refused\", `${m.title} ${held.version} (sequence ${held.sequence}) is served: ${m.version} is older (sequence ${app.sequence}); app unserve it first to go back`);\n if (held && app.sequence === held.sequence && app.digest !== held.digest) throw new CliError(\"refused\", `Another ${m.title} with sequence ${app.sequence} is served (two different versions ${app.sequence} exist); app unserve it first to take this one`);\n const next = [...apps.filter((a) => a.ref !== ref), app].sort((a, b) => (a.ref < b.ref ? -1 : 1));\n writeServed(ctx.runtime.paths.dir, next);\n return { served: app, ...offered(ctx, next) };\n },\n\n async \"app.served\"(ctx) {\n const apps = servedApps(ctx.runtime.paths.dir);\n return { apps, ...offered(ctx, apps) };\n },\n\n async \"app.unserve\"(ctx, params) {\n const ref = str(params, \"ref\", true);\n const apps = servedApps(ctx.runtime.paths.dir);\n const app = servedApp(apps, ref);\n const next = apps.filter((a) => a !== app);\n writeServed(ctx.runtime.paths.dir, next);\n // Open in a chat, it stops there too: `app close` no longer names it, and the contact's frames would still come.\n if (ctx.mode === \"daemon\") node(ctx).appsCloseOf(app.ref);\n return { unserved: app.ref, apps: next.length, ...offered(ctx, next) };\n },\n};\n","import type { AppFrameEvent } from \"@ghostly/core\";\nimport { servedApps, servedStamp } from \"./appServe\";\nimport type { EventHub } from \"./events\";\n\n/*\n * What a contact's app says in a chat, for the apps this profile serves as a bot (WISP 1200 § A bot on the other side):\n * `app.opened {chat, app, version}`, `app.closed {chat, app, offline?}` and `app.message {chat, app, data}`, `app` being\n * the app's reference. The engine names an app by its chat app id, which differs in every chat: it is matched against\n * the served apps' ids in that chat, so a frame of any other app names nothing here and is not reported. `data` is the\n * contact's own JSON, already held to the receiver's limits by the engine: untrusted, never instructions.\n */\n\n/** The engine's part: the chat app id of a reference in a chat (it throws for a chat that is not a paired 1:1 chat). */\nexport interface AppIds { appId(params: { linkId: string; ref: string }): { app: string } }\n\n/** Per hub: what the contacts have open now, `<chat> <reference>` to the version they said. */\nconst peers = new WeakMap<object, Map<string, string>>();\n\n/** The version of a served app the contact has open in a chat on this session, or undefined. */\nexport function peerVersion(hub: object, chat: string, ref: string): string | undefined {\n return peers.get(hub)?.get(`${chat} ${ref}`);\n}\n\nexport function reportAppFrames(hub: Pick<EventHub, \"onAppFrame\" | \"emitLive\">, node: AppIds, profileDir: string): () => void {\n const open = new Map<string, string>();\n peers.set(hub, open);\n /**\n * Per chat: chat app id to reference, of the apps served when they were learned there; and the list's stamp then\n * (undefined when an id could not be derived, so the next open tries again).\n */\n const known = new Map<string, { ids: Map<string, string>; stamp?: string }>();\n let count = 0;\n const learn = (chat: string) => {\n // The stamp is taken before the read: a write in between makes the next open learn again.\n let stamp: string | undefined = servedStamp(profileDir);\n const ids = new Map<string, string>();\n for (const { ref } of servedApps(profileDir)) {\n try { ids.set(node.appId({ linkId: chat, ref }).app, ref); } catch { stamp = undefined; /* not a paired chat: it has no app ids */ }\n }\n const learnt = { ids, stamp };\n known.set(chat, learnt);\n return learnt;\n };\n /**\n * An open learns the served list again only when it changed since (a stat, no read): an app served or unserved since\n * is taken or left from its next open, and a contact repeating opens (up to 50 a second for each of 16 apps), at one\n * version or alternating two, costs no read of the list nor derivation of ids, which do not depend on the version.\n */\n const current = (chat: string, frame: AppFrameEvent) => {\n const learnt = known.get(chat);\n if (!learnt) return learn(chat);\n if (!(\"o\" in frame) || frame.o !== \"open\") return learnt;\n return learnt.stamp === undefined || learnt.stamp !== servedStamp(profileDir) ? learn(chat) : learnt;\n };\n return hub.onAppFrame((chat: string, frame: AppFrameEvent) => {\n const learnt = current(chat, frame);\n const app = learnt.ids.get(frame.app);\n if (!app) return;\n // Frames are not stored, so nothing names one but its place in this run: the id is unique, and never derived again.\n // Nor are their events: live only, never in the journal, where a contact's app would push out the other chats'.\n const id = `${chat}:${app}:${Date.now()}-${++count}`;\n if (\"o\" in frame) { if (frame.o === \"open\") open.set(`${chat} ${app}`, frame.v); else open.delete(`${chat} ${app}`); }\n if (!(\"o\" in frame)) hub.emitLive(\"app.message\", `app.message:${id}`, { chat, app, data: frame.d });\n else if (frame.o === \"open\") hub.emitLive(\"app.opened\", `app.opened:${id}`, { chat, app, version: frame.v });\n else hub.emitLive(\"app.closed\", `app.closed:${id}`, { chat, app, ...(frame.offline && { offline: true }) });\n });\n}\n","import { APP_DATA_MAX_BYTES, APP_SEND_LIMIT, STATUS_CARD_LIMITS, appCardId, type AppCard, type AppSendError } from \"@ghostly/core\";\nimport { bool, chatOf, node, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { peerVersion } from \"./appEvents\";\nimport { servedApp, servedApps, type ServedApp } from \"./appServe\";\nimport { CliError } from \"./errors\";\nimport { isLive } from \"./views\";\n\n/*\n * A served app in a chat (WISP 1200 § A bot on the other side): `app open` says the app is open on this side and, when\n * the contact's app is not open there yet, sends the app's card, as a person's app does when they open one; `app send`\n * is one frame of the app's own protocol to the contact's app, once both opened it; `app close` ends it. What is open is the engine's, in memory: only a daemon holds it, and a restarted one opens again.\n */\n\n/** The chat and the served app a command names, on an engine that speaks apps/1. */\nfunction target(ctx: ApiContext, params: Params): { chat: string; live: boolean; app: ServedApp } {\n const app = servedApp(servedApps(ctx.runtime.paths.dir), str(params, \"ref\", true));\n if (ctx.mode !== \"daemon\") throw new CliError(\"unavailable\", \"An app is open only while a daemon runs: start one (ghostly daemon --detach) and open it there\");\n if (!ctx.runtime.apps) throw new CliError(\"unavailable\", \"This daemon started before an app was served, so it offers no apps/1 yet: ghostly daemon restart\");\n const link = chatOf(ctx, params);\n return { chat: link.id, live: isLive(link), app };\n}\n\n/** The engine's own words for a call it refused (a chat not paired yet, a group), as `refused`. */\nasync function engine<T>(run: () => T | Promise<T>): Promise<T> {\n try { return await run(); } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n}\n\nexport const APP_CHAT_METHODS: Record<string, Method> = {\n async \"app.open\"(ctx, params) {\n const { chat, live, app } = target(ctx, params);\n const peer = peerVersion(ctx.hub, chat, app.ref) ?? null;\n await engine(() => node(ctx).appOpen({ linkId: chat, ref: app.ref, version: app.version }));\n let card: string | null = null;\n // The card is how a person learns of the app and gets it (\"Install to play\"); one whose app is open has no use for it.\n if (!bool(params, \"noCard\") && peer === null) {\n // A manifest's version may be longer than a card takes: the card goes without it, as a person's app sends it.\n const version = app.version.length <= STATUS_CARD_LIMITS.appVersion ? { version: app.version } : {};\n const sent: AppCard = { kind: \"app\", id: appCardId(app.ref), ref: app.ref, digest: app.digest, sequence: app.sequence, title: app.title, ...version, ...(app.url !== undefined && { url: app.url }), opened: true };\n const result = await node(ctx).sendMessage({ linkId: chat, text: \"\", card: sent });\n if (result.error || !result.messageId) {\n // Not half open: with no card the contact would never know, so the open is taken back.\n await engine(() => node(ctx).appClose({ linkId: chat, ref: app.ref }));\n throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error ?? \"The app's card could not be sent\");\n }\n card = result.messageId;\n }\n return { chat, app: app.ref, version: app.version, card, peer, live };\n },\n\n async \"app.close\"(ctx, params) {\n const { chat, app } = target(ctx, params);\n await engine(() => node(ctx).appClose({ linkId: chat, ref: app.ref }));\n return { chat, app: app.ref, closed: true };\n },\n\n async \"app.send\"(ctx, params) {\n const { chat, app } = target(ctx, params);\n if (!(\"data\" in params) || params.data === undefined) throw new CliError(\"bad_request\", \"data is required: the app's message, any JSON value\");\n const { error } = await engine(() => node(ctx).appSend({ linkId: chat, ref: app.ref, data: params.data }));\n if (error) throw new CliError(NOT_SENT[error].code, NOT_SENT[error].message, { reason: error });\n return { chat, app: app.ref, sent: true };\n },\n};\n\n/** Why a frame did not go (WISP 1200 § In a chat), in `details.reason`. Nothing is kept to send later. */\nconst NOT_SENT: Record<AppSendError, { code: \"refused\" | \"bad_request\" | \"unavailable\"; message: string }> = {\n \"not-open\": { code: \"refused\", message: \"The app is not open in this chat on this side: app open it first\" },\n \"too-large\": { code: \"bad_request\", message: `The message is over ${APP_DATA_MAX_BYTES} bytes of JSON, the most an app's frame carries` },\n offline: { code: \"unavailable\", message: \"The chat is not live: an app's frames go on the live session only, and none is kept for later\" },\n \"peer-closed\": { code: \"unavailable\", message: \"The contact's app is not open in this chat (or their Ghostly runs no apps): wait for app.opened\" },\n \"too-fast\": { code: \"refused\", message: `More than ${APP_SEND_LIMIT} frames in a second, or the connection is still sending earlier ones: slow down and send it again` },\n};\n","/**\n * Names only a local network answers (RFC 6762, RFC 8375, ICANN's .internal, and the usual router and company ones).\n * A copy of packages/core/src/localNames.ts, as this module imports nothing; the same as Desktop's\n * apps/desktop/src/local_names.rs (src/test/chat/linkPreviewParse.test.ts pins all three).\n */\nexport const LOCAL_SUFFIXES = [\"localhost\", \"local\", \"internal\", \"lan\", \"home\", \"home.arpa\", \"localdomain\", \"intranet\", \"corp\"] as const;\n\n/**\n * A host that names this machine or the local network, as far as its spelling tells: a name under a local suffix\n * (`localhost`, `.local`, `.lan`, `.home`, `.corp`, …), a single label, private and reserved IP addresses. Previews\n * are never made for these, a page on the internet may not point its picture at one, and a contact's app may not open\n * one. (Desktop also checks the addresses a name resolves to.)\n * In a module of its own, importing nothing: the extension's background worker reads it too.\n */\nexport function isLocalHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/\\.+$/, \"\").replace(/^\\[|\\]$/g, \"\");\n if (!host.includes(\".\") && !host.includes(\":\")) return true;\n if (LOCAL_SUFFIXES.some(s => host === s || host.endsWith(`.${s}`))) return true;\n const v4 = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(host);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b < 32)\n || (a === 192 && b === 168) || (a === 100 && b >= 64 && b < 128) || (a === 198 && (b === 18 || b === 19)) || (a === 192 && b === 0);\n }\n // Any IPv6 literal but a global unicast one (2000::/3: a first group of four digits, as `2::` is `0002::`), none\n // that embeds an IPv4 address (dotted, 6to4 2002::/16, Teredo 2001::/32: `new URL()` writes them all in hex), and\n // no documentation one (2001:db8::/32).\n if (host.includes(\":\")) {\n return !/^[23][0-9a-f]{3}:/.test(host) || host.includes(\".\") || host.startsWith(\"2002:\") || /^2001:(0{0,4}|0{0,3}db8):/.test(host);\n }\n return false;\n}\n","import { generateMnemonic } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\nimport { parsePaymentAmount, type WalletNetwork } from \"@ghostly/core\";\nimport type { EngineState, NetworkWalletsView, PaymentView, WalletInstanceView, WalletOffer, WalletType } from \"@ghostly/browser/shared/types\";\nimport { bool, chatOf, inviteTaken, node, num, oneOf, ownChatOf, sentAt, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { paymentNetwork } from \"@ghostly/browser/engine/paymentAdapters/walletInstances\";\nimport { CASHU_MINT_SOURCE } from \"@ghostly/browser/engine/paymentAdapters/providers/cashuMint\";\nimport { normalizeMintUrl } from \"@ghostly/browser/engine/wallet\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport { ADDRESS_TYPES, CHAT_METHODS, PAY_METHODS, WALLET_TYPES } from \"./words\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { shellWord } from \"./shellWord\";\nimport { isLocalHost } from \"../../../apps/ui/src/lib/localHost\";\n\n/**\n * Wallets and payments (WISP 1100, phase 2): the app's wallet deck and a chat's payment sheet, as methods. Test\n * networks move nothing real. On Mainnet every spend passes `confirmedReal`, which the engine requires, only when the\n * call says `confirmReal: true` (the CLI's `--confirm-real`): no flag, no spend.\n */\n\nconst NETWORKS = [\"mainnet\", \"testnet\"] as const;\n\n/**\n * What the app has and a headless Ghostly cannot run yet, and why (WISP 1100 § Wallet SDKs on Node). New offers\n * them as unavailable; creating one is refused before the engine is asked.\n */\nexport const NODE_GAPS: Partial<Record<WalletType, string>> = {\n bark: \"Bark's SDK ships a browser build only: its WebAssembly needs a browser window. Use it from the app.\",\n};\n\n/** Sources the engine lists that live in a browser page (`window.webln`): a headless Ghostly never offers them. */\nconst BROWSER_SOURCES = new Set([\"webln\"]);\n\n/** The sources of an offer a headless Ghostly can connect. */\nconst nodeSources = (offer: WalletOffer | undefined) => offer?.providers?.filter((p) => !BROWSER_SOURCES.has(p.id));\n\n/**\n * What `wallet create` was given checked against the offer's own form, before the engine is asked: a source, a field\n * or a flag left out, or one the wallet does not take, is the person's value, said naming the flag. Before, the engine\n * refused it in the app's words (\"Enter connection uri\", \"Nothing was saved; try again\") as `engine`, or the flag was\n * dropped without a word.\n */\nfunction createChecked(type: WalletType, n: WalletNetwork, offer: WalletOffer | undefined, provider: string | undefined, values: Record<string, string>, params: Params): void {\n if (type !== \"lightning\" && type !== \"bitcoin\") {\n if (provider || Object.keys(values).length) throw new CliError(\"usage\", `--provider and --value name a lightning or bitcoin source: not with ${type}`);\n if (offer?.needs === \"invite\" && !str(params, \"invite\")?.trim()) throw new CliError(\"bad_request\", `${type} needs --invite <fed11…>`);\n if (offer?.needs === \"apiKey\" && !str(params, \"apiKey\")?.trim()) throw new CliError(\"bad_request\", `${type} on ${n} needs --api-key <key> (or api-key=… on --stdin)`);\n return;\n }\n // None offered on this network: the engine says why.\n const sources = nodeSources(offer);\n if (!sources?.length) return;\n if (!provider) throw new CliError(\"bad_request\", `${type} needs --provider: one of ${sources.map((p) => p.id).join(\", \")} (ghostly wallet list)`);\n const source = sources.find((p) => p.id === provider);\n if (!source) throw new CliError(\"bad_request\", `No ${type} source ${JSON.stringify(provider)} on ${n} (ghostly wallet list)`);\n const unknown = Object.keys(values).find((name) => !source.fields.some((f) => f.name === name));\n // Never the name itself: a secret given with no name= but with a base64 `=` (a macaroon, a rune) reads as one (`pairs`).\n if (unknown) throw new CliError(\"bad_request\", `one --value names no field of ${provider}: ${source.fields.length ? `its fields are ${source.fields.map((f) => f.name).join(\", \")}` : \"it has no fields\"}`);\n const missing = source.fields.find((f) => !f.optional && !f.defaults?.[n] && !values[f.name]?.trim());\n if (missing) throw new CliError(\"bad_request\", `${provider} needs --value ${missing.name}=<${missing.options?.map((o) => o.value).join(\"|\") ?? missing.placeholder ?? missing.label.toLowerCase()}>`);\n}\n\nconst network = (params: Params, fallback: WalletNetwork = \"testnet\") => oneOf(params, \"network\", NETWORKS, fallback);\n\n/** `confirmedReal` for the engine: only when the caller confirmed real money, and only then. */\nconst real = (params: Params): { confirmedReal?: true } => (bool(params, \"confirmReal\") ? { confirmedReal: true } : {});\n\nfunction netView(s: EngineState, n: WalletNetwork): NetworkWalletsView | undefined {\n return s.wallet.networks?.[n];\n}\n\n/** A Lightning card named by `card` on the network asked: one that is not there is not_found, before the engine is asked. */\nfunction lightningCard(ctx: ApiContext, params: Params): void {\n const n = network(params), card = str(params, \"card\", true);\n if (!netView(state(ctx), n)?.lightnings?.some((c) => c.card === card)) throw new CliError(\"not_found\", `No Lightning card ${JSON.stringify(card)} on ${n} (ghostly wallet list)`);\n}\n\n/**\n * The card a payment, a request or a wallet command names. \"\" (an unset variable in a script: `--card \"$CARD\"`) is a\n * usage error: taken as not given, it moved money through, or removed, the network's default card or the whole wallet.\n */\nfunction cardParam(params: Params): string | undefined {\n if (params.card === \"\") throw new CliError(\"usage\", \"--card needs a Lightning card id (ghostly wallet list)\");\n return str(params, \"card\");\n}\n\n/**\n * The Lightning card `card` names, checked before the engine is asked: given with another type of wallet it is a usage\n * error, and one not on the network is not_found. Before, the engine dropped it for every type but Lightning, so a card\n * that named nothing removed the whole wallet of that type and the answer echoed the card as removed.\n */\nfunction cardOf(ctx: ApiContext, params: Params, type: WalletType): string | undefined {\n const card = cardParam(params);\n if (card === undefined) return undefined;\n if (type !== \"lightning\") throw new CliError(\"usage\", `--card names a Lightning card: not with ${type}`);\n lightningCard(ctx, params);\n return card;\n}\n\n/**\n * The engine opens the federations joined before in the background as it starts. A daemon has long done so when a call\n * comes; a one-shot command waits for them (at most 30 s) before its balances are read or money moves through one.\n */\nasync function federationsOpen(ctx: ApiContext, ms = 30_000): Promise<void> {\n if (ctx.mode !== \"one-shot\") return;\n const until = Date.now() + ms;\n const connecting = () => NETWORKS.some((n) => (netView(state(ctx), n)?.fedimint?.federations ?? []).some((f) => f.status === \"connecting\"));\n while (connecting() && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 250));\n}\n\n/**\n * An Arkade, Bark, Spark or USDT balance, known only once the wallet is open and read it: until then the view holds 0\n * (USDT \"0\", also offline for good), which the app's total shows as \"?\" (walletTotals). `null` with `status` `locked` or\n * `reading`, never a 0 a script takes for the balance.\n */\nfunction readBalance<T extends number | string>(view: { locked: boolean; read?: true; balance: T } | undefined): { balance: T | null; status: string | null } {\n if (!view) return { balance: null, status: null };\n if (view.locked) return { balance: null, status: \"locked\" };\n return view.read ? { balance: view.balance, status: null } : { balance: null, status: \"reading\" };\n}\n\n/**\n * One wallet of the deck with its balance, in its own unit. Never a key, a phrase or a token. A balance not read yet\n * is `null`, with `status` saying why (`locked`, `reading`, `error`).\n */\nexport function walletJson(instance: WalletInstanceView, s: EngineState) {\n const view = netView(s, instance.network);\n let balance: number | string | null = null, unit = \"sat\", address: string | null = null, status: string | null = null, error: string | null = null;\n switch (instance.type) {\n case \"cashu\": balance = view?.balance ?? null; break;\n case \"lightning\": {\n const card = view?.lightnings?.find((c) => c.card === instance.card);\n // Through the mints, the card pays from and into the Cashu balance, which the app's card shows (walletCardData):\n // its own copy is read again only every 15 s, so after a payment it answered the balance from before it.\n balance = (card?.providerId === CASHU_MINT_SOURCE ? view?.balance : card?.balance) ?? null; status = card?.status ?? null; error = card?.error ?? null;\n break;\n }\n case \"arkade\": ({ balance, status } = readBalance(view?.ark)); address = view?.ark?.address ?? null; error = view?.ark?.error ?? null; break;\n case \"bark\": ({ balance, status } = readBalance(view?.bark)); error = view?.bark?.error ?? null; break;\n case \"spark\": ({ balance, status } = readBalance(view?.spark)); address = view?.spark?.address ?? null; error = view?.spark?.error ?? null; break;\n case \"bitcoin\": balance = view?.bitcoin?.balance ?? null; address = view?.bitcoin?.address ?? null; status = view?.bitcoin?.status ?? null; error = view?.bitcoin?.error ?? null; break;\n case \"fedimint\": {\n // Every federation read, or the balance is not known (the app's total says \"?\"): one that did not answer could hold the most.\n const federations = view?.fedimint?.federations ?? [];\n const known = federations.every((f) => f.read && f.status === \"ready\");\n balance = known ? view?.fedimint?.balance ?? null : null;\n status = known ? null : federations.some((f) => f.status === \"error\") ? \"error\" : \"reading\";\n error = view?.fedimint?.error ?? federations.find((f) => f.error)?.error ?? null;\n break;\n }\n case \"usdt\": ({ balance, status } = readBalance(view?.usdt)); unit = \"token-base\"; address = view?.usdt?.address ?? null; error = view?.usdt?.error ?? null; break;\n }\n return {\n id: instance.id, type: instance.type, network: instance.network,\n ...(instance.card ? { card: instance.card, name: instance.name ?? null, receive: !!instance.receive } : {}),\n balance, unit, address, status, error, config: instance.config,\n };\n}\n\n/** A token amount (USDT) is in base units: its `decimals` say how many make one. Sats carry none. */\nconst tokenDecimals = (p: PaymentView): { decimals?: number } => (p.target?.method === \"usdt\" ? { decimals: p.target.decimals ?? 6 } : {});\n\n/** USDT typed as the app's composer takes it (\"5\", \"0.25\") in base units: more decimals than the token has is refused. */\nfunction tokenUnits(text: string, decimals: number): number {\n try {\n const units = parsePaymentAmount(text.trim(), decimals);\n if (units > 0) return units;\n } catch (error) {\n throw new CliError(\"bad_request\", `amount: ${(error as Error).message}`);\n }\n throw new CliError(\"bad_request\", \"amount must be above 0\");\n}\n\nexport function paymentJson(p: PaymentView) {\n return {\n id: p.id, chat: p.linkId, kind: p.kind, direction: p.direction, amount: p.amount, unit: p.unit, ...tokenDecimals(p), memo: p.memo ?? null,\n state: p.state, error: p.error ?? null, network: paymentNetwork(p), method: p.target?.method ?? (p.federation || p.federations ? \"fedimint\" : p.invoice ? \"lightning\" : p.mint || p.mints ? \"cashu\" : null),\n createdAt: p.createdAt, ...(p.group ? { group: p.group } : {}), ...(p.closed ? { closed: true } : {}), ...(p.txid ? { txid: p.txid } : {}),\n };\n}\n\n/**\n * A Lightning invoice's network by its prefix (BOLT 11), for a hint only: test mints issue `lnbc` invoices too, so\n * the paying wallet's network is always named by the caller.\n */\nexport function invoiceNetwork(invoice: string): WalletNetwork | null {\n const lower = invoice.trim().toLowerCase().replace(/^lightning:/, \"\");\n if (!lower.startsWith(\"ln\")) return null;\n if (/^lnbcrt/.test(lower)) return \"testnet\";\n if (/^lnbc\\d|^lnbc1/.test(lower)) return \"mainnet\";\n return /^ln(tb|tbs|sb)/.test(lower) ? \"testnet\" : null;\n}\n\nconst isInvoice = (text: string) => /^(lightning:)?ln(bc|tb|tbs|sb|bcrt)[0-9a-z]+$/i.test(text.trim());\nconst isLnurl = (text: string) => /^(lightning:)?lnurl[0-9a-z]+$/i.test(text.trim()) || /^[a-z0-9._+-]+@[a-z0-9.-]+\\.[a-z]{2,}$/i.test(text.trim());\n\n/**\n * The engine refusing the mint URL the person typed (not a URL, or not https): their value, so `bad_request`, as\n * `service add` says; before, it was `engine` (exit 1), which a bot reads as the engine failing and may retry. Read by\n * its shape: the engine's `EngineError` carries `engineCode`.\n */\n/** A payment's memo: the contact reads it as a message's text, so the secret guard of `send` holds (docs/CLI.md § Safety). */\nfunction memoOf(params: Params, verb: string, field: \"memo\" | \"comment\" = \"memo\"): string | undefined {\n const memo = str(params, field);\n if (memo && !bool(params, \"force\")) {\n const secret = findSecret(memo);\n if (secret) throw new CliError(\"confirm\", `The ${field} looks like ${secretWords(secret)}; ${verb} with --force if you mean to`, { kind: secret.kind });\n }\n return memo || undefined;\n}\n\n/**\n * What `pay` reads of its own words, the target's shape among them: checked again before a one-shot opens the profile\n * (`refuseBeforeStart`), where a target that is no invoice, address or LNURL started every saved chat to be refused.\n */\nexport function payShape(params: Params): { comment?: string; text: string; card?: string } {\n // A Lightning address's comment reaches its owner as a memo reaches a contact (agents#1624).\n const comment = memoOf(params, \"pay\", \"comment\");\n const text = str(params, \"target\", true).trim();\n const card = cardParam(params);\n // The chat the invoice was found in: on Testnet its contact is told it was paid, as a chat card's Pay tells it. A test\n // mint says every invoice is paid, so one from `wallet receive` is credited only on its payer's word.\n if (params.chat !== undefined && !isInvoice(text)) throw new CliError(\"usage\", \"--chat names the chat an invoice came from: an address's or LNURL's invoice is its server's\");\n if (!isInvoice(text) && !isLnurl(text)) throw new CliError(\"bad_request\", \"Not a Lightning invoice, Lightning address or LNURL\");\n return { comment, text, card };\n}\n\n/** The token `wallet redeem` takes, refused as the engine refuses one Cashu's library cannot read (`refuseBeforeStart`). */\nexport async function tokenShape(params: Params): Promise<string> {\n const token = str(params, \"token\", true).trim();\n const { getTokenMetadata } = await import(\"@cashu/cashu-ts\");\n try { getTokenMetadata(token); } catch { throw new CliError(\"bad_request\", \"That is not a valid ecash token\"); }\n return token;\n}\n\n/** The mint URL `wallet add-mint` takes, refused in the engine's words when it is no URL or not https (`refuseBeforeStart`). */\nexport function mintUrlShape(params: Params): string {\n const url = str(params, \"url\", true);\n try { normalizeMintUrl(url); } catch (error) { throw badMintUrl(error) ? new CliError(\"bad_request\", (error as Error).message) : error; }\n return url;\n}\n\n/**\n * What `pay` says with `paid: false`: the payment is not known paid yet. The mint (or the card's source) holds it\n * pending, or its answer was lost; the engine keeps asking and never pays it twice. Before, the answer said `paid:\n * false` and nothing else, and no read showed the sats the Cashu wallet set aside for it. Said in the\n * words of the app's Cashu card (\"set aside\", `wallet.cashu.setAsideInfo`).\n */\nfunction notPaidYet(ctx: ApiContext, n: WalletNetwork, source: string, amount: number, feeReserve: number): string {\n const running = ctx.mode === \"one-shot\" ? \" while this profile runs (`ghostly daemon --detach`)\" : \"\";\n if (source !== CASHU_MINT_SOURCE) {\n return `Not paid yet: your Lightning source has not confirmed this payment (it is pending, or its answer was lost). It is asked again${running} and never paid twice: \\`ghostly wallet list\\` shows the card's balance once it settles.`;\n }\n const sats = `${amount + feeReserve} ${n === \"testnet\" ? \"test sats\" : \"sats\"}`;\n return `Not paid yet: the mint has not settled this payment (it is pending, or its answer was lost). ${sats} are set aside for it, out of the balance: they leave with the payment, or come back to the balance if the mint says it failed. It settles by itself: the wallet keeps asking the mint${running} and never pays it twice. \\`ghostly wallet history\\` lists it once paid, and \\`ghostly wallet list\\` shows the balance.`;\n}\n\nfunction badMintUrl(error: unknown): boolean {\n const code = error instanceof Error ? (error as { engineCode?: unknown }).engineCode : undefined;\n return code === \"invalidMintUrl\" || code === \"mintNotHttps\";\n}\n\n/** What the engine's faucet says with no test mint to ask. */\nconst NO_TEST_MINT = /^The faucet did not pay: This wallet has no test mint\\b/;\n\n/**\n * The engine's wallet refusals about what the person asked, by the words it writes (they carry no `engineCode`): a\n * wallet or card that is not there, a token or invoice that is not one, a wallet already made, no mint or source to do\n * it with. Before, each was `engine` (exit 1), which a bot reads as the engine failing and may retry. With no wallet of\n * the type at all, `wallet faucet`, `wallet receive` and `wallet address` say which to make first (`noWalletOf`).\n */\nconst WALLET_REFUSALS: [RegExp, ErrorCode][] = [\n [/^There is no .+ to remove$/, \"not_found\"],\n [/^That Lightning card is gone\\b/, \"not_found\"],\n [/^That is not a (valid ecash token|Lightning invoice)$/, \"bad_request\"],\n [/^You already have a .+ wallet$/, \"refused\"],\n [/^No mint could create an invoice: No mint configured$/, \"unavailable\"],\n [/^No Bitcoin source is set up$/, \"unavailable\"],\n [NO_TEST_MINT, \"unavailable\"],\n [/^Ghostly cannot ask this wallet's faucet by itself\\b/, \"unavailable\"],\n // What a payment's state refuses: a payment the contact took (or a request) has nothing to take back, a request or an\n // invoice already paid is not paid again.\n [/^Nothing to (reclaim|take back)$/, \"refused\"],\n [/^This request is no longer open$/, \"refused\"],\n [/^This invoice is already paid$/, \"refused\"],\n];\n\nconst WALLET_NAMES: Record<WalletType, string> = { cashu: \"Cashu\", lightning: \"Lightning\", arkade: \"Arkade\", bark: \"Bark\", spark: \"Spark\", bitcoin: \"Bitcoin\", fedimint: \"Fedimint\", usdt: \"USDT\" };\n\n/**\n * A request refused for want of a wallet of that type and network at all: `chat pay`, `chat request`, `wallet receive`\n * and the Cashu faucet with no Cashu wallet, an address with no wallet of its type. The engine says the wallet is short\n * of sats, that it has no mint or source, and names nothing to do. `refused` with the command that makes one, as a\n * contact with no wallet is told; `details.reason` `no_wallet`. With a wallet, the engine's own words.\n */\nfunction noWalletOf(ctx: ApiContext, n: WalletNetwork, error: unknown, type: WalletType = \"cashu\"): unknown {\n if ((state(ctx).wallet.wallets ?? []).some((w) => w.type === type && w.network === n)) return error;\n const name = n === \"mainnet\" ? \"Mainnet\" : \"Testnet\";\n return new CliError(\"refused\", `You have no ${name} ${WALLET_NAMES[type]} wallet: ghostly wallet create ${type}${n === \"mainnet\" ? \" --network mainnet\" : \"\"}`, { reason: \"no_wallet\" });\n}\nconst engineCode = (error: unknown) => error instanceof Error ? (error as { engineCode?: unknown }).engineCode : undefined;\n/** What the engine says to a Cashu request it has no mint for: no mint for the invoice, or none to name for ecash. */\nconst NO_MINT = /^(No mint could create an invoice: No mint configured|You have no (Mainnet|Testnet) Cashu wallet: create one in Wallet → New)$/;\nfunction walletRefusal(error: unknown): unknown {\n if (!(error instanceof Error) || error instanceof CliError) return error;\n // A mint asked for a swap that has not answered (the engine's `SwapUnsettledError`, by its name, or a chat payment's\n // error that carries it as `unsettled`): nothing is known to have failed, try again later, as a mint that cannot be\n // reached at all is `unavailable`.\n if (error.name === \"SwapUnsettledError\" || (error as { unsettled?: unknown }).unsettled === true) return new CliError(\"unavailable\", error.message);\n const code = WALLET_REFUSALS.find(([pattern]) => pattern.test(error.message))?.[1];\n return code ? new CliError(code, error.message) : error;\n}\n\n/**\n * `wallet redeem` of ecash from a mint that is not one of the wallet's: the engine names the mint's host only and no\n * way on. Its words, then the command that adds the whole mint URL (the token's), for one who trusts that mint: a mint\n * holds the sats, so it is offered, never done. Shell-quoted as any hint's word; a URL no quoting survives is not printed.\n */\nfunction mintNotAdded(error: unknown): CliError | undefined {\n if (!(error instanceof Error) || !/^Ecash from \\S+ is not accepted$/.test(error.message)) return undefined;\n const mint = (error as { mint?: unknown }).mint;\n if (typeof mint !== \"string\") return undefined;\n return new CliError(\"engine\", `${error.message}: its mint is not one of yours (if you trust it to hold your sats: ghostly wallet add-mint ${shellWord(mint, \"<the token's mint URL>\")})`);\n}\n\n/**\n * The mints `mintNotAdded` offers no `add-mint` for. A token is what a contact sends, and the way out reads as the\n * app's advice: never a command `wallet add-mint` refuses (plain http off this machine), nor one that makes a server\n * on this machine or the local network a mint the wallet then talks to. One who runs such a mint types its URL.\n */\nfunction mintNotOffered(error: unknown): CliError | undefined {\n const mint = error instanceof Error && /^Ecash from \\S+ is not accepted$/.test(error.message) ? (error as { mint?: unknown }).mint : undefined;\n if (typeof mint !== \"string\") return undefined;\n const words = (error as Error).message;\n try { normalizeMintUrl(mint); } catch (refusal) {\n return new CliError(\"engine\", `${words}: its mint is not one of yours, and not one a wallet can add (${(refusal as Error).message})`);\n }\n if (!isLocalHost(new URL(mint).hostname)) return undefined;\n return new CliError(\"engine\", `${words}: its mint is not one of yours, and it is on this machine or a local network (add a mint there only if you run it yourself)`);\n}\n\nconst WALLETS: Record<string, Method> = {\n async \"wallet.list\"(ctx, params) {\n await federationsOpen(ctx);\n const s = state(ctx);\n const only = params.network === undefined ? null : network(params);\n const wallets = (s.wallet.wallets ?? []).filter((w) => !only || w.network === only).map((w) => walletJson(w, s));\n const offers = (s.wallet.offers ?? []).filter((o) => !only || o.network === only).map((o) => {\n const gap = NODE_GAPS[o.type];\n return { type: o.type, network: o.network, available: o.available && !gap, reason: gap ?? o.reason ?? null, exists: !!o.exists, several: !!o.several, needs: o.needs ?? null,\n ...(o.providers ? { providers: nodeSources(o)!.map((p) => ({ id: p.id, label: p.label, fields: p.fields.map((f) => ({ name: f.name, label: f.label, kind: f.kind, optional: !!f.optional })) })) } : {}) };\n });\n return { wallets, offers };\n },\n\n async \"wallet.create\"(ctx, params) {\n const type = oneOf(params, \"type\", WALLET_TYPES, \"cashu\");\n const n = network(params);\n const gap = NODE_GAPS[type];\n if (gap) throw new CliError(\"unavailable\", gap);\n // A Fedimint Lightning card needs its federation open.\n await federationsOpen(ctx);\n const values: Record<string, string> = {};\n const raw = params.values ?? {};\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw) || Object.values(raw).some((v) => typeof v !== \"string\")) throw new CliError(\"bad_request\", \"values must be an object of strings\");\n Object.assign(values, raw);\n // On-chain is BDK unless another source is named.\n const provider = str(params, \"provider\") ?? (type === \"bitcoin\" ? \"bdk\" : undefined);\n // BDK asks for a recovery phrase and makes a new wallet from one the app draws: here, one drawn now.\n if (type === \"bitcoin\" && provider === \"bdk\" && !values.mnemonic) values.mnemonic = generateMnemonic(wordlist, 128);\n createChecked(type, n, state(ctx).wallet.offers?.find((o) => o.type === type && o.network === n), provider, values, params);\n const made = await node(ctx).walletCreate({ type, network: n, ...(provider ? { providerId: provider } : {}), ...(Object.keys(values).length ? { values } : {}), ...(str(params, \"invite\") ? { invite: str(params, \"invite\") } : {}), ...(str(params, \"apiKey\") ? { apiKey: str(params, \"apiKey\") } : {}) });\n return walletJson(made, state(ctx));\n },\n\n async \"wallet.remove\"(ctx, params) {\n const type = oneOf(params, \"type\", WALLET_TYPES, \"cashu\");\n const n = network(params);\n const card = cardOf(ctx, params, type);\n try {\n await node(ctx).walletRemove({ type, network: n, ...(card ? { card } : {}), ...(bool(params, \"acceptLoss\") ? { acceptLoss: true } : {}) });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n // The engine keeps a wallet that holds money here, or that someone still pays into (#303): only the person decides.\n if (!bool(params, \"acceptLoss\") && /hold|still|awaiting|lose|backup/i.test(message)) throw new CliError(\"confirm\", `${message} (pass acceptLoss, --accept-loss, only if that is intended)`);\n throw error;\n }\n return { removed: { type, network: n, card: card ?? null } };\n },\n\n async \"wallet.faucet\"(ctx, params) {\n const type = oneOf(params, \"type\", WALLET_TYPES, \"cashu\");\n if (network(params) !== \"testnet\") throw new CliError(\"refused\", \"Test coins are for Testnet wallets only\");\n const card = cardOf(ctx, params, type);\n // No test mint: the faucet of Cashu and of a Lightning card through the mints, which a Cashu wallet brings.\n return node(ctx).walletTestCoins({ type, network: \"testnet\", ...(card ? { card } : {}) })\n .catch((error: unknown) => { throw error instanceof Error && NO_TEST_MINT.test(error.message) ? noWalletOf(ctx, \"testnet\", error) : error; });\n },\n\n async \"wallet.history\"(ctx, params) {\n const n = network(params);\n const limit = num(params, \"limit\", 50, { min: 1, max: 10_000, whole: true });\n await federationsOpen(ctx);\n // Read from the store: the wallet view keeps only the newest 100.\n return { network: n, history: await node(ctx).walletHistory({ network: n, limit }) };\n },\n\n async \"wallet.receive\"(ctx, params) {\n const amount = num(params, \"amount\", 0, { min: 1 });\n if (!amount) throw new CliError(\"bad_request\", \"amount is required\");\n const n = network(params);\n await federationsOpen(ctx);\n const card = cardOf(ctx, params, \"lightning\");\n const invoice = await node(ctx).walletReceiveLightning({ amount, network: n, ...(card ? { card } : {}) })\n .catch((error: unknown) => { throw error instanceof Error && NO_MINT.test(error.message) ? noWalletOf(ctx, n, error) : error; });\n return { network: n, amount, invoice: invoice.invoice, expiresAt: invoice.expiresAt, paymentHash: invoice.paymentHash ?? null, source: invoice.source };\n },\n\n async \"wallet.address\"(ctx, params) {\n const type = oneOf(params, \"type\", ADDRESS_TYPES, \"bitcoin\");\n const n = network(params);\n if (type === \"bitcoin\") {\n const address = await node(ctx).bitcoinReceiveAddress({ network: n })\n .catch((error: unknown) => { throw error instanceof Error && /^No Bitcoin source is set up$/.test(error.message) ? noWalletOf(ctx, n, error, \"bitcoin\") : error; });\n return { type, network: n, address };\n }\n const view = netView(state(ctx), n);\n const address = type === \"arkade\" ? view?.ark?.address : type === \"spark\" ? view?.spark?.address : view?.usdt?.address;\n if (!address) throw noWalletOf(ctx, n, new CliError(\"unavailable\", `No ${type} wallet with an address on ${n}`), type);\n return { type, network: n, address };\n },\n\n async \"wallet.redeem\"(ctx, params) {\n return node(ctx).walletReceiveToken({ token: await tokenShape(params) }).catch((error: unknown) => { throw mintNotOffered(error) ?? mintNotAdded(error) ?? error; });\n },\n\n async \"wallet.mint.add\"(ctx, params) {\n return node(ctx).walletAddMint({ url: mintUrlShape(params), ...(bool(params, \"primary\") ? { primary: true } : {}) }).catch((error: unknown) => {\n throw badMintUrl(error) ? new CliError(\"bad_request\", (error as Error).message) : error;\n });\n },\n\n async \"lightning.default\"(ctx, params) {\n lightningCard(ctx, params);\n await node(ctx).lightningSetReceive({ network: network(params), card: str(params, \"card\", true) });\n return { network: network(params), receive: str(params, \"card\", true) };\n },\n\n async \"lightning.rename\"(ctx, params) {\n lightningCard(ctx, params);\n await node(ctx).lightningRename({ network: network(params), card: str(params, \"card\", true), name: str(params, \"name\", true) });\n return { network: network(params), card: str(params, \"card\", true), name: str(params, \"name\", true) };\n },\n\n /** An invoice, a Lightning address or an LNURL, from the network's Lightning (a card of it, or its default). */\n async \"pay\"(ctx, params) {\n const { comment, text, card } = payShape(params);\n let invoice = text.replace(/^lightning:/i, \"\");\n let note: string | undefined;\n // Its contact is told it was paid: a contact's own name or a prefix of its id never names the chat.\n const chat = params.chat === undefined ? undefined : ownChatOf(ctx, params);\n if (chat) inviteTaken(chat);\n // Which wallet pays is named, never guessed from the invoice: test mints issue `lnbc` invoices too, and a guess\n // must never be what makes real money move. Testnet unless `network` says mainnet.\n const n = network(params);\n if (!isInvoice(text)) {\n // A Lightning address or an LNURL (`payShape`).\n const amount = num(params, \"amount\", 0, { min: 1 });\n if (!amount) throw new CliError(\"bad_request\", \"amount is required to pay a Lightning address or LNURL\");\n // Asked before the address's server hears of the payment (and its comment).\n if (n === \"mainnet\" && !bool(params, \"confirmReal\")) throw new CliError(\"confirm\", \"This pays real money (Mainnet): pass --confirm-real to confirm this payment\");\n const view = await node(ctx).lnurlResolve({ text, network: n });\n if (amount < view.minSat || amount > view.maxSat) throw new CliError(\"refused\", `${view.domain} takes from ${view.minSat} to ${view.maxSat} sats`);\n const got = await node(ctx).lnurlInvoice({ id: view.id, amount, ...(comment ? { comment } : {}), network: n });\n invoice = got.invoice; note = got.note;\n }\n if (n === \"mainnet\" && !bool(params, \"confirmReal\")) throw new CliError(\"confirm\", \"This pays real money (Mainnet): pass --confirm-real to confirm this payment\");\n await federationsOpen(ctx);\n const quote =await node(ctx).walletQuoteInvoice({ invoice, network: n, ...(card ? { card } : {}) });\n // With an invoice, --amount is what the payer expects it to ask: the invoice's writer never decides past it.\n const expected = isInvoice(text) ? num(params, \"amount\", 0, { min: 1 }) : 0;\n if (expected && quote.amount !== expected) throw new CliError(\"refused\", `The invoice asks ${quote.amount} sats, not the ${expected} given with --amount`);\n const maxFee = params.maxFee === undefined ? null : num(params, \"maxFee\", 0);\n if (maxFee !== null && quote.feeReserve > maxFee) throw new CliError(\"refused\", `The fee may reach ${quote.feeReserve} sats, more than the ${maxFee} allowed`);\n const paid = await node(ctx).walletPayQuote({ quote: quote.quote, mint: quote.mint, ...(note ? { note } : {}), ...real(params), ...(chat ? { linkId: chat.id, invoice } : {}) });\n const source = (quote as { source?: string }).source ?? quote.mint;\n return { network: n, amount: quote.amount, feeReserve: quote.feeReserve, source, paid: paid.paid, ...(!paid.paid && { note: notPaidYet(ctx, n, source, quote.amount, quote.feeReserve) }) };\n },\n\n /** Ecash to a contact in a chat (the payment sheet's Pay). */\n async \"chat.pay\"(ctx, params) {\n const memo = memoOf(params, \"pay\");\n // Money moves: a contact's own name or a prefix of its id never names the chat.\n const link = ownChatOf(ctx, params);\n inviteTaken(link);\n const amount = num(params, \"amount\", 0, { min: 1 });\n if (!amount) throw new CliError(\"bad_request\", \"amount is required\");\n const n = network(params);\n if (n === \"mainnet\" && !bool(params, \"confirmReal\")) throw new CliError(\"confirm\", \"This pays real money (Mainnet): pass --confirm-real to confirm this payment\");\n await federationsOpen(ctx);\n const { paymentId } = await node(ctx).sendPayment({ linkId: link.id, amount, timestamp: sentAt(), network: n, ...(memo ? { memo } : {}), ...real(params) })\n .catch((error: unknown) => { throw engineCode(error) === \"notEnoughSats\" ? noWalletOf(ctx, n, error) : error; });\n return { chat: link.id, paymentId };\n },\n\n /**\n * A request in a chat (the payment sheet's Request): the contact's app pays it. A USDT amount given as text (\"5\",\n * \"0.25\") is USDT, turned into base units with the wallet's decimals as the app's composer does; a number is base units.\n * The answer says the amount asked: USDT's carries the engine's tag of a few base units, and its decimals.\n */\n async \"chat.request\"(ctx, params) {\n const memo = memoOf(params, \"request\");\n const card = cardParam(params);\n const link = chatOf(ctx, params);\n const method = params.method === undefined ? undefined : oneOf(params, \"method\", PAY_METHODS, \"cashu\");\n const n = network(params);\n const amount = method === \"usdt\" && typeof params.amount === \"string\" ? tokenUnits(params.amount, netView(state(ctx), n)?.usdt?.decimals ?? 6) : num(params, \"amount\", 0, { min: 1 });\n if (!amount) throw new CliError(\"bad_request\", \"amount is required\");\n const rail = params.rail === undefined ? undefined : oneOf(params, \"rail\", [\"cashu\", \"lightning\"] as const, \"cashu\");\n await federationsOpen(ctx);\n const { paymentId } = await node(ctx).requestPayment({\n linkId: link.id, amount, timestamp: sentAt(), network: n,\n ...(memo ? { memo } : {}), ...(method ? { method } : {}), ...(rail ? { rail } : {}), ...(card ? { card } : {}),\n }).catch((error: unknown) => { throw (!method || method === \"cashu\") && error instanceof Error && NO_MINT.test(error.message) ? noWalletOf(ctx, n, error) : error; });\n const asked = state(ctx).payments[paymentId];\n return { chat: link.id, paymentId, ...(asked ? { amount: asked.amount, unit: asked.unit, ...tokenDecimals(asked) } : {}) };\n },\n\n /** Pays a request the contact made in a chat. */\n async \"chat.payRequest\"(ctx, params) {\n // Money moves: a contact's own name or a prefix of its id never names the chat.\n const s = state(ctx);\n const link = ownChatOf(ctx, params, s);\n const paymentId = str(params, \"payment\", true);\n const card = cardParam(params);\n const request = s.payments[paymentId];\n // Said as `payment check` says it: the id quoted, where this chat's payments are listed, and a payment of this chat\n // that is no request named as what it is (it read \"No request\", as if nothing had that id).\n const listed = `(ghostly payment list --chat ${link.id})`;\n if (request?.linkId === link.id && request.kind !== \"request\") {\n throw new CliError(\"not_found\", `${JSON.stringify(paymentId)} is ${request.direction === \"out\" ? \"a payment you sent\" : \"a payment you received\"}, not a request: chat pay-request pays a request the contact made of you ${listed}`);\n }\n if (!request || request.linkId !== link.id) throw new CliError(\"not_found\", `No request ${JSON.stringify(paymentId)} in this chat ${listed}`);\n // One I made is the contact's to pay: the engine knew it only as \"Unknown payment request\" (engine, exit 1).\n if (request.direction !== \"in\") throw new CliError(\"bad_request\", `${JSON.stringify(paymentId)} is your own request: the contact pays it`);\n // The request says which network it is paid on: real money or test coins, never the choice of the payer.\n const n = paymentNetwork(request);\n if (n === \"mainnet\" && !bool(params, \"confirmReal\")) throw new CliError(\"confirm\", \"This request is for real money (Mainnet): pass --confirm-real to confirm this payment\", { network: n });\n const via = params.via === undefined ? undefined : oneOf(params, \"via\", [\"lightning\"] as const, \"lightning\");\n await federationsOpen(ctx);\n await node(ctx).payRequest({ linkId: link.id, paymentId, network: n, ...(via ? { via } : {}), ...(params.maxFee !== undefined ? { maxFee: num(params, \"maxFee\", 0) } : {}), ...(card ? { card } : {}), ...real(params) });\n return paymentJson(state(ctx).payments[paymentId] ?? request);\n },\n\n /** Which ways of paying this chat takes, per network (the chat's Accept switches). */\n async \"chat.accept\"(ctx, params) {\n const link = chatOf(ctx, params);\n // No method: what it takes now, with nothing changed.\n if (params.method === undefined) {\n if (params.on !== undefined || params.networks !== undefined) throw new CliError(\"bad_request\", \"on and networks change one method: name it\");\n return { chat: link.id, methods: link.paymentMethods ?? null, networks: link.paymentNetworks ?? null };\n }\n const method = oneOf(params, \"method\", CHAT_METHODS, \"cashu\");\n // On unless `on` says otherwise, as `chat accept <chat> <method>` does; an `on` that is no boolean is refused.\n const on = params.on === undefined || bool(params, \"on\");\n const nets = params.networks === undefined ? undefined : (() => {\n const value = params.networks;\n if (!Array.isArray(value) || !value.every((v) => v === \"mainnet\" || v === \"testnet\")) throw new CliError(\"bad_request\", \"networks must list mainnet and/or testnet\");\n // An empty list names no network: the method would stay on while it is taken nowhere.\n if (value.length === 0) throw new CliError(\"bad_request\", \"networks must list mainnet and/or testnet: to stop taking it, --off\");\n return value as WalletNetwork[];\n })();\n await node(ctx).setChatPaymentMethods({ linkId: link.id, methods: { [method]: on }, ...(nets ? { networks: { [method]: nets } } : {}) });\n const now = state(ctx).links.find((l) => l.id === link.id);\n return { chat: link.id, methods: now?.paymentMethods ?? null, networks: now?.paymentNetworks ?? null };\n },\n\n async \"payment.list\"(ctx, params) {\n const s = state(ctx);\n const chat = params.chat === undefined ? null : chatOf(ctx, params, s).id;\n const payments = Object.values(s.payments).filter((p) => !chat || p.linkId === chat).sort((a, b) => b.createdAt - a.createdAt).map(paymentJson);\n return { payments };\n },\n\n async \"payment.check\"(ctx, params) {\n const s = state(ctx);\n const link = chatOf(ctx, params, s);\n const p = s.payments[str(params, \"payment\", true)];\n if (p?.linkId !== link.id) throw new CliError(\"not_found\", `No payment ${JSON.stringify(str(params, \"payment\", true))} in this chat (ghostly payment list --chat ${link.id})`);\n // The contact's app is asked to look for a request it made: one of mine, or a payment, has nothing to look for.\n if (p.kind !== \"request\" || p.direction !== \"in\") throw new CliError(\"bad_request\", `${JSON.stringify(p.id)} is ${p.kind === \"request\" ? \"your own request\" : p.direction === \"out\" ? \"a payment you sent\" : \"a payment you received\"}: payment check is for a request the contact made of you`);\n await node(ctx).checkPayment({ linkId: link.id, paymentId: str(params, \"payment\", true) });\n return { chat: link.id, paymentId: str(params, \"payment\", true) };\n },\n\n async \"payment.reclaim\"(ctx, params) {\n if (!state(ctx).payments[str(params, \"payment\", true)]) throw new CliError(\"not_found\", `No payment ${JSON.stringify(str(params, \"payment\", true))} (ghostly payment list)`);\n await node(ctx).reclaimPayment({ paymentId: str(params, \"payment\", true) });\n const p = state(ctx).payments[str(params, \"payment\", true)];\n return p ? paymentJson(p) : { paymentId: str(params, \"payment\", true) };\n },\n};\n\nexport const WALLET_METHODS: Record<string, Method> = Object.fromEntries(Object.entries(WALLETS).map(([name, method]) => [name,\n (ctx: ApiContext, params: Params) => method(ctx, params).catch((error: unknown) => { throw walletRefusal(error); })]));\n\nexport type { ApiContext };\n","import { AWAITING_PEER_MS, DHT_PACKET_BUDGET, decodeCommunityLink, decodeGroupEntryLink, inviteLink, LIMITS, MENTION_EVERYONE, normalizeRelayUrl, ownInviteRefusal, relayUrlProblem, replySnippet, sanitizeTypingStatus, TYPING_KINDS, TYPING_STATUS_MAX, type GroupMention, type TypingKind } from \"@ghostly/core\";\nimport type { EngineState, GroupView, LinkView, Settings, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { iceServerProblem, iceServerSetting } from \"@ghostly/browser/shared/ice\";\nimport { DEFAULT_HYPERDHT_RELAY } from \"@ghostly/browser/shared/hyperdhtRelay\";\nimport { groupPayLineId, groupPayNoteId } from \"@ghostly/browser/shared/groupPayNotes\";\nimport { DEFAULT_IROH_RELAYS } from \"@ghostly/browser/platform/irohWeb\";\nimport { FORWARD_MESSAGES, FORWARD_TARGETS } from \"@ghostly/browser/engine/forwards\";\nimport { findSecret, guardText, secretWords } from \"./secretGuard\";\nimport { DESTRUCTIVE_CALLS, ENGINE_METHODS, ENGINE_PARAMS, ENGINE_READS, READ_PARAMS, engineParamsProblem } from \"./engineMethods\";\nimport { asCliError, CliError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport {\n bool, chatOf, chatOrGroup, dhtOnly, findChat, findChatOrGroup, findGroup, groupById, groupCalled, groupNameOf, groupOf, groupPrefixed, inviteTaken, keptForJoin, list, messageOf, noMessage, nobodyJoined, node, notInYet, notInYetError, num, oneOf, oneShotWaits, settingsOf, shownName, sinceSeq, somebodyJoined, state, str, transportOffered, waitForState,\n type ApiContext, type CallScope, type Method, type Params, type RefPlace,\n} from \"./apiKit\";\nimport { FILE_METHODS } from \"./files\";\nimport { checkShownName } from \"./profiles\";\nimport { ended, foldsAnyway, goesOn, nobodyElseIn, outOf, purgeMessage, waitForConfirmed, waitForEdit, waitForGroupFrame, waitForMessage, waitForRemoval } from \"./waits\";\nimport { STATUS_CARD_METHODS, secretIn } from \"./statusCards\";\nimport { BUTTON_METHODS, buttonsCard, pressable } from \"./buttons\";\nimport { forgetHold, HOLD_MAX_MINUTES, holdChat, holdEnds, holdOf, releaseHold } from \"./holds\";\nimport { endTyping, keepOneShot, keepTyping, sayTyping } from \"./typing\";\nimport { GROUP_ADMIN_METHODS, noMember, withUrl } from \"./groupAdmin\";\nimport { withStoredIds } from \"./turnRefs\";\nimport { IDENTITY_METHODS } from \"./identities\";\nimport { X401_METHODS } from \"./x401\";\nimport { closeServicesOf, SERVICE_METHODS, serviceShape } from \"./services\";\nimport { BACKUP_METHODS } from \"./backup\";\nimport { CALL_METHODS } from \"./calls/api\";\nimport { APP_SERVE_METHODS } from \"./appServe\";\nimport { APP_CHAT_METHODS } from \"./appChat\";\nimport { mintUrlShape, payShape, tokenShape, WALLET_METHODS } from \"./wallets\";\nimport { checkOwnStatus, statusJson } from \"./ownStatus\";\nimport { TRANSPORT_NAMES } from \"./words\";\nimport { chatState, dhtOnlyNote, heldWords } from \"./waitNotice\";\nimport { chatDetailsJson, chatJson, chatMessageJson, groupJson, groupMessageJson, groupPayTwins, isLive, messageJson, type MessageJson } from \"./views\";\n\n/**\n * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the\n * engine is asked, with a code that says it never goes as it is, not \"unavailable\", which reads as \"try later\".\n */\nfunction checkTextSize(text: string): void {\n const bytes = new TextEncoder().encode(text.trim()).length;\n if (bytes > LIMITS.maxChatMessageBytes) throw new CliError(\"bad_request\", `Message exceeds ${LIMITS.maxChatMessageBytes} UTF-8 bytes (${bytes}): shorten it, or send it as a file`, { bytes, max: LIMITS.maxChatMessageBytes });\n}\n\n// ---------- settings ----------\n\n/**\n * The engine's state as `engine getState` prints it without `--show-secret`: the settings' credentials, a group's\n * entry link and the link of another group kept under its id (anyone who reads one can join), a pending chat's\n * invite code (whoever reads it can take the chat) and this side's wake-up tokens are `<hidden>`.\n */\nexport function hideStateSecrets<T extends {\n settings: Settings;\n groups?: { entryLink?: string; others?: unknown[]; wakeTokens?: string[] }[];\n links?: { inviteCode?: string; wakeToken?: string }[];\n}>(state: T) {\n const hideOther = (o: unknown) => (o && typeof o === \"object\" && \"link\" in o ? { ...o, link: \"<hidden>\" } : o);\n return {\n ...state,\n settings: redactSettings(state.settings),\n ...(state.groups ? { groups: state.groups.map((g) => ({ ...g,\n ...(g.entryLink ? { entryLink: \"<hidden>\" } : {}),\n ...(g.others ? { others: g.others.map(hideOther) } : {}),\n ...(g.wakeTokens ? { wakeTokens: g.wakeTokens.map(() => \"<hidden>\") } : {}) })) } : {}),\n ...(state.links ? { links: state.links.map((l) => ({ ...l,\n ...(l.inviteCode ? { inviteCode: \"<hidden>\" } : {}),\n ...(l.wakeToken ? { wakeToken: \"<hidden>\" } : {}) })) } : {}),\n };\n}\n\n/** Settings as a bot may read them: storage credentials and other secrets masked unless asked for. */\nexport function redactSettings(settings: Settings, showSecret = false): Record<string, unknown> {\n if (showSecret) return settings as unknown as Record<string, unknown>;\n const mask = (value: unknown, key = \"\"): unknown => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, mask(v, k)]));\n if (Array.isArray(value)) return value.map((item) => mask(item, key));\n if (typeof value === \"string\" && (/secret|password|token|credential|privatekey|nsec|bunker/i.test(key) || key === \"auth\" || key === \"space\")) return \"<hidden>\";\n return value;\n };\n // The push subscription (wake-up push) is a capability: who holds it can wake this profile's web app.\n const { avatar, wake, ...rest } = settings;\n return { ...(mask(rest) as Record<string, unknown>), ...(avatar ? { avatar: \"<set>\" } : {}), ...(wake ? { wake: \"<set>\" } : {}) };\n}\n\n/** Settings a command may change; the rest are the app's to manage. */\nconst SETTABLE_KINDS = {\n relays: \"strings\", irohRelays: \"strings\", hyperdhtRelay: \"string\",\n iceServers: \"ice\", publicProfiles: \"boolean\", online: \"boolean\", shareProfile: \"boolean\", sendTyping: \"boolean\", nick: \"string\",\n autoDownloads: \"boolean\", serveFiles: \"boolean\", daemonPresence: \"boolean\",\n} as const satisfies Partial<Record<keyof Settings, \"strings\" | \"string\" | \"boolean\" | \"ice\">>;\nexport const SETTABLE: Record<string, \"strings\" | \"string\" | \"boolean\" | \"ice\"> = SETTABLE_KINDS;\n\ntype Settable = keyof typeof SETTABLE_KINDS;\n/**\n * What a setting of the table reads as while the engine keeps none (types.ts `Settings`): a switch that is on and the\n * default relays are kept as absent (node.ts `updateSettings` deletes `sendTyping: true`, an empty `irohRelays`...).\n * Every key of the table the engine may leave out needs one here, or tsc fails.\n */\nconst SETTING_DEFAULTS: { [K in Settable as undefined extends Settings[K] ? K : never]-?: () => NonNullable<Settings[K]> } = {\n irohRelays: () => [...DEFAULT_IROH_RELAYS], hyperdhtRelay: () => DEFAULT_HYPERDHT_RELAY,\n publicProfiles: () => true, shareProfile: () => true, sendTyping: () => true, autoDownloads: () => true, serveFiles: () => true,\n daemonPresence: () => false,\n};\n\n/**\n * The settings as `settings get` and `settings set` answer them: each key `settings set` takes, with its value in\n * effect. Before, a switch that is on (absent as kept) was never shown, and a fresh profile showed 4 of the 11 keys.\n */\nexport function settingsInEffect(settings: Settings): Settings {\n const filled: Record<string, unknown> = { ...settings };\n for (const key of Object.keys(SETTABLE_KINDS) as Settable[]) {\n if (filled[key] === undefined && Object.hasOwn(SETTING_DEFAULTS, key)) filled[key] = SETTING_DEFAULTS[key as keyof typeof SETTING_DEFAULTS]();\n }\n return filled as unknown as Settings;\n}\n\n/**\n * A relay address the engine refuses (node.ts `updateSettings`, irohWeb.ts, hyperdhtRelay.ts): the person's value, so\n * `bad_request` named by its key, in a terminal's words (\"give\", not the app's \"Enter\"). Before, `engine` (exit 1). A\n * wrong scheme (\"Use an https:// relay address\") too.\n */\nfunction relayRefused(error: unknown, patch: Record<string, unknown>): unknown {\n if (!(error instanceof Error) || !/^(?:Enter (?:at least one|a) relay address|Not a relay address|Use an? \\S+ relay address)\\b/.test(error.message)) return error;\n const keys = [\"relays\", \"irohRelays\", \"hyperdhtRelay\"].filter((key) => Object.hasOwn(patch, key));\n return new CliError(\"bad_request\", `${keys.join(\", \") || \"relays\"}: ${error.message.replace(/^Enter /, \"give \").replace(/^(Not|Use) /, (word) => word.toLowerCase())}`);\n}\n\n// ---------- chat names ----------\n\n/** The engine keeps a chat's name to 48 characters (code points: `renameLink`). */\nconst CHAT_NAME_LENGTH = 48;\n\n/**\n * A chat's name on this side (`chat rename`, an invite's `--label`), as the engine stores it (`shownName`): a tab or a\n * line break is a space, invisible characters go, and what is left is counted. Longer than the engine keeps whole is\n * refused, not cut. An empty name (or spaces) is the documented one of `chat rename` (the contact's own name) and no\n * label for an invite; a name with nothing that shows is refused: given as is, the engine cleared the chat's name. A\n * name starting with `group:` is refused: `group:<ref>` names a group in every command (`groupPrefixed`).\n */\nfunction chatName(params: Params, name: string): string | undefined {\n const value = str(params, name);\n if (value === undefined || !value.trim()) return value === undefined ? undefined : \"\";\n const clean = shownName(value, CHAT_NAME_LENGTH, \"A chat's name\", \" (an empty name gives back the contact's own)\");\n if (groupPrefixed(clean) !== null) throw new CliError(\"bad_request\", `A chat's name can't start with \"group:\": that names a group`);\n return clean;\n}\n\n// ---------- mentions ----------\n\n/** Code points before `index` (UTF-16) in `text`: mentions count code points (WISP 902 § Mentions). */\nconst codePoints = (text: string, index: number) => [...text.slice(0, index)].length;\n\n/**\n * Mentions for a group message: each ref (a member key, a unique prefix of one, a member's name, or `everyone`) must\n * be written in the text as `@<name>` (or `@<key prefix>`, `@everyone`); the first such place is the mention.\n */\nexport function mentionsFor(text: string, refs: readonly string[], group: GroupView): GroupMention[] {\n const out: GroupMention[] = [];\n for (const ref of refs) {\n let key: string, spelled: string[];\n if (ref === \"everyone\" || ref === MENTION_EVERYONE) { key = MENTION_EVERYONE; spelled = [\"everyone\", \"all\"]; }\n else {\n const lower = ref.toLowerCase();\n // A member's key is that member, whatever another member calls itself.\n const byKey = group.members.filter((m) => !m.me && m.key === ref);\n const matches = byKey.length ? byKey : group.members.filter((m) => !m.me && (m.key.startsWith(ref) || m.nick?.trim().toLowerCase() === lower));\n if (matches.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one member`);\n if (!matches.length) throw noMember(group, ref);\n key = matches[0].key;\n spelled = [matches[0].nick?.trim(), ref, key.slice(0, 8)].filter((s): s is string => !!s);\n }\n const found = spelled.map((name) => ({ name, index: text.toLowerCase().indexOf(\"@\" + name.toLowerCase()) })).find((f) => f.index >= 0);\n if (!found) throw new CliError(\"bad_request\", `Write @${spelled[0]} in the text to mention ${ref}`);\n out.push({ k: key, o: codePoints(text, found.index), l: [...\"@\" + found.name].length });\n }\n return out;\n}\n\n/** Per host: stops watching the invite it marked as the chat on screen. */\nconst inviteShown = new WeakMap<ApiContext, () => void>();\n\n/**\n * Refuses DHT only (a hold, `chat transport dht`) while a call is on in the chat. A call's signals cross the live\n * link: off it, the call talked on over its own connection, and a hang-up from either side never reached the other\n * (that call ended only when its media stalled out, 16 s later). Removing the chat (`chat remove`) is refused the same\n * way: the call talked on in a chat gone from this device, and its hang-up had no chat left to cross. `engine.call`\n * refuses the raw calls that do the same (`removeLink`, `setChatTransport` / `setDeliveryMode` to `dht`).\n */\nfunction noCallOn(ctx: ApiContext, linkId: string, then: string): void {\n const call = ctx.calls.list().find((c) => c.chat === linkId);\n if (call) throw new CliError(\"busy\", `A call is on in this chat: hang it up first (ghostly call hangup ${linkId}), then ${then}`, { call: call.call });\n}\n\n/**\n * Marks a new invite as the chat on screen (native listeners, the quick pace) only until it is paired: a paired chat\n * keeps its listeners anyway, and a daemon nobody looks at reads an away contact at the background pace, as its\n * other chats and the same chat after a restart do. Nor past its wait for a peer (`AWAITING_PEER_MS`): an invite\n * nobody joined is then read at the background pace like the daemon's other ones, which it no longer holds back.\n */\nfunction showUntilPaired(ctx: ApiContext, linkId: string): void {\n inviteShown.get(ctx)?.();\n node(ctx).setActiveLink({ linkId });\n // Gone only once a state had it: one pushed before the invite was made does not end it.\n let seen = false;\n const done = (s: EngineState) => {\n const link = s.links.find((l) => l.id === linkId);\n if (link) seen = true;\n return link ? !!link.peerParticipationKey : seen;\n };\n const stop = () => { off(); clearTimeout(timer); if (inviteShown.get(ctx) === stop) inviteShown.delete(ctx); };\n const hide = () => { stop(); node(ctx).setActiveLink({ linkId: null }); };\n const timer = setTimeout(hide, AWAITING_PEER_MS);\n timer.unref?.();\n const off = ctx.hub.onState((s) => { if (done(s)) hide(); });\n inviteShown.set(ctx, stop);\n}\n\n/**\n * `invite create`'s `reason` when no relay took the invite. The engine's words (\"Publish failed on every relay: Error:\n * http://… did not answer a moment ago; retry shortly; Error: …\") read as the CLI failing, a class name per relay, beside\n * a `note` that says the invite is good: the relays are named, and nothing is asked of whoever reads it.\n */\nfunction inviteNotOut(detail: string): string {\n if (!detail.startsWith(\"Publish failed on every relay:\")) return detail;\n const hosts = [...new Set([...detail.matchAll(/\\bhttps?:\\/\\/[^\\s;,]+/g)].map(([url]) => URL.canParse(url) ? new URL(url).host : url))];\n const named = hosts.length ? ` (${hosts.join(\", \")})` : \"\";\n // A relay that answered with an error status took the request: \"did not answer\" would not be true of it.\n return `${/ responded \\d{3}\\b/.test(detail) ? \"No relay took the invite\" : \"No relay answered\"}${named}: it goes out once one does`;\n}\n\n/** V8's words for reading what a value does not have: an `engine.call` given a parameter of the wrong kind. */\nconst BAD_VALUE = /^Cannot (destructure|read properties of (undefined|null))|is not (a function|iterable)/;\n\n/** A one-shot's typing without `--for` (it opens the profile offline, `offlineCall`): said on no live session. */\nconst ONE_SHOT_TYPING = \"Typing is said on a live session only, and a one-shot has none: it reached nobody. Keep the profile online (`ghostly daemon --detach`), or give --for to wait until it is live\";\n// A stop takes no --for, so only the daemon half holds.\nconst ONE_SHOT_TYPING_STOP = \"A stop is said on a live session only, and a one-shot has none: it reached nobody. Keep the profile online (`ghostly daemon --detach`)\";\n\n// ---------- methods ----------\n\n/**\n * A removal on its way goes with the chat's row, and the contact kept the message for good, though `message delete\n * --everyone` had said its removal goes on: `chat remove`, the engine's `removeLink` and `clearProfileData` (every\n * chat's row at once) are refused until `--force`.\n */\nfunction noRemovalOnItsWay(ctx: ApiContext, linkIds: readonly string[], clearing = false): void {\n const pending = linkIds.flatMap((linkId) => node(ctx).removalsPending({ linkId }));\n if (!pending.length) return;\n const n = pending.length, one = n === 1;\n const [now, then, go] = clearing ? [\"clearing the profile\", \"clear it then\", \"clear it\"] : [\"removing the chat\", \"remove the chat then\", \"remove it\"];\n throw new CliError(\"confirm\", `${one ? \"A message you deleted for everyone has\" : `${n} messages you deleted for everyone have`} not reached the contact yet: ${now} now leaves ${one ? \"it\" : \"them\"} on their device. Keep this profile online until the contact is reachable (ghostly daemon --detach) and ${then}, or pass --force (force: true over the socket) to ${go} now`, { messages: pending });\n}\n\n/**\n * Stages a one-shot `group join` stops waiting at. The link was replaced: knocking again does not get in. The group\n * has no room yet (`full`, or `blocked` while it waits for every member's app to take more than eight): the engine\n * goes on knocking until there is room, which a minute's wait seldom sees, so it says that the knock goes on only\n * while the profile runs.\n */\nconst NO_ROOM: Record<string, string> = {\n full: \"No room yet: the group is full\",\n blocked: \"No room yet: the group waits for every member's app to take more than eight members\",\n};\nconst JOIN_STOPS = new Set([\"replaced\", ...Object.keys(NO_ROOM)]);\n/** How long a one-shot `group join` waits to be let in: as long as a one-shot `invite join` waits to pair. */\nconst ONE_SHOT_JOIN_S = 60;\n\n/**\n * A one-shot `group join` waits to be let in, as a one-shot invite join waits to pair: a member's app lets the joiner\n * in only while its knocks go on, and they stop when the command leaves. It left at once with `{\"group\": id}` and exit\n * 0, in 0.5 s, the admin online: the group stayed an invitation at \"knocking\" and nothing said a daemon had to run for\n * the knock to be answered. The answer says whether it is in and at what stage it waits, and what to do when it is not.\n * A contact's invitation to the group keeps its place and the link is only kept beside it: nothing knocks, so it\n * answers at once. Not accepted, only `group accept` moves it; accepted, only its welcome does, over the contact's chat.\n * In a group under the link's id already (`held`, before the join), the link is only kept beside it unless it is this\n * profile's own group's (the engine's `joinByLink`): nothing knocks, and it answered `\"joined\": true` for a link whose\n * group it never joined, with a second group waiting under the id that only `group show`'s `others` said.\n * Through a daemon the knock goes on after the answer, so it waits for nothing; it answered `{\"group\": id}` only, with\n * neither whether it was in nor a word about a link only kept beside a group held.\n */\nasync function letIn(ctx: ApiContext, groupId: string, link: string, held: GroupView | undefined): Promise<Record<string, unknown>> {\n const seen = (s: EngineState) => s.groups.find((g) => g.id === groupId);\n const id = shellWord(groupId, groupId);\n const invited = seen(state(ctx))?.invitation;\n if (invited && !invited.viaLink && !invited.takenBack) {\n const who = invited.contact || \"a contact\";\n if (!invited.accepted) return { group: groupId, joined: false, stage: null, warning: `Not in yet: ${who} invited you to this group and the invitation waits for your answer. Accept it: ghostly group accept ${id}` };\n return { group: groupId, joined: false, stage: null, warning: `Not in yet: you accepted ${who}'s invitation to this group, and its welcome has not arrived; the link was kept beside it, and knocks nowhere. The welcome arrives only while this profile is running: keep it running (ghostly daemon --detach), then ghostly group show ${id}` };\n }\n const opened = decodeGroupEntryLink(link);\n const own = held?.entryLink ? decodeGroupEntryLink(held.entryLink) : null;\n if (held?.status === \"active\" && opened && own?.host !== opened.host) {\n const kept = seen(state(ctx))?.others?.some((o) => \"link\" in o && decodeGroupEntryLink(o.link)?.host === opened.host);\n const pick = `keep the one you are in (ghostly engine keepGroup '{\"groupId\":\"${groupId}\"}') or take the link's instead, which leaves the one you are in and deletes its history on this device (ghostly engine switchGroup '{\"groupId\":\"${groupId}\",\"to\":\"<its link, from group show --show-secret>\"}' --yes)`;\n return { group: groupId, joined: false, stage: null, warning: kept\n ? `Not joined: you are in a group under this link's id already, and only a group's welcome says whose a link is, so the link was kept beside that group and knocks nowhere. ghostly group show ${id} lists it under \"others\": ${pick}`\n : `Not joined: you are in a group under this link's id already, and as many other groups as are kept already wait beside it to be picked, so the link was not kept. ghostly group show ${id} lists them under \"others\": ${pick}, then open the link again` };\n }\n if (ctx.mode !== \"one-shot\") {\n const now = seen(state(ctx));\n return { group: groupId, joined: now?.status === \"active\", stage: now?.invitation?.stage ?? null };\n }\n const done = (g: GroupView | undefined) => !g || g.status === \"active\" || JOIN_STOPS.has(g.invitation?.stage ?? \"\");\n const group = await waitForState(ctx, (s) => { const g = seen(s); return done(g) ? { g } : undefined; }, ONE_SHOT_JOIN_S * 1000, `group ${groupId} to let this profile in`)\n .then(({ g }) => g, (error: unknown) => { if (error instanceof CliError && error.code === \"timeout\") return seen(state(ctx)); throw error; });\n const joined = group?.status === \"active\", stage = group?.invitation?.stage ?? null;\n if (joined || !group) return { group: groupId, joined, stage };\n // A replaced link never lets it in: the next step is a new link, not a daemon.\n if (stage === \"replaced\") return { group: groupId, joined, stage, warning: \"This link was replaced or turned off: ask someone in the group for the current link, then ghostly group join <link>\" };\n const show = `keep it running (ghostly daemon --detach), then ghostly group show ${shellWord(groupId, groupId)}`;\n const full = stage === \"full\" ? group.invitation?.full : undefined;\n const noRoom = stage ? NO_ROOM[stage] : undefined;\n if (noRoom) return { group: groupId, joined, stage, warning: `${noRoom}${full ? ` (${full.n} of ${full.max} members)` : \"\"}. Your app goes on knocking only while this profile is running, and gets in when there is room: ${show}` };\n if (stage === \"admitted\") return { group: groupId, joined, stage, warning: `Not in yet: a member's app let you in, and the group's welcome has not finished arriving. It arrives only while this profile is running: ${show}` };\n return { group: groupId, joined, stage, warning: `Not in yet: no member's app has let you in. A member's app lets you in only while this profile is running: ${show}` };\n}\n\n/**\n * Why a text that waits will not go by itself, or undefined (waitNotice.ts `dhtOnlyNote`). This side's DHT only that is\n * a hold (`chat disconnect --hold`) is read from `ctx`'s profile; without it, as a DHT only chosen.\n */\nfunction dhtOnlyWait(link: LinkView, text: string, ref: string, ctx?: ApiContext): string | undefined {\n const mine = link.deliveryMode === \"dht\";\n return dhtOnlyNote({ mine, theirs: link.dhtDelivery?.peerMode === \"dht\", heldUntil: mine && ctx ? holdEnds(ctx, link.id) : null, oneShot: ctx?.mode === \"one-shot\" }, text, ref);\n}\n\n/**\n * A `--wait sent|delivered` on a text `dhtOnlyWait` holds back, ended short (its timeout, the daemon's stop): it said the\n * text still goes by itself, or with this profile's next command, which it does not while the chat stays on the DHT\n * only. It says why instead, with the note in `details.note` too; same code and exit. Read again at the end: a chat\n * taken off DHT only meanwhile keeps the usual words.\n */\nfunction dhtOnlyTimeout(ctx: ApiContext, chat: string, text: string, ref: string, ms: number, error: unknown): unknown {\n if (!(error instanceof CliError) || error.code !== \"timeout\" || error.details?.delivery !== \"waiting\") return error;\n const link = state(ctx).links.find((l) => l.id === chat);\n const note = link && dhtOnlyWait(link, text, ref, ctx);\n return note ? new CliError(\"timeout\", `${ended(ctx, ms)}: the message is waiting. ${note}`, { ...error.details, note }) : error;\n}\n\n/**\n * What keeps `link` off a live session, or undefined: a chat on DHT only opens none (WISP 100: no app dials it). A hold\n * of this side's (`chat disconnect --hold`) ends by itself (`held`: when), unless the contact's choice keeps it there\n * too; this side's choice or the contact's is `chat connect`'s refusal (apiKit `dhtOnly`), in its words.\n */\nfunction offLive(ctx: ApiContext, link: LinkView): { held: number } | { refusal: CliError } | undefined {\n const held = link.deliveryMode === \"dht\" && link.dhtDelivery?.peerMode !== \"dht\" ? holdEnds(ctx, link.id) : null;\n if (held !== null) return { held };\n try { dhtOnly(link); } catch (error) { if (error instanceof CliError) return { refusal: error }; throw error; }\n return undefined;\n}\n\n/**\n * A `chat wait --until live` that timed out on a chat on DHT only: it could never go live, and its timeout read as a\n * slow network, so a script waited again. Said with why and what ends it, in `chat connect`'s words; same code, exit\n * and fields. Read as the chat is at the end: one taken off DHT only meanwhile keeps the usual words.\n */\nfunction liveNeverCame(ctx: ApiContext, linkId: string, ref: string, error: unknown): unknown {\n if (!(error instanceof CliError) || error.code !== \"timeout\" || error.details) return error;\n const link = state(ctx).links.find((l) => l.id === linkId);\n const off = link && offLive(ctx, link);\n if (!off) return error;\n const why = \"held\" in off ? heldWords(off.held, ref, \"it goes live\", ctx.mode === \"one-shot\") : off.refusal.message;\n return new CliError(\"timeout\", `${error.message}. ${why.charAt(0).toUpperCase()}${why.slice(1)}`);\n}\n\nconst METHODS: Record<string, Method> = {\n ...WALLET_METHODS,\n ...FILE_METHODS,\n ...STATUS_CARD_METHODS,\n ...BUTTON_METHODS,\n ...GROUP_ADMIN_METHODS,\n ...IDENTITY_METHODS,\n ...X401_METHODS,\n ...SERVICE_METHODS,\n ...BACKUP_METHODS,\n ...CALL_METHODS,\n ...APP_SERVE_METHODS,\n ...APP_CHAT_METHODS,\n\n async status(ctx) {\n const s = state(ctx);\n // A daemon's: how each relay is doing and where its last read went, as the apps' connection panel says. With every\n // relay down, its status read as with them all fine. A one-shot asked none of them.\n const seen = ctx.mode === \"daemon\" ? s.transport.discovery : undefined;\n return {\n version: ctx.version, profile: ctx.runtime.paths.name, mode: ctx.mode, pid: process.pid,\n online: s.settings.online, name: s.settings.nick || null, webrtc: ctx.runtime.webrtc, calls: ctx.runtime.callsUnavailable === null,\n chats: s.links.length, live: s.links.filter(isLive).length, groups: s.groups.length,\n discovery: { protocol: s.transport.protocol, relays: s.transport.relays, ...(seen && { health: seen.relays, via: seen.path?.via ?? null }) },\n events: { lastSeq: ctx.hub.lastSeq },\n // A listen running the profile: `daemon stop` and `restart` end it too, as their answers say.\n ...(ctx.listen && { listen: true }),\n };\n },\n\n /**\n * This profile's status (WISP 401 § Presence and status), said to every paired contact whose app offers `status/1`:\n * at once on a live session, else on each chat's next one. A new one replaces the one before, whole.\n */\n async \"status.get\"(ctx) {\n return statusJson(node(ctx).getOwnStatus().status);\n },\n async \"status.set\"(ctx, params) {\n const until = params.until === undefined ? undefined : num(params, \"until\", 0, { min: 1, whole: true });\n const status = checkOwnStatus({ text: str(params, \"text\"), emoji: str(params, \"emoji\"), availability: str(params, \"availability\"), until }, (field) => field, \"bad_request\");\n // Every contact reads it, as the name they see.\n guardText(status.text, bool(params, \"force\"), \"status\", \"set it\");\n await node(ctx).setOwnStatus({ status });\n return statusJson(node(ctx).getOwnStatus().status);\n },\n async \"status.clear\"(ctx) {\n await node(ctx).clearOwnStatus();\n return statusJson(node(ctx).getOwnStatus().status);\n },\n\n async \"profile.get\"(ctx) {\n const settings = settingsOf(ctx);\n return { profile: ctx.runtime.paths.name, name: settings.nick || null, shareProfile: settings.shareProfile !== false, picture: !!settings.avatar, online: settings.online };\n },\n async \"profile.set\"(ctx, params) {\n const patch: Partial<Settings> = {};\n if (params.name !== undefined) patch.nick = checkShownName(params.name);\n // Every contact reads it, as a message's text.\n guardText(patch.nick, bool(params, \"force\"), \"name\", \"set it\");\n if (params.shareProfile !== undefined) patch.shareProfile = bool(params, \"shareProfile\");\n await node(ctx).updateSettings({ settings: patch });\n return METHODS[\"profile.get\"](ctx, {});\n },\n\n async \"settings.get\"(ctx, params) {\n return redactSettings(settingsInEffect(settingsOf(ctx)), bool(params, \"showSecret\"));\n },\n async \"settings.set\"(ctx, params) {\n const patch: Record<string, unknown> = {};\n let warning: string | undefined;\n for (const [key, value] of Object.entries(params)) {\n if (key === \"force\") continue;\n // The table's own keys only: every object has `constructor` and `toString`, which are no settings.\n const kind = Object.hasOwn(SETTABLE, key) ? SETTABLE[key] : undefined;\n // The app's \"Also use Pkarr relays\": the CLI reads the relays first whatever it says (README § Network), and a\n // false taken with exit 0 changed nothing (bug hunt, 2026-10-19).\n if (key === \"readRelays\") throw new CliError(\"bad_request\", \"readRelays is not a setting the CLI follows: it reads the Pkarr relays first, so a contact on the web app (relays only) is found, and the Mainline DHT when every relay fails\");\n if (!kind) throw new CliError(\"bad_request\", `${key} is not a setting the CLI changes (${Object.keys(SETTABLE).join(\", \")})`);\n if (kind === \"strings\" && !(Array.isArray(value) && value.every((v) => typeof v === \"string\"))) throw new CliError(\"bad_request\", `${key} must be a list of strings`);\n if (kind === \"string\" && typeof value !== \"string\") throw new CliError(\"bad_request\", `${key} must be a string`);\n if (kind === \"boolean\" && typeof value !== \"boolean\") throw new CliError(\"bad_request\", `${key} must be true or false`);\n // The engine says \"Enter at least one relay address\" for any list it can't use (node.ts `updateSettings`): the\n // address given is named here, in the app's Settings words; an empty list stays the engine's to refuse.\n if (key === \"relays\" && (value as string[]).length && !(value as string[]).some(normalizeRelayUrl)) {\n throw relayRefused(new Error(relayUrlProblem((value as string[])[0]) ?? \"\"), { relays: value });\n }\n // The name contacts see: `profile set --name`'s rule.\n if (key === \"nick\") { patch.nick = checkShownName(value, key); guardText(patch.nick, bool(params, \"force\"), \"nick\", \"set it\"); continue; }\n if (kind === \"ice\") {\n if (!(Array.isArray(value) && value.every((v) => v && typeof v === \"object\"))) throw new CliError(\"bad_request\", `${key} must be a list of ICE servers`);\n // WebRTC's own form (`urls` a list) is taken; a server without urls is said here, not as the engine's TypeError.\n const servers = value.map(iceServerSetting);\n for (const server of servers) { const problem = iceServerProblem(server); if (problem) throw new CliError(\"bad_request\", `${key}: ${problem}`); }\n patch[key] = servers;\n // libdatachannel (libjuice) skips TURN over TCP and TLS without a word; the apps' browsers use them, so they stay.\n const unused = servers.flatMap((server) => server.urls.split(/[\\s,]+/)).filter((url) => /^turns:|\\?transport=tcp$/i.test(url));\n if (unused.length) warning = `The CLI reaches TURN over UDP only: it does not use ${unused.join(\", \")} (the apps do). Add a turn: server over UDP for the CLI`;\n continue;\n }\n patch[key] = value;\n }\n await node(ctx).updateSettings({ settings: patch }).catch((error: unknown) => { throw relayRefused(error, patch); });\n return { ...redactSettings(settingsInEffect(settingsOf(ctx))), ...(warning ? { warning } : {}) };\n },\n\n async \"invite.create\"(ctx, params) {\n const label = chatName(params, \"label\");\n const { linkId, inviteCode } = await node(ctx).createLink();\n if (label) await node(ctx).renameLink({ linkId, label });\n // Native listeners start for the chat on screen (or a paired one): a new invite is the chat a bot waits on.\n showUntilPaired(ctx, linkId);\n // Its first records must be out before a one-shot leaves. A daemon publishes them later too: it answers at once when\n // the relays' request budget holds them back (a few invites in a minute), and says when they go.\n const progressOf = (s: EngineState) => s.links.find((l) => l.id === linkId)?.pairingProgress;\n const progress = await waitForState(ctx, (s) => { const p = progressOf(s); return p && (p.stage !== \"publishing\" || (ctx.mode === \"daemon\" && p.relayWaitUntil)) ? p : undefined; }, 20_000, \"the invite to be published\")\n .catch(() => progressOf(state(ctx)));\n const published = !!progress && progress.stage !== \"publishing\" && progress.reason !== \"publish\";\n const answer = { chat: linkId, invite: inviteCode, link: inviteLink(inviteCode), published };\n if (published) return answer;\n // Not out yet is not lost: the link works, so nobody should make another. Said here, not only in `chat show`.\n const waitUntil = progress?.relayWaitUntil;\n return {\n ...answer,\n ...(waitUntil !== undefined && { retryInMs: Math.max(0, waitUntil - Date.now()) }),\n ...(progress?.detail && { reason: inviteNotOut(progress.detail) }),\n note: \"The invite is good: it goes out by itself once a relay answers, while a daemon runs for this profile\",\n };\n },\n async \"invite.join\"(ctx, params) {\n let invite = str(params, \"invite\", true).trim();\n const label = chatName(params, \"label\");\n const hash = invite.indexOf(\"#\");\n if (/^https?:\\/\\//i.test(invite) && hash !== -1) invite = invite.slice(hash + 1);\n let linkId: string;\n try {\n ({ linkId } = await node(ctx).joinLink({ inviteCode: invite }));\n } catch (error) {\n // This profile's own invite: the sentence alone, and the chat that owns it as its own field, not the engine's tag\n // for its RPC clients (\"own-invite <chat>: …\").\n const own = ownInviteRefusal(error);\n if (own) throw new CliError(\"refused\", \"This is your own invite. Share it with a contact; they join with it.\", own.linkId ? { chat: own.linkId } : undefined);\n const message = error instanceof Error ? error.message : String(error);\n if (/does not look like/i.test(message)) throw new CliError(\"bad_request\", message);\n throw error;\n }\n if (label) await node(ctx).renameLink({ linkId, label });\n showUntilPaired(ctx, linkId);\n return { chat: linkId };\n },\n\n async \"chat.list\"(ctx, params) {\n const showSecret = bool(params, \"showSecret\");\n return { chats: state(ctx).links.map((link) => chatJson(link, showSecret)).sort((a, b) => (b.lastMessageAt ?? 0) - (a.lastMessageAt ?? 0) || b.createdAt - a.createdAt) };\n },\n async \"chat.get\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group show\");\n return { ...chatDetailsJson(link, bool(params, \"showSecret\")), heldUntil: holdOf(ctx, link.id) };\n },\n async \"chat.history\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group history\");\n return historyOf(ctx, link.id, params, async () => (m) => chatMessageJson(m, link));\n },\n async \"chat.send\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group send\", \"[text...]\");\n const text = str(params, \"text\", true);\n checkTextSize(text);\n if (!bool(params, \"force\")) {\n const secret = findSecret(text);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; send it with --force if you mean to`, { kind: secret.kind });\n }\n // A one-shot leaves with its process, so by default it stays until the text went out. To a chat whose invite nobody\n // took there is no one to send to: the text is kept and goes once they join. It sat 30 s, then answered `timeout`.\n const unjoined = nobodyJoined(link);\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, ctx.mode === \"one-shot\" && !unjoined ? \"sent\" : \"none\");\n // Read before anything is sent, as `wait` is: a timeout refused after the send made a retry send it again.\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const replyTo = str(params, \"reply\");\n // Buttons under the text (WISP 406 · Message Buttons): the text is the question, and what older apps show.\n const card = buttonsCard(params);\n // A kept `typing --for` ends with the message (the engine says stop with it).\n endTyping(ctx, { linkId: link.id }, false);\n const result = await node(ctx).sendMessage({ linkId: link.id, text, ...(replyTo ? { replyTo } : {}), ...(card ? { card } : {}) });\n // A `--reply` to a message this chat does not have is not_found (exit 3), as `file send --reply` and `group send` say.\n if (result.error) {\n throw (replyTo && notHere(result.error, replyTo, { group: false, ref: str(params, \"chat\", true) }))\n || (/not in this chat|cannot be replied to/.test(result.error) ? new CliError(\"not_found\", result.error) : new CliError(result.refused ? \"refused\" : \"unavailable\", dhtTooLong(ctx, link, result.error, \"text\", str(params, \"chat\", true))));\n }\n if (!result.messageId) throw new CliError(\"bad_request\", \"Nothing to send\");\n let message = await node(ctx).getMessage(link.id, result.messageId);\n // Past the 256 bytes the DHT carries, in a chat on the DHT only: it waits for a live session, which comes only once\n // the chat leaves DHT only. A one-shot sat 30 s, then answered `timeout` saying it goes with the next command.\n const ref = str(params, \"chat\", true);\n const dhtOnly = message?.delivery === \"waiting\" ? dhtOnlyWait(link, text, ref, ctx) : undefined;\n // An explicit `--wait` still waits as asked, and a wait that ends short says that note, not that the text goes by itself.\n if (wait !== \"none\" && !(dhtOnly && params.wait === undefined)) {\n message = await waitForMessage(ctx, link.id, result.messageId, wait, ms).catch((error: unknown) => { throw dhtOnlyTimeout(ctx, link.id, text, ref, ms, error); });\n }\n return {\n chat: link.id, messageId: result.messageId, delivery: message?.delivery ?? null, ...(card ? { buttons: card.id, card, pressable: pressable(link) } : {}),\n ...(unjoined && message?.delivery === \"waiting\" && { note: `Nobody joined this chat yet: the message goes once they join${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}` }),\n ...(dhtOnly && message?.delivery === \"waiting\" && { note: dhtOnly }),\n };\n },\n /**\n * WISP 400 § Edits: the whole new text of one of my texts in a 1:1 chat. It shows here at once and reaches the contact\n * once the chat is live and both apps offer edit/1; `--wait confirmed` waits for the contact to confirm it.\n */\n async \"chat.edit\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group edit\", \"<message> <text...>\");\n const messageId = str(params, \"message\", true);\n const text = str(params, \"text\", true);\n // Before the guard: it read megabytes whole (`edit --stdin`), holding the daemon, for the engine to refuse them after.\n checkTextSize(text);\n if (!bool(params, \"force\")) {\n const secret = findSecret(text);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });\n }\n const { wait, ms } = confirmWait(ctx, params, link.id);\n // The edit number before, as `group edit` reads it: the text the message already has makes no edit. Undefined for\n // a message named by its wire id (no row goes by it): then only a message never edited is known unchanged.\n const prior = await node(ctx).getMessage(link.id, messageId);\n const before = prior ? prior.edit?.seq ?? 0 : undefined;\n const result = await node(ctx).editMessage({ linkId: link.id, messageId, text });\n if (result.error) throw await editRefused(ctx, link.id, messageId, { group: false, ref: str(params, \"chat\", true) }, dhtTooLong(ctx, link, result.error, \"edit\", str(params, \"chat\", true)), result);\n const id = result.messageId ?? messageId;\n let message = await node(ctx).getMessage(link.id, id);\n const edits = message?.edit?.seq ?? 0;\n // It answered `edits` as before with no flag, so a script could not tell it from an edit that went.\n const unchanged = !!message && edits === (before ?? 0);\n if (wait === \"confirmed\" && message?.edit?.pending) message = await waitForEdit(ctx, link.id, id, ms);\n const confirmed = !!message && !message.edit?.pending;\n // Too long for the DHT packet as an edit: it waits for the live session (`note`), refused where none comes.\n return { chat: link.id, messageId: id, edits: message?.edit?.seq ?? 0, confirmed, ...(unchanged && { unchanged: true }), ...(!confirmed && result.note && { note: result.note }), ...(!confirmed && keptForJoin(ctx, link.id, \"the edit\")) };\n },\n /**\n * WISP 401 § Typing: said on the live session only, and a start only while `sendTyping` is on; it holds 6 s there.\n * `kind` (typing, recording, thinking) and `status` (a short line, e.g. \"Transcribing your audio…\") say what this\n * side is doing; a new one reaches the contact at once.\n * `for`: kept that many seconds (a one-shot stays that long once the chat is live, and stops when it is not live\n * within `ONE_SHOT_LIVE_GRACE_MS`), until a message to the chat or a stop.\n */\n async \"chat.typing\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group typing\");\n const typing = !bool(params, \"stop\");\n const { kind, status } = typingWord(params, typing);\n const word = { ...(kind !== \"typing\" ? { kind } : {}), ...(status ? { status } : {}) };\n const seconds = params.for === undefined ? 0 : num(params, \"for\", 0, { min: 1, max: 600 });\n if (!typing && seconds) throw new CliError(\"bad_request\", \"for keeps typing on: not with stop\");\n endTyping(ctx, { linkId: link.id }, false);\n node(ctx).setTyping({ linkId: link.id, typing, ...word });\n const until = seconds ? Date.now() + seconds * 1000 : null;\n const kept = seconds ? keepTyping(ctx, { linkId: link.id }, seconds * 1000, word) : null;\n const open = (s: EngineState) => s.links.find((l) => l.id === link.id)?.dataLink === \"open\";\n if (kept && ctx.mode === \"one-shot\") await keepOneShot(ctx, { linkId: link.id }, kept, open);\n const now = state(ctx);\n return {\n chat: link.id, typing, ...(typing ? { kind } : {}), ...(status ? { status } : {}),\n live: open(now), sendTyping: now.settings.sendTyping !== false, ...(until ? { until } : {}),\n ...(!kept && ctx.mode === \"one-shot\" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }),\n };\n },\n /**\n * WISP 400 § Reactions: one emoji per person per message, a new one replaces mine; `remove` takes mine back.\n * `wait: confirmed` (a one-shot's default) stays until the contact confirmed it; `confirmed` says whether it has.\n */\n async \"chat.react\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group react\", \"<message> <emoji>\");\n const { wait, ms } = confirmWait(ctx, params, link.id);\n // A new reaction of mine is numbered past every one still waiting: it is confirmed once none past those is left.\n const before = Math.max(...node(ctx).chatUnconfirmed({ linkId: link.id }).reactions);\n const result = await react(ctx, link.id, params, { group: false, ref: str(params, \"chat\", true) });\n const pending = (left: { reactions: number[] }) => left.reactions.some((n) => n > before);\n if (wait === \"confirmed\") await waitForConfirmed(ctx, link.id, \"reaction\", pending, ms);\n const confirmed = !pending(node(ctx).chatUnconfirmed({ linkId: link.id }));\n return { chat: link.id, ...result, confirmed, ...(!confirmed && keptForJoin(ctx, link.id, \"the reaction\")) };\n },\n /**\n * WISP 400 § Pinned message: one per chat or group, a new pin replaces it; `remove` unpins. In a community only the\n * admin pins. Answers the chat (or group) and the message now pinned (null once unpinned). In a 1:1 chat `wait:\n * confirmed` (a one-shot's default) stays until the contact confirmed it, and `confirmed` says whether it has. A\n * group has no receipts: `wait: sent` (a one-shot's default) stays until an edge took it, and `edges` and `sent` say\n * how many did, as for `group react`.\n */\n async \"chat.pin\"(ctx, params) {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const remove = bool(params, \"remove\"), messageId = remove ? str(params, \"message\") : str(params, \"message\", true);\n if (target.group && params.wait === \"confirmed\") throw new CliError(\"bad_request\", \"A group has no receipts: wait confirmed is for a 1:1 chat (wait sent waits until a member's edge took it)\");\n if (!target.group && params.wait === \"sent\") throw new CliError(\"bad_request\", \"wait sent is for a group: a 1:1 chat's pin waits with wait confirmed\");\n const { wait, ms } = target.group\n ? { wait: oneOf(params, \"wait\", [\"none\", \"sent\"] as const, ctx.mode === \"one-shot\" ? \"sent\" : \"none\"), ms: num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000 }\n : confirmWait(ctx, params, target.linkId);\n const result = await node(ctx).pinMessage({ linkId: target.linkId, ...(messageId && { messageId }), remove });\n const gone = result.error && messageId ? notHere(result.error, messageId, { group: target.group, ref: str(params, \"chat\", true) }) : undefined;\n if (gone) throw gone;\n if (result.error) {\n const error = new CliError(result.refused || /Only the admin/.test(result.error) ? \"refused\" : /not in this (?:chat|group)|Nothing is pinned/.test(result.error) ? \"not_found\" : \"bad_request\", result.error);\n const group = target.group ? groupById(ctx, target.id) : undefined;\n throw group ? notInYetError(group, str(params, \"chat\", true), error) : error;\n }\n if (target.group) {\n // A one-shot leaves once its command is done, and its groups with it: what no edge took yet went nowhere.\n const n = result.n, pinned = remove ? null : messageId;\n const edges = !n ? 0 : wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, messageId ?? \"\", { pin: n }, ms)\n : node(ctx).groupTaken({ groupId: target.id, messageId: messageId ?? \"\", pin: n });\n return { group: target.id, messageId: pinned, removed: remove, sent: edges > 0, edges };\n }\n // The chat's one pin of mine waiting for the contact is this one (none: the contact confirmed it already).\n const mine = node(ctx).chatUnconfirmed({ linkId: target.linkId }).pin;\n const pending = (left: { pin: number | null }) => mine !== null && left.pin === mine;\n if (wait === \"confirmed\") await waitForConfirmed(ctx, target.linkId, \"pin\", pending, ms);\n const confirmed = !pending(node(ctx).chatUnconfirmed({ linkId: target.linkId }));\n return { chat: target.id, messageId: remove ? null : messageId, removed: remove, confirmed, ...(!confirmed && keptForJoin(ctx, target.linkId, remove ? \"the unpin\" : \"the pin\")) };\n },\n /** Saved messages: a mark on a message of a chat or a group, kept for this profile on this device; nothing is sent. */\n async \"saved.add\"(ctx, params) {\n return saveMark(ctx, params, false);\n },\n async \"saved.remove\"(ctx, params) {\n return saveMark(ctx, params, true);\n },\n /** The saved messages under `saved`, the last saved first, each as it is now and named by its chat or group. */\n async \"saved.list\"(ctx) {\n const { links, groups } = state(ctx);\n const saved = await node(ctx).savedMessages();\n // A saved reply quotes its original as history gives it: per chat or group, one read per quoted original.\n const originals = new Map<string, Originals>();\n for (const linkId of new Set(saved.map((s) => s.message.linkId))) originals.set(linkId, await originalsNow(ctx, linkId, saved.flatMap((s) => (s.message.linkId === linkId ? [s.message] : []))));\n return {\n saved: saved.map(({ savedAt, message }) => {\n const checked = (json: MessageJson) => quoteChecked(json, message, originals.get(message.linkId)!);\n if (!message.linkId.startsWith(\"group:\")) return { chat: message.linkId, savedAt, message: checked(chatMessageJson(message, links.find((l) => l.id === message.linkId))) };\n const id = message.linkId.slice(\"group:\".length);\n return { group: id, savedAt, message: checked(groupMessageJson(message, groups.find((g) => g.id === id))) };\n }),\n };\n },\n /**\n * WISP 400 § Forwards: messages of a chat or a group sent on to up to 5 chats and groups, each as a new message of mine\n * that says it was forwarded (one hop more) and nothing of who wrote it. A file goes from the bytes here, never\n * fetched again; a group takes texts only. `wait: sent`: each text until it is on its way (a group's until an edge\n * took it), each file until its transfer is done. What a chat refused comes back per chat; any refusal fails the call.\n */\n async \"chat.forward\"(ctx, params) {\n const s = state(ctx);\n const from = chatOrGroup(ctx, str(params, \"chat\", true), s);\n // Each id once, and the engine's bounds before any row is read: one id given 50,000 times was read and guarded as\n // often (a minute of the daemon's thread) for the one message the engine forwarded.\n const messageIds = [...new Set(list(params, \"messages\"))];\n if (!messageIds.length) throw new CliError(\"bad_request\", \"Name the messages to forward (their ids, from history or an event)\");\n if (messageIds.length > FORWARD_MESSAGES) throw new CliError(\"bad_request\", `Forward at most ${FORWARD_MESSAGES} messages at once, not ${messageIds.length}`);\n // A chat or group named twice (by its name and its id too) is one of them, as the engine counts.\n const to: (ReturnType<typeof chatOrGroup> & { ref: string })[] = [];\n for (const ref of new Set(list(params, \"to\"))) {\n const target = chatOrGroup(ctx, ref, s);\n if (to.some((t) => t.linkId === target.linkId)) continue;\n if (to.length === FORWARD_TARGETS) throw new CliError(\"bad_request\", `Forward to at most ${FORWARD_TARGETS} chats and groups at once`);\n to.push({ ...target, ref });\n }\n if (!to.length) throw new CliError(\"bad_request\", \"Forward to which chat? Name one or more with --to\");\n // Each by its id here, one row each: never the whole history of the chat or group.\n const chosen: StoredMessage[] = [];\n for (const id of messageIds) {\n const message = await node(ctx).getMessage(from.linkId, id);\n if (!message) throw noMessage(id, { group: from.group, ref: str(params, \"chat\", true) });\n chosen.push(message);\n }\n if (!bool(params, \"force\")) for (const message of chosen) {\n const secret = message.file ? null : findSecret(message.text);\n if (secret) throw new CliError(\"confirm\", `A message looks like ${secretWords(secret)}; forward it with --force if you mean to`, { kind: secret.kind, messageId: message.id });\n }\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\");\n // A one-shot leaves once its command is done, and its groups with it: a group's copy waits for an edge by default,\n // as `group send` does.\n const groupWait = params.wait === undefined && ctx.mode === \"one-shot\" ? \"sent\" : wait;\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n let results;\n try { ({ results } = await node(ctx).forwardMessages({ linkId: from.linkId, messageIds, to: to.map((t) => t.linkId) })); }\n catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n const out: { to: string; kind: \"group\" | \"chat\"; messageIds: string[]; sent: string[]; error: string | null; edges?: number; note?: string }[] =\n results.map((result, i) => ({ to: to[i]!.id, kind: to[i]!.group ? \"group\" as const : \"chat\" as const, messageIds: result.messageIds, sent: result.sent, error: result.error }));\n // A text past the 256 bytes the DHT carries, forwarded into a chat on the DHT only, waits as `send`'s does: the\n // chat's result says why in a `note`, and a `--wait sent` that ends short says it too. It said nothing, and the\n // timeout that the text still goes by itself.\n for (const [i, result] of out.entries()) {\n const link = to[i]!.group ? undefined : state(ctx).links.find((l) => l.id === to[i]!.id);\n // Its copies read only in a chat on the DHT only, by either side's choice.\n if (!link || (link.deliveryMode !== \"dht\" && link.dhtDelivery?.peerMode !== \"dht\")) continue;\n for (const messageId of result.messageIds) {\n const copy = await node(ctx).getMessage(link.id, messageId);\n if (copy && !copy.file && copy.delivery === \"waiting\") result.note ??= dhtOnlyWait(link, copy.text, to[i]!.ref);\n }\n }\n // A copy's wait that ends short (its time ran out, its delivery failed) ends the waits, not the answer: it threw\n // alone with that copy's id, every target's result and another's refusal lost, and a bot that sent again sent twice.\n let short: CliError | undefined;\n const waited = async <T>(wait: () => Promise<T>, now: () => T): Promise<T> => {\n if (short) return now();\n try { return await wait(); } catch (error) { short = asCliError(error); return now(); }\n };\n // A group's `edges`: how many took each of its copies so far (the fewest), as `group send` says it.\n for (const [i, result] of out.entries()) if (to[i]!.group) {\n let edges: number | undefined;\n for (const messageId of result.messageIds) {\n const taken = () => node(ctx).groupTaken({ groupId: to[i]!.id, messageId });\n const took = groupWait === \"sent\" ? await waited(() => waitForGroupFrame(ctx, to[i]!.id, messageId, undefined, ms), taken) : taken();\n edges = Math.min(edges ?? took, took);\n }\n result.edges = edges ?? 0;\n }\n if (wait === \"sent\") for (const [i, result] of out.entries()) for (const messageId of result.messageIds) {\n if (to[i]!.group) continue;\n await waited(async () => {\n const sent = await node(ctx).getMessage(to[i]!.id, messageId);\n if (sent?.file) await FILE_METHODS[\"file.wait\"](ctx, { chat: to[i]!.id, file: sent.file.id, timeout: ms / 1000 });\n else await waitForMessage(ctx, to[i]!.id, messageId, \"sent\", ms).catch((error: unknown) => { throw dhtOnlyTimeout(ctx, to[i]!.id, sent?.text ?? \"\", to[i]!.ref, ms, error); });\n }, () => undefined);\n }\n // A refusal first, then what ended a wait: each with every target's result.\n const failed = out.filter((r) => r.error);\n if (failed.length) throw new CliError(failed.length === out.length ? \"refused\" : \"engine\", failed.map((r) => `${r.to}: ${r.error}`).join(\"; \"), { from: from.id, results: out });\n if (short) throw new CliError(short.code, short.message, { ...short.details, from: from.id, results: out });\n return { from: from.id, results: out };\n },\n async \"chat.retry\"(ctx, params) {\n // A group has no failed message to send again: it stays in the group and goes when a member's edge opens.\n const link = notAGroup(ctx, params, () => chatOf(ctx, params), () => \"a group's message is not sent again by hand, it goes by itself when a member's edge opens\");\n const messageId = str(params, \"message\", true);\n const message = await node(ctx).getMessage(link.id, messageId);\n const place = { group: false, ref: str(params, \"chat\", true) };\n if (!message) throw noMessage(messageId, place);\n // Before, both answered done and nothing was sent: the engine sends again whatever id it is given.\n if (message.sender !== \"me\") throw noMessage(messageId, place, { whose: \"of yours\", tail: \": only your own messages are sent again\" });\n if (message.delivery === \"delivered\") throw new CliError(\"refused\", \"Nothing to send again: it was delivered\");\n await node(ctx).retryMessage({ linkId: link.id, messageId });\n return { chat: link.id, messageId };\n },\n // `--purge` folds the store even when the delete answers no (`foldsAnyway`): a message already gone, another's.\n \"chat.delete\": foldsAnyway(async (ctx, params) => {\n // `--purge`: what it said leaves the profile's folder before the answer (`purgeMessage`), and the answer says so.\n const purge = bool(params, \"purge\"), purged = purge ? { purged: true } : {};\n // For everyone (WISP 400 § Delete for everyone): a message of mine, in a chat or a group, gone from every device.\n if (bool(params, \"everyone\")) {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n // A one-shot leaves once its command is done, and the removal with it: by default it stays until the contact has it,\n // or in a group (no receipts) until a member's edge took it.\n const wait = oneOf(params, \"wait\", [\"none\", \"confirmed\", \"sent\"] as const, ctx.mode !== \"one-shot\" ? \"none\" : target.group ? \"sent\" : \"confirmed\");\n if (target.group && wait === \"confirmed\") throw new CliError(\"bad_request\", \"A group has no receipts: --wait confirmed is for a chat (--wait sent waits until a member's edge took it)\");\n if (!target.group && wait === \"sent\") throw new CliError(\"bad_request\", \"--wait sent is for a group: a chat's removal waits with --wait confirmed\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const ref = str(params, \"message\", true);\n // Another's message the ref names (by its id or wire id), seen in the same reads that look for mine.\n let theirs: StoredMessage | undefined;\n const message = await messageOf(ctx, target.linkId, ref, (m) => {\n if (m.sender !== \"me\" && (m.id === ref || m.wireId === ref)) theirs ??= m;\n return m.sender === \"me\";\n });\n if (!message) throw deleteNotMine(ctx, target, ref, theirs, { group: target.group, ref: str(params, \"chat\", true) }, purge);\n const result = await node(ctx).removeMessage({ linkId: target.linkId, messageId: message.id });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n // Gone here at once: the fold need not wait for the contact or an edge.\n if (purge) await purgeMessage(ctx, message);\n // A wait that ends short: the message is gone here all the same (out of the folder with `--purge`), so its timeout\n // says so and names it as the answer would. The group's said \"it stays in the group\", as for an edit, and neither\n // said the purge ran: a script saw exit 4, and its retry was refused as \"No message … of yours\".\n const goneHere = async <T>(wait: () => Promise<T>, text?: string): Promise<T> => {\n try { return await wait(); } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"timeout\") throw error;\n throw new CliError(\"timeout\", text ?? error.message, { ...error.details, deleted: message.id, ...purged });\n }\n };\n // `messageId`, as every command that makes or changes a message names it; `deleted` kept for callers that read\n // it (agents#1582).\n if (target.group) {\n const e = result.e;\n const edges = !e ? 0 : wait === \"sent\"\n ? await goneHere(() => waitForGroupFrame(ctx, target.id, message.id, e, ms), `${ended(ctx, ms)}: the message is gone here and no member's edge took its removal yet (it goes when one opens). Its removal ${goesOn(ctx)}`)\n : node(ctx).groupTaken({ groupId: target.id, messageId: message.id, edit: e });\n return { group: target.id, messageId: message.id, deleted: message.id, everyone: true, sent: edges > 0, edges, ...purged };\n }\n if (wait === \"confirmed\") await goneHere(() => waitForRemoval(ctx, target.linkId, message.id, ms));\n return { chat: target.id, messageId: message.id, deleted: message.id, everyone: true, confirmed: !node(ctx).removalPending({ linkId: target.linkId, messageId: message.id }), ...purged };\n }\n // A group's message is deleted for everyone only (the apps forget none on one device): a group named without the\n // flag says so, with the command that takes it, not \"No chat\".\n // `message delete --everyone` takes a chat's name before a group's, and never takes a name shaped like a chat's id or\n // a contact's key as a group's: the command offered names the group by `group:` unless the name alone reaches it.\n const ref = str(params, \"message\") ?? \"<message>\", typed = str(params, \"chat\", true);\n const reachesGroup = (name: string) => { try { return \"group\" in findChatOrGroup(state(ctx).links, state(ctx).groups, name); } catch { return false; } };\n let link: ReturnType<typeof chatOf>;\n try {\n // `--purge` stays in the command offered: pasted without it, the text stayed in the profile's folder up to an hour.\n link = notAGroup(ctx, params, () => chatOf(ctx, params), (shown, id) => `ghostly message delete ${groupPrefixed(typed) === null && reachesGroup(typed) ? shown : shellWord(groupPrefixed(typed) === null ? `group:${typed}` : typed, `group:${id}`)} ${ref === \"<message>\" ? ref : shellWord(ref, \"<message>\")} --everyone${purge ? \" --purge\" : \"\"}`);\n } catch (error) {\n // Another member's message: only its author deletes it, so the `--everyone` offered was then refused as not mine,\n // a second command to learn it cannot be deleted at all. A history that cannot be read keeps that hint.\n const group = error instanceof CliError ? error.details?.group : undefined;\n const theirs = typeof group === \"string\" && ref !== \"<message>\" ? await messageOf(ctx, `group:${group}`, ref).catch(() => undefined) : undefined;\n if (theirs && theirs.sender !== \"me\") throw new CliError(\"not_found\", `${JSON.stringify(typed)} is a group, and ${JSON.stringify(ref)} is another member's message in it: only its author deletes a group's message, for everyone`, { group });\n throw error;\n }\n const messageId = str(params, \"message\", true);\n const message = await node(ctx).getMessage(link.id, messageId);\n if (!message) throw noMessage(messageId, { group: false, ref: str(params, \"chat\", true) });\n // A waiting text of mine is cancelled; one the outbox already handed to the link may be out, so the engine deletes it\n // for everyone instead, and `everyone` says so.\n const { everyone } = node(ctx).deleteMessage({ linkId: link.id, messageId });\n if (purge) await purgeMessage(ctx, message);\n return { chat: link.id, messageId, deleted: messageId, everyone, ...purged };\n }),\n /** A chat's or a group's (`group:<id>`, or its name) message, as the app's details show it; a group's said `No chat`. */\n async \"chat.details\"(ctx, params) {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const messageId = str(params, \"message\", true);\n const details = await node(ctx).messageDetails({ linkId: target.linkId, messageId });\n if (!details) throw noMessage(messageId, { group: target.group, ref: str(params, \"chat\", true) });\n return details;\n },\n async \"chat.rename\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group rename\", \"<name...>\");\n await node(ctx).renameLink({ linkId: link.id, label: chatName(params, \"name\") ?? \"\" });\n return chatJson(findChat(state(ctx).links, link.id));\n },\n async \"chat.remove\"(ctx, params) {\n const link = chatNotGroup(ctx, params, \"group forget\", \"--yes\");\n if (!bool(params, \"yes\")) throw new CliError(\"confirm\", \"Removing a chat deletes its keys and history on this device; pass --yes (yes: true over the socket) to go on\");\n noCallOn(ctx, link.id, \"remove the chat\");\n if (!bool(params, \"force\")) noRemovalOnItsWay(ctx, [link.id]);\n await node(ctx).removeLink({ linkId: link.id });\n ctx.calls.forgetChat(link.id);\n ctx.groupAuto.forgetChat(link.id);\n await forgetHold(ctx, link.id);\n await closeServicesOf(ctx, link.peerPubKeyZ32);\n return { removed: link.id };\n },\n async \"chat.transport\"(ctx, params) {\n const link = chatNotGroupLink(ctx, params);\n const name = str(params, \"transport\", true);\n const transport = Object.hasOwn(TRANSPORT_NAMES, name) ? TRANSPORT_NAMES[name] : undefined;\n if (!transport) throw new CliError(\"bad_request\", `transport must be one of auto, dht, webrtc, iroh, hyperdht`);\n if (transport === \"dht\") noCallOn(ctx, link.id, \"put the chat on DHT only\");\n else if (transport !== \"auto\") transportOffered(link, transport);\n await node(ctx).setChatTransport({ linkId: link.id, transport });\n // A choice made during a hold (`chat disconnect --hold`) ends it: its time running out takes nothing back.\n await releaseHold(ctx, link.id, \"lifted\", true);\n return chatDetailsJson(findChat(state(ctx).links, link.id));\n },\n /** Reconnects now; a chat held off its direct link (`chat disconnect --hold`) leaves the hold first. */\n async \"chat.connect\"(ctx, params) {\n const link = chatNotGroupLink(ctx, params);\n await releaseHold(ctx, link.id, \"connect\");\n inviteTaken(link);\n dhtOnly(findChat(state(ctx).links, link.id));\n await connectWithin(ctx, link, num(params, \"timeout\", CONNECT_MAX_SECONDS, { min: 1, max: CONNECT_MAX_SECONDS }) * 1000);\n return chatJson(findChat(state(ctx).links, link.id));\n },\n /**\n * Closes the live session; the contact's app may dial again at once. `hold` (minutes): the chat stays off its\n * direct link that long, on the DHT (its \"DHT only\" choice, taken back after); 0 ends a hold now.\n */\n async \"chat.disconnect\"(ctx, params) {\n const link = chatNotGroupLink(ctx, params);\n const minutes = params.hold === undefined ? undefined : num(params, \"hold\", 0, { min: 0, max: HOLD_MAX_MINUTES });\n // `--hold 0` still ends a hold, one an older version put on a waiting invite too.\n if (minutes !== 0) somebodyJoined(link);\n if (minutes === undefined) {\n node(ctx).disconnect({ linkId: link.id });\n return chatJson(findChat(state(ctx).links, link.id));\n }\n if (minutes > 0) noCallOn(ctx, link.id, \"hold the chat\");\n if (minutes === 0) await releaseHold(ctx, link.id, \"lifted\");\n else await holdChat(ctx, link, minutes);\n return { ...chatJson(findChat(state(ctx).links, link.id)), heldUntil: holdOf(ctx, link.id) };\n },\n async \"chat.verify\"(ctx, params) {\n const link = chatOf(ctx, params);\n const code = str(params, \"code\", true).replace(/\\s+/g, \"\").toLowerCase();\n const mine = link.pairing?.code?.replace(/\\s+/g, \"\").toLowerCase();\n if (!mine) throw new CliError(\"unavailable\", \"This chat shows no comparison code yet (it needs a live session)\");\n if (code !== mine) throw new CliError(\"refused\", \"The code does not match the one this side shows: do not trust this chat until you know why\");\n await node(ctx).confirmPair({ linkId: link.id, code: link.pairing!.code! });\n return chatJson(findChat(state(ctx).links, link.id));\n },\n async \"chat.wait\"(ctx, params) {\n const link = chatNotGroupLink(ctx, params);\n const until = oneOf(params, \"until\", [\"live\", \"text\", \"paired\"] as const, \"live\");\n const ms = num(params, \"timeout\", 60, { min: 1, max: 86_400 }) * 1000;\n // The chat as the person named it, as the waiting notice says it (waitNotice.ts): its id read as another chat.\n const ref = str(params, \"chat\", true);\n const view = await waitForState(ctx, (s) => {\n const now = s.links.find((l) => l.id === link.id);\n if (!now) throw new CliError(\"not_found\", `Chat ${link.id} was removed`);\n // Live: a session that exists now, never one remembered from the last run (`isLive`). Paired: the contact's key\n // kept (`peerParticipationKey`) is a fact of the chat, whether the contact is online now or not.\n const ok = until === \"live\" ? isLive(now)\n : until === \"text\" ? now.textDelivery === \"stream\" || now.textDelivery === \"dht\" || now.textDelivery === \"hold\"\n : !!now.peerParticipationKey || !!now.pairingProgress?.peerSeen || now.pairing?.status === \"ready\" || isLive(now);\n return ok ? now : undefined;\n }, ms, `chat ${ref} ${chatState(until).to}`).catch((error: unknown) => { throw until === \"live\" ? liveNeverCame(ctx, link.id, ref, error) : error; });\n return chatJson(view);\n },\n\n async \"group.create\"(ctx, params) {\n // As `group rename` checks it: a name a group cannot have is said here, before anything is made.\n const name = groupNameOf(params);\n // Every member reads it, and a community's anyone who opens its link.\n guardText(name, bool(params, \"force\"), \"group's name\", \"create it\");\n const profile = oneOf(params, \"profile\", [\"community\", \"mesh\"] as const, \"community\");\n const { groupId } = await node(ctx).createGroup({ name, profile });\n let link: string | null = null;\n if (profile === \"community\") ({ link } = await node(ctx).enableGroupLink({ groupId }));\n return withUrl(groupId, link);\n },\n async \"group.join\"(ctx, params) {\n let groupId: string;\n const link = str(params, \"link\", true);\n // What was held before the join: a group already active under the link's id only gets the link noted beside it.\n const before = state(ctx).groups;\n try {\n ({ groupId } = await node(ctx).joinGroupByLink({ link }));\n } catch (error) {\n // Not a link to a group at all: the caller's input, as `invite join` answers a word that is no invite.\n if (error instanceof Error && error.message === \"This is not a link to a group\") throw new CliError(\"bad_request\", error.message);\n throw joinRefused(link, error);\n }\n return letIn(ctx, groupId, link, before.find((g) => g.id === groupId));\n },\n async \"group.list\"(ctx, params) {\n const showSecret = bool(params, \"showSecret\");\n return { groups: state(ctx).groups.map((g) => groupJson(g, showSecret)).sort((a, b) => (b.lastMessageAt ?? 0) - (a.lastMessageAt ?? 0)), autoJoin: ctx.groupAuto.get() };\n },\n /** Invitations over the chats named accepted by the daemon itself (`group auto on --from`); no argument: the setting. */\n async \"group.auto\"(ctx, params) {\n if (params.on === undefined) return { autoJoin: ctx.groupAuto.get() };\n return { autoJoin: ctx.groupAuto.set({ on: bool(params, \"on\"), from: list(params, \"from\") }) };\n },\n async \"group.get\"(ctx, params) {\n return groupJson(groupOf(ctx, params, \"chat show <chat>\"), bool(params, \"showSecret\"));\n },\n async \"group.history\"(ctx, params) {\n const group = groupOf(ctx, params, \"chat history <chat>\");\n return historyOf(ctx, `group:${group.id}`, params, async (page) => {\n const twins = await groupPayTwinsOf(ctx, group, page);\n return (m) => groupMessageJson(m, group, twins.get(m.id));\n });\n },\n async \"group.send\"(ctx, params) {\n const group = groupOf(ctx, params, \"send <chat> [text...]\");\n const text = str(params, \"text\", true);\n checkTextSize(text);\n if (!bool(params, \"force\")) {\n const secret = findSecret(text);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; send it with --force if you mean to`, { kind: secret.kind });\n }\n const mentions = mentionsFor(text, list(params, \"mentions\"), group);\n const replyTo = str(params, \"reply\");\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const card = buttonsCard(params);\n // A kept `group typing --for` ends with the message (the engine says stop with it).\n endTyping(ctx, { groupId: group.id }, false);\n const result = await node(ctx).sendGroupMessage({ groupId: group.id, text, ...(mentions.length ? { mentions } : {}), ...(replyTo ? { replyTo } : {}), ...(card ? { card } : {}) });\n // Not a member (removed, say): refused, and nothing was sent. Anything else by what a bot can do about it.\n // A `--reply` the group lacks says \"group\": the engine's line says \"chat\".\n if (result.error) throw (replyTo && notHere(result.error, replyTo, { group: true, ref: str(params, \"group\", true) }))\n || notInYetError(group, str(params, \"group\", true), result.refused ? new CliError(\"refused\", result.error) : groupSendRefused(result.error));\n const messageId = result.messageId ?? null;\n // `edges`: how many took it so far (none yet is not an error: it goes when one opens). `sent`: whether one did.\n // Before 2026-10-02 `sent` was always true, also for a message no edge had taken.\n const edges = messageId ? (wait === \"sent\" ? await waitForGroupFrame(ctx, group.id, messageId, undefined, ms) : node(ctx).groupTaken({ groupId: group.id, messageId })) : 0;\n return {\n group: group.id, messageId, sent: edges > 0, edges, ...(card ? { buttons: card.id, card } : {}),\n ...(messageId && nobodyElseIn(ctx, group.id) ? { note: \"Nobody else is in this group: nobody gets this message, not even someone who joins later\" } : {}),\n };\n },\n /**\n * WISP 902 § Edits: the whole new text of one of my messages in a group. It shows here at once and goes to the members\n * (a private group's over the edges that are up, the others when theirs open; a community's through the group).\n * `mentions`: members the new text names beyond those the message named. `sent`: whether an edge took it, as for group send.\n */\n async \"group.edit\"(ctx, params) {\n const group = groupOf(ctx, params, \"edit <chat> <message> <text...>\");\n const messageId = str(params, \"message\", true);\n const text = str(params, \"text\", true);\n checkTextSize(text);\n if (!bool(params, \"force\")) {\n const secret = findSecret(text);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; edit with --force if you mean to`, { kind: secret.kind });\n }\n const mentions = mentionsFor(text, list(params, \"mentions\"), group);\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const linkId = `group:${group.id}`;\n const before = (await node(ctx).getMessage(linkId, messageId))?.edit?.seq ?? 0;\n const result = await node(ctx).editMessage({ linkId, messageId, text, ...(mentions.length ? { mentions } : {}) });\n if (result.error) throw await editRefused(ctx, linkId, messageId, { group: true, ref: str(params, \"group\", true) }, result.error, result);\n const message = await node(ctx).getMessage(linkId, messageId);\n const edits = message?.edit?.seq ?? 0;\n // The text the message already has: no edit was made and nothing went. It answered `sent: true` before, for a\n // message never edited, as if an edit had gone.\n if (edits === before) return { group: group.id, messageId, edits, sent: false, edges: 0, unchanged: true };\n // An edit waiting for the pace is not said yet: `--wait sent` waits for that too, then for an edge to take it.\n const edges = !edits ? 0 : wait === \"sent\" ? await waitForGroupFrame(ctx, group.id, messageId, edits, ms)\n : node(ctx).groupTaken({ groupId: group.id, messageId, edit: edits });\n // Before 2026-11-01 `sent` was also true for an edit no edge had taken, once it no longer waited for the pace.\n return { group: group.id, messageId, edits, sent: edges > 0, edges };\n },\n /**\n * WISP 400 § Reactions in a group, which has no receipts: `edges` says how many took it, `sent` whether one did.\n * `wait: sent` (a one-shot's default: what is not said yet leaves with the process) stays until an edge took it.\n */\n async \"group.react\"(ctx, params) {\n const group = groupOf(ctx, params, \"react <chat> <message> <emoji>\");\n const wait = oneOf(params, \"wait\", [\"none\", \"sent\"] as const, ctx.mode === \"one-shot\" ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const ref = str(params, \"group\", true);\n const { n, ...said } = await react(ctx, `group:${group.id}`, params, { group: true, ref }).catch((error) => { throw error instanceof CliError ? notInYetError(group, ref, error) : error; });\n const edges = !n ? 0 : wait === \"sent\" ? await waitForGroupFrame(ctx, group.id, said.messageId, { reaction: n }, ms)\n : node(ctx).groupTaken({ groupId: group.id, messageId: said.messageId, reaction: n });\n return { group: group.id, ...said, sent: edges > 0, edges };\n },\n /**\n * WISP 902 · Group Mesh § Typing: `chat.typing` in a private group, said on the edges that are open (`reached`: to\n * how many members), with the same kinds, status rules, 6 s hold and `for`. A community does not carry typing yet.\n */\n async \"group.typing\"(ctx, params) {\n const group = groupOf(ctx, params, \"typing <chat>\");\n if (group.profile !== \"mesh\") throw new CliError(\"unavailable\", \"A community does not carry typing yet: only a private group does\");\n const typing = !bool(params, \"stop\");\n const { kind, status } = typingWord(params, typing);\n const word = { ...(kind !== \"typing\" ? { kind } : {}), ...(status ? { status } : {}) };\n const seconds = params.for === undefined ? 0 : num(params, \"for\", 0, { min: 1, max: 600 });\n if (!typing && seconds) throw new CliError(\"bad_request\", \"for keeps typing on: not with stop\");\n // Removed or gone, as `group send` says it: `refused`, with the group's reason; not in yet, with the next step.\n if (typing && group.status !== \"active\") throw new CliError(\"refused\", group.statusReason ?? notInYet(group, str(params, \"group\", true)) ?? \"You are not in this group\");\n const target = { groupId: group.id };\n endTyping(ctx, target, false);\n sayTyping(ctx, target, typing, word);\n const until = seconds ? Date.now() + seconds * 1000 : null;\n const kept = seconds ? keepTyping(ctx, target, seconds * 1000, word) : null;\n const reached = (now: GroupView | undefined) => (now ?? group).members.filter((m) => !m.me && m.online && !m.viaHub).length;\n if (kept && ctx.mode === \"one-shot\") await keepOneShot(ctx, target, kept, (s) => reached(s.groups.find((g) => g.id === group.id)) > 0);\n return {\n group: group.id, typing, ...(typing ? { kind } : {}), ...(status ? { status } : {}),\n reached: reached(groupById(ctx, group.id)), sendTyping: settingsOf(ctx).sendTyping !== false, ...(until ? { until } : {}),\n ...(!kept && ctx.mode === \"one-shot\" && { note: typing ? ONE_SHOT_TYPING : ONE_SHOT_TYPING_STOP }),\n };\n },\n async \"group.leave\"(ctx, params) {\n const group = groupOf(ctx, params);\n if (!bool(params, \"yes\")) throw new CliError(\"confirm\", \"Leaving a group deletes its history and files on this device; pass --yes (yes: true over the socket) to go on\");\n const ref = str(params, \"group\", true);\n const { admin } = await node(ctx).leaveGroup({ groupId: group.id }).catch((error) => { throw leaveRefused(group, ref, error); });\n // The member who became the admin, named from the roster read before leaving: the group is gone from the state now.\n const next = admin ? group.members.find((m) => m.key === admin) : undefined;\n return { left: group.id, ...(admin ? { admin: { key: admin, name: next?.nick ?? null } } : {}) };\n },\n async \"group.forget\"(ctx, params) {\n const group = groupOf(ctx, params, \"chat remove <chat> --yes\");\n if (!bool(params, \"yes\")) throw new CliError(\"confirm\", \"Forgetting a group deletes its history on this device; pass --yes (yes: true over the socket) to go on\");\n await node(ctx).forgetGroup({ groupId: group.id });\n return { forgotten: group.id };\n },\n async \"group.accept\"(ctx, params) {\n const group = groupOf(ctx, params);\n // Nothing to accept, said with why: before, a community this profile is in or was removed from answered done, exit\n // 0 (the engine's knock again does nothing there), and a private group \"No invitation to accept\".\n if (!group.invitation) throw new CliError(\"refused\", `${outOf(group) ?? `You are in ${group.name} already`}: there is no invitation to accept`);\n await node(ctx).acceptGroupInvitation({ groupId: group.id });\n return { group: group.id };\n },\n async \"group.decline\"(ctx, params) {\n const group = groupOf(ctx, params);\n await node(ctx).declineGroupInvitation({ groupId: group.id });\n return { group: group.id };\n },\n\n async \"events.replay\"(ctx, params) {\n return { events: ctx.hub.replay(sinceSeq(params, 0)), lastSeq: ctx.hub.lastSeq };\n },\n\n async \"daemon.stop\"(ctx) {\n if (ctx.mode !== \"daemon\" || !ctx.stop) throw new CliError(\"unavailable\", \"No daemon runs this profile\");\n setTimeout(() => ctx.stop!(), 10);\n return { stopping: true, pid: process.pid, ...(ctx.listen && { listen: true }) };\n },\n\n async \"engine.call\"(ctx, params) {\n const method = str(params, \"method\", true);\n if (!ENGINE_METHODS.includes(method) && !ENGINE_READS.includes(method)) throw new CliError(\"not_found\", `The engine has no call ${method}`);\n const raw = params.params;\n if (raw !== undefined && (raw === null || typeof raw !== \"object\" || Array.isArray(raw))) throw new CliError(\"bad_request\", \"params must be an object\");\n const args = raw as Params | undefined;\n // \"Hide my IP from contacts\" (`relayOnly`, WISP 100 § Relay only) is the apps' switch in Settings, Network, not the\n // CLI's yet: its WebRTC chat links (node-datachannel) still check from this machine's own sockets under the relay\n // policy, as its calls did (they are refused while it is on). Nobody turns it on through here until they keep to\n // the relay; turning it off stays possible, for a profile an older CLI (whose engine took any key) turned it on in.\n if (method === \"updateSettings\" && args?.settings && typeof args.settings === \"object\" && \"relayOnly\" in args.settings && (args.settings as Params).relayOnly !== false) {\n throw new CliError(\"bad_request\", \"relayOnly is not a setting yet: Hide my IP from contacts comes in a later release\");\n }\n // Real money moves only on an explicit confirmation of this call (WISP 1100 § Mainnet).\n if (args && \"confirmedReal\" in args && !bool(params, \"confirmReal\")) {\n throw new CliError(\"confirm\", `${method} spends real money: pass --confirm-real (confirmReal: true over the socket) to confirm it`);\n }\n const deletes = DESTRUCTIVE_CALLS.get(method);\n if (deletes && !bool(params, \"yes\")) throw new CliError(\"confirm\", `${method} ${deletes}; pass --yes (yes: true over the socket) to go on`);\n if (method === \"clearProfileData\") return clearProfile(ctx, bool(params, \"force\"));\n // A call given less than it takes failed with JavaScript's own TypeError, or did nothing and answered null.\n const takes = ENGINE_PARAMS[method] ?? READ_PARAMS[method];\n const wrong = (why: string, rawError?: string) => new CliError(\"bad_request\", `${method} takes ${takes || \"no parameters\"}: ${why} (ghostly engine --list --verbose)`, { takes, ...(rawError ? { rawError } : {}) });\n const problem = engineParamsProblem(method, args);\n if (problem) throw wrong(problem);\n // Removing the chat or putting it on DHT only is refused mid-call, as `chat remove` and `chat transport dht` are.\n if (typeof args?.linkId === \"string\") {\n if (method === \"removeLink\") {\n noCallOn(ctx, args.linkId, \"remove the chat\");\n if (!bool(params, \"force\")) noRemovalOnItsWay(ctx, [args.linkId]);\n }\n else if ((method === \"setChatTransport\" && args.transport === \"dht\") || (method === \"setDeliveryMode\" && args.mode === \"dht\")) noCallOn(ctx, args.linkId, \"put the chat on DHT only\");\n }\n if (args && ENGINE_SENDS.has(method) && !bool(params, \"force\")) await guardEngineSend(ctx, method, args);\n if (method === \"getMessages\") return node(ctx).getMessages(str(args ?? {}, \"linkId\", true));\n if (method === \"getState\") return state(ctx);\n // Someone chose the chat on screen: an invite's mark no longer clears it.\n if (method === \"setActiveLink\") inviteShown.get(ctx)?.();\n const target = (node(ctx) as unknown as Record<string, (p?: unknown) => unknown>)[method];\n if (typeof target !== \"function\") throw new CliError(\"not_found\", `The engine has no call ${method}`);\n const removedPeer = method === \"removeLink\" ? state(ctx).links.find((link) => link.id === args?.linkId)?.peerPubKeyZ32 : undefined;\n try {\n const result = (await target.call(node(ctx), args)) ?? null;\n // The chat is gone, as with `chat remove`: auto-answer and auto-join no longer name it, its hold goes with it and its\n // services opened here close.\n if (method === \"removeLink\") {\n ctx.calls.forgetChat(str(args ?? {}, \"linkId\", true));\n ctx.groupAuto.forgetChat(str(args ?? {}, \"linkId\", true));\n await forgetHold(ctx, str(args ?? {}, \"linkId\", true));\n if (removedPeer) await closeServicesOf(ctx, removedPeer);\n }\n // A transport chosen during a hold ends it, as `chat transport` does: its time running out takes nothing back.\n if ((method === \"setChatTransport\" || method === \"setDeliveryMode\") && typeof args?.linkId === \"string\") await releaseHold(ctx, args.linkId, \"lifted\", true);\n return result;\n } catch (error) {\n // A value of the wrong kind (a number for a text, a missing key of a typed object) ends as JavaScript reading what is\n // not there. Not every TypeError: Node's `fetch failed` is the network.\n if (error instanceof TypeError && BAD_VALUE.test(error.message)) throw wrong(\"a parameter of the wrong kind\", error.message);\n throw error;\n }\n },\n};\n\n/**\n * \"Clear all data\": the engine withdraws what it can, stops and empties its stores; the app reloads its page after it.\n * A daemon would go on serving the stopped engine's memory (chats and groups that are gone, new ones that are not\n * kept): it stops once it has answered, and the next command starts on the emptied profile.\n */\nasync function clearProfile(ctx: ApiContext, force: boolean): Promise<{ cleared: { chats: number; groups: number }; stopped?: true }> {\n // Every chat goes at once: mid-call, the call's hang-up had no chat left to cross, as with `chat remove` (`noCallOn`).\n const call = ctx.calls.list()[0];\n if (call) throw new CliError(\"busy\", `A call is on in a chat: hang it up first (ghostly call hangup ${call.chat}), then clear the profile`, { call: call.call });\n const { links, groups } = state(ctx);\n if (!force) noRemovalOnItsWay(ctx, links.map((link) => link.id), true);\n await node(ctx).clearProfileData();\n const cleared = { chats: links.length, groups: groups.length };\n if (ctx.mode !== \"daemon\" || !ctx.stop) return { cleared };\n setTimeout(() => ctx.stop!(), 10);\n return { cleared, stopped: true };\n}\n\n/**\n * The engine's calls that send a text this side writes (a message, a file's caption, a payment's memo, a name others\n * read): `engine.call`\n * runs the secret guard of `send`, `edit` and `forward` on them too (docs/CLI.md § Safety), so a raw call is no way around it. `force: true` (`--force`) sends it.\n */\nconst ENGINE_SENDS: ReadonlySet<string> = new Set([\n \"sendMessage\", \"sendGroupMessage\", \"editMessage\", \"forwardMessages\", \"sendGroupFile\",\n // A payment's memo reaches the contact as a message's text does (`chat pay` and `chat request` guard it too).\n \"sendPayment\", \"requestPayment\", \"requestGroupPayment\", \"askToPay\",\n // The payment sheet's own path (its memo goes out with the token), an invoice's description the payer reads, and a\n // Lightning address's comment its owner reads (agents#1624).\n \"preparePayment\", \"fedimintInvoice\", \"lnurlInvoice\",\n // A group's name, the name contacts see and a file's name, as `group create`, `group rename`, `profile set` and\n // `file send` guard them.\n \"createGroup\", \"renameGroup\", \"updateSettings\", \"sendFile\",\n // The status every contact reads, as `status set` guards it.\n \"setOwnStatus\",\n // A Nostr note or profile, public on relays: the app asks before it is signed (NostrPublishDialog).\n \"nostrDraft\",\n]);\n\nasync function guardEngineSend(ctx: ApiContext, method: string, args: Params): Promise<void> {\n const of = (value: unknown, key: string) => (value && typeof value === \"object\" ? (value as Params)[key] : undefined);\n let texts: unknown = [args.text, args.card, args.caption, args.memo, args.comment, args.name, of(args.settings, \"nick\"), of(args.file, \"name\"), of(args.status, \"text\"), args.content,\n ...(args.fields && typeof args.fields === \"object\" ? Object.values(args.fields) : [])];\n if (method === \"forwardMessages\") {\n // Each id once, and none past the engine's bound, which it refuses before reading any: as `chat.forward` reads them.\n // One id given 50,000 times was read as often, all at once, for the engine's refusal or its one message.\n const ids = Array.isArray(args.messageIds) ? [...new Set(args.messageIds.filter((id): id is string => typeof id === \"string\"))] : [];\n const linkId = args.linkId;\n texts = typeof linkId === \"string\" && linkId && ids.length <= FORWARD_MESSAGES ? await Promise.all(ids.map(async (id) => {\n const message = await node(ctx).getMessage(linkId, id);\n return message && !message.file ? message.text : null;\n })) : [];\n }\n const secret = secretIn(texts);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; call ${method} with --force if you mean to`, { kind: secret.kind });\n}\n\n/**\n * How long `edit`, `react` and `pin` in a 1:1 chat wait for the contact: a one-shot until it confirmed, since what is\n * not said yet leaves with the process; a daemon goes on saying it, so it answers at once unless asked to wait, as a\n * one-shot does on a chat nobody joined yet (`oneShotWaits`).\n */\nfunction confirmWait(ctx: ApiContext, params: Params, chat: string): { wait: \"none\" | \"confirmed\"; ms: number } {\n const wait = oneOf(params, \"wait\", [\"none\", \"confirmed\"] as const, oneShotWaits(ctx, chat) ? \"confirmed\" : \"none\");\n return { wait, ms: num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000 };\n}\n\n/**\n * Reacts to a message of a chat or a group (`group:<id>`): `emoji`, or `remove` for \"\" (WISP 400 § Reactions). In a\n * group, `n` is the reaction's number, for `groupTaken`.\n */\nasync function react(ctx: ApiContext, linkId: string, params: Params, place: RefPlace): Promise<{ messageId: string; emoji: string | null; removed: boolean; n?: number }> {\n const messageId = str(params, \"message\", true);\n const removed = bool(params, \"remove\");\n const emoji = removed ? \"\" : str(params, \"emoji\");\n if (!removed && !emoji) throw new CliError(\"usage\", \"Give one emoji, or --remove to take yours back\");\n const result = await node(ctx).react({ linkId, messageId, emoji: emoji ?? \"\" });\n const gone = result.error ? notHere(result.error, messageId, place) : undefined;\n if (gone) throw gone;\n if (result.error) throw new CliError(result.refused ? \"refused\" : /not in this (?:chat|group)|No reaction of yours/.test(result.error) ? \"not_found\" : \"bad_request\", result.error);\n return { messageId, emoji: emoji || null, removed, ...(result.n ? { n: result.n } : {}) };\n}\n\n/**\n * What `typing` says: a kind, and a status a bot writes. The contact's app would cut a long status and drop one with\n * a link; here that is an error instead, so the bot learns what the contact will (not) see.\n */\nfunction typingWord(params: Params, typing: boolean): { kind: TypingKind; status?: string } {\n const kind = oneOf(params, \"kind\", TYPING_KINDS, \"typing\");\n const raw = str(params, \"status\");\n if (!typing && (params.kind !== undefined || raw !== undefined)) throw new CliError(\"bad_request\", \"kind and status go with a start, not with stop\");\n if (raw === undefined) return { kind };\n const oneLine = raw.replace(/\\s+/g, \" \").trim();\n if ([...oneLine].length > TYPING_STATUS_MAX) throw new CliError(\"bad_request\", `status: at most ${TYPING_STATUS_MAX} characters`);\n const status = sanitizeTypingStatus(oneLine);\n if (!status) throw new CliError(\"bad_request\", \"status: plain text, with no link or markup\");\n return { kind, status };\n}\n\n/**\n * A group message the engine did not send, by what a bot can do about it: a `--reply` to a message this group does not\n * have is `not_found` (exit 3), as `group react`, `group edit` and `pin` answer for one; out of the group (removed,\n * left, a forked history) is `refused`: it will not go later either. Anything else may go on a later try\n * (`unavailable`): the epoch's key is still on its way. All three were `unavailable` (exit 1) before.\n */\nexport function groupSendRefused(error: string): CliError {\n if (/not in this chat|cannot be replied to/.test(error)) return new CliError(\"not_found\", error);\n if (/^You (were removed from|left|are no longer in) this group$|Membership changes are halted/.test(error)) return new CliError(\"refused\", error);\n return new CliError(\"unavailable\", error);\n}\n\n/** The engine's admin who may not leave: the app's words say \"make someone the admin\", which names no command here. */\nconst ADMIN_ALONE = \"You are the admin and nobody else in the group is online to take over. Try again when a member is, or make someone the admin first.\";\n\n/**\n * `group leave` the engine refused, said with the CLI's next step: an invitation not joined yet answered \"Group not\n * found\" of a group `group show` lists (its way out is `group decline`), and an admin alone online \"make someone the\n * admin\", the app's words. The code stays the engine's.\n */\nfunction leaveRefused(group: GroupView, ref: string, error: unknown): unknown {\n if (!(error instanceof Error)) return error;\n const shown = shellWord(ref, group.id);\n if (error.message === ADMIN_ALONE) return new CliError(\"engine\", `You are the admin and nobody else in ${groupCalled(group)} is online to take over: try again when a member is, or make one the admin first (ghostly group admin ${shown} <member key>)`);\n const yet = error.message === \"Group not found\" ? notInYet(group, ref, true) : undefined;\n return yet ? new CliError(\"engine\", yet) : error;\n}\n\n/**\n * `group join` the engine refused for a group held here under the link's id, in the app's words (\"Delete it from this\n * device\", its menu item), said with the CLI's command. The code stays the engine's. \"Answer it first\" comes only for\n * an invitation taken back (a live one is kept and the link goes on beside it), which `group accept` refuses: its way\n * out is `group decline`.\n */\n/**\n * The link `group join` takes, read before a one-shot opens the profile (`refuseBeforeStart`): one that names no group,\n * a private one's or a community's, is refused as the engine's `joinByLink` refuses it with the same two decoders.\n */\nfunction groupLinkShape(params: Params): void {\n const link = str(params, \"link\", true);\n if (!decodeCommunityLink(link) && !decodeGroupEntryLink(link)) throw new CliError(\"bad_request\", \"This is not a link to a group\");\n}\n\nfunction joinRefused(link: string, error: unknown): unknown {\n if (!(error instanceof Error)) return error;\n const id = (decodeCommunityLink(link) ?? decodeGroupEntryLink(link))?.g ?? \"<group>\";\n if (error.message === \"You are out of this group and its history is still here. Delete it from this device to join with a link.\") {\n return new CliError(\"engine\", `You are out of this group and its history is still here: ghostly group forget ${id} --yes deletes it from this device, then join with the link`);\n }\n if (error.message === \"You have an invitation to this group. Answer it first.\") {\n return new CliError(\"engine\", `Its invitation to this group was taken back: ghostly group decline ${id} drops it, then join with the link`);\n }\n return error;\n}\n\n/**\n * The chat a command about a chat's own connection names (`chat connect`, `disconnect`, `transport`, `wait`): a group's\n * name says a group has none of its own, as `chat show` names `group show`. It read \"(ghostly chat list)\", a list that\n * never has the group.\n */\nfunction chatNotGroupLink(ctx: ApiContext, params: Params) {\n return notAGroup(ctx, params, () => chatOf(ctx, params), (shown) => `it connects through its members' chats, with no transport of its own (ghostly group show ${shown})`);\n}\n\n/**\n * A chat command given a group's id, prefix or name: `not_found` that says it is a group, with `hint`: the group\n * command that takes it (`react` on a group, where `group react` is meant), or what to do where none does. `group:<id>`,\n * the form `pin` and `saved` take, is that group too (it read \"No chat\" before). A name no chat and no group has stays\n * the chat's error.\n */\nfunction notAGroup<T>(ctx: ApiContext, params: Params, chat: () => T, hint: (shown: string, id: string) => string): T {\n try { return chat(); } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"not_found\") throw error;\n const ref = str(params, \"chat\", true);\n const named = groupPrefixed(ref) ?? ref;\n let group: GroupView;\n try { group = findGroup(state(ctx).groups, named); } catch { throw error; }\n const shown = shellWord(named, group.id);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat: ${hint(shown, group.id)}`, { group: group.id });\n }\n}\n\n/** The chat a chat command with a group twin names: a group's name says so, with `command`, the twin (see `notAGroup`). */\nfunction chatNotGroup(ctx: ApiContext, params: Params, command: string, rest = \"\") {\n return notAGroup(ctx, params, () => chatOf(ctx, params), (shown) => `ghostly ${command} ${shown}${rest ? ` ${rest}` : \"\"}`);\n}\n\n/**\n * An edit the engine refused. A message that is not in the chat or group at all is `not_found` (exit 3), said as every\n * message id is (`noMessage`); before, a mistyped or lost id read \"Only your own text messages can be edited\"\n * (`refused`, exit 1), as if the message were someone else's. Whether it is there is the engine's answer (`missing`)\n * once it looked for it: read again here, an id no message goes by read the chat's whole history a second time (0.7 s\n * at 100,000 messages). Only a refusal before it looked (a chat that cannot edit, a group I am not in) looks here.\n */\nasync function editRefused(ctx: ApiContext, linkId: string, ref: string, place: RefPlace, error: string, result: { refused?: boolean; missing?: boolean }): Promise<CliError> {\n if (!result.refused) return new CliError(\"unavailable\", error);\n if (result.missing ?? !(await messageOf(ctx, linkId, ref))) return noMessage(ref, place);\n return new CliError(\"refused\", editRefusalWords(error, ref, place));\n}\n\n/**\n * The engine's refusal of an edit with what to run instead: it named none, so a bot that hit the edit cap had a sentence\n * and exit 1 to go on. Matched by the engine's exact words (`editMessage`, `GroupEdits.edit`); any other sentence, or\n * one these no longer match, stays the engine's.\n */\nfunction editRefusalWords(error: string, ref: string, place: RefPlace): string {\n const chat = shellWord(place.ref, place.group ? \"<group>\" : \"<chat>\"), id = shellWord(ref, \"<message>\");\n const send = `ghostly ${place.group ? \"group send\" : \"send\"} ${chat}`;\n // A contact's message (or another member's), or one of mine that is no text: neither is edited, a reply answers it.\n if (error === \"Only your own text messages can be edited\") return `${error}: to answer this one, reply to it (${send} --reply ${id} <text>)`;\n const most = /^(This message was edited \\d+ times, the most one takes)\\.$/.exec(error);\n if (most) return `${most[1]}: send the new text as a new message (${send} <text>); ghostly message delete ${chat} ${id} --everyone takes the old one away`;\n // The text alone decides it (`isJoinNotice`: \"👋 <name> joined\", whole): other first words make it a text.\n if (error === \"An edit cannot read as a join notice.\") return \"An edit cannot read as a join notice (\\\"👋 … joined\\\"): change its first words\";\n return error;\n}\n\n/**\n * `message delete --everyone` given no message of mine. It said \"No message … of yours\" for all of them, as if one of\n * mine deleted already were the contact's: another's message says whose it is (in a chat, with the delete that takes\n * it off this device), one of mine deleted already says so (the chat's deleted ids), and any other is not here.\n */\nfunction deleteNotMine(ctx: ApiContext, target: { linkId: string; group: boolean }, ref: string, theirs: StoredMessage | undefined, place: RefPlace, purge: boolean): CliError {\n if (theirs && target.group) return new CliError(\"not_found\", `${JSON.stringify(ref)} is another member's message: only its author deletes a group's message, for everyone`);\n if (theirs) return new CliError(\"not_found\", `${JSON.stringify(ref)} is the contact's message: only your own messages are deleted for everyone (ghostly message delete ${shellWord(place.ref, \"<chat>\")} ${shellWord(theirs.id, \"<message>\")}${purge ? \" --purge\" : \"\"} deletes it on this device)`);\n const deleted = !target.group && node(ctx).deletedIdsOf(target.linkId).includes(ref);\n return noMessage(ref, place, deleted ? { tail: \": it was deleted already\" } : {});\n}\n\n/**\n * About the longest ASCII text, and edit, the DHT packet carries once sealed and signed: within the 256 bytes, the\n * envelope's authentication (and an edit's element) takes the rest. The edge moves by a byte or two with the chat (the\n * envelope's sequence, the edit's number), so the words say \"about\"; `dhtBudgetWords.test.ts` sends both sizes on two\n * paired daemons.\n */\nconst DHT_TEXT_FITS = 248, DHT_EDIT_FITS = 214;\n\n/**\n * The engine's refusal of a text or an edit within 256 bytes that the DHT packet cannot carry (`DHT_PACKET_BUDGET`,\n * \"Text and authentication exceed the DHT packet budget\"), said as the apps and `dhtOnlyWait` say it: too long for the\n * DHT, about how much fits, and what ends it, by whose choice keeps the chat on the DHT only (this side's hold: when\n * it ends, and the command that ends it now). Any other error as is.\n */\nfunction dhtTooLong(ctx: ApiContext, asked: LinkView, error: string, kind: \"text\" | \"edit\", ref: string): string {\n if (error !== DHT_PACKET_BUDGET) return error;\n // Read again: the contact's choice may have come with the envelope the engine read since the chat was looked up.\n const link = state(ctx).links.find((l) => l.id === asked.id) ?? asked;\n const mine = link.deliveryMode === \"dht\", theirs = link.dhtDelivery?.peerMode === \"dht\";\n const held = mine ? holdEnds(ctx, link.id) : null, chosen = mine && held === null;\n const fits = kind === \"text\" ? `a text fits about ${DHT_TEXT_FITS} bytes there` : `an edit fits about ${DHT_EDIT_FITS} bytes there`;\n const act = kind === \"text\" ? \"send it\" : \"make the edit\";\n const switchBack = `ghostly chat transport ${shellWord(ref, \"<chat>\")} auto`;\n const who = chosen && theirs ? `you and the contact keep this chat on the DHT only: ${act} once both choose a live transport (${switchBack}), or shorten it`\n : chosen ? `this chat is on the DHT only: ${act} once you choose a live transport (${switchBack}), or shorten it`\n : theirs ? `the contact keeps this chat on the DHT only: ${act} once they choose a live transport, or shorten it`\n : held !== null ? `${heldWords(held, ref, act)}, or shorten it`\n : `shorten it, or ${act} once the chat is live`;\n return `Too long for the DHT (${fits} once sealed): ${who}`;\n}\n\n/**\n * The engine's \"That message is not in this chat\" (\", or takes no reaction\", \", or cannot be pinned\", \", or cannot be\n * replied to\") for the message `id`, said as `noMessage` says it, with that reason kept; undefined for any other error.\n * The engine says \"chat\" in a group for a reply and a save: `place` says which it is.\n */\nfunction notHere(error: string, id: string, place: RefPlace): CliError | undefined {\n const said = /^That message is not in this (?:chat|group)(?:, or (.+))?$/.exec(error);\n return said ? noMessage(id, place, said[1] ? { tail: `, or it ${said[1]}` } : {}) : undefined;\n}\n\n/** The chat link's own wait for a contact (`GhostLink.connect`): `chat connect --timeout` waits at most that long. */\nconst CONNECT_MAX_SECONDS = 90;\n\n/**\n * `chat connect`, waiting at most `ms` for the contact; the link's dial goes on behind a shorter wait. Timed out (here,\n * or by the link's own 90 s), it says what happens next: before, it waited a fixed 90 s and ended \"Timed out connecting\n * to the peer\", with no next step.\n */\nasync function connectWithin(ctx: ApiContext, link: LinkView, ms: number): Promise<void> {\n const dial = node(ctx).connect({ linkId: link.id });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<\"late\">((resolve) => { timer = setTimeout(() => resolve(\"late\"), ms); });\n try {\n if ((await Promise.race([dial, late])) !== \"late\") return;\n } catch (error) {\n // A DHT only learned while it dialled (the contact's, read from the DHT up to 30 s later) is said as before the dial.\n if (asCliError(error).code !== \"timeout\") {\n dhtOnly(findChat(state(ctx).links, link.id));\n const away = contactAway(error);\n if (away) throw new CliError(\"unavailable\", `${away}. ${connectNext(ctx, link)}`, { chat: link.id, reason: (error as Error).message });\n throw error;\n }\n } finally { clearTimeout(timer); }\n throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: ${notLiveYet(ctx, link)}. ${connectNext(ctx, link)}`, { chat: link.id });\n}\n\n/**\n * How long after a daemon's start a chat with no attempt ended yet reads as still resuming: with many chats, the start\n * brings them back a few at a time, over minutes.\n */\nconst RESUMING_MS = 5 * 60_000;\n\n/**\n * Why a daemon's `chat connect` timed out, as the chat reads at the end. No attempt of this run ended yet\n * (`lastAttempt` null) while the daemon just started, or while the contact reads online: the chat is still coming\n * back, nobody failed to answer. It said \"the contact did not answer\" right after a `daemon restart`, with the\n * contact online. A one-shot always just started: it keeps the words it had.\n */\nfunction notLiveYet(ctx: ApiContext, link: LinkView): string {\n const now = state(ctx).links.find((l) => l.id === link.id) ?? link;\n if (ctx.mode !== \"daemon\" || now.liveAttempt) return \"the contact did not answer\";\n if (process.uptime() * 1000 < RESUMING_MS) return \"the chat is still resuming after the daemon's start, and no attempt to reach the contact has ended yet\";\n return now.peerOnline ? \"your contact's app reads online, and no attempt to reach it has ended yet\" : \"the contact did not answer\";\n}\n\n/** What happens after a `chat connect` the contact did not answer: the daemon dials again by itself, a one-shot does not. */\nfunction connectNext(ctx: ApiContext, link: LinkView): string {\n const shown = /^[\\w.:-]+$/.test(link.label ?? \"\") ? link.label! : link.id;\n return ctx.mode === \"one-shot\"\n ? \"Try again later, or keep this profile online with `ghostly daemon --detach`: it reconnects by itself\"\n : `It reconnects by itself while this profile is online; ghostly chat wait ${shown} --until live waits for it`;\n}\n\n/**\n * A dial that ended because the contact's app is not there: the link's own \"Could not connect to the peer\", or\n * HyperDHT's errors as the app's errorText says them (closed, or asleep or frozen). They answered as they came, without\n * the next step; HyperDHT's as `engine`, \"PEER_NOT_FOUND: Peer not found\", as if this side had failed.\n */\nfunction contactAway(error: unknown): string | undefined {\n const message = error instanceof Error ? error.message : \"\";\n const reason = /^Could not connect to the peer(?:: ([\\s\\S]*))?$/.exec(message);\n const native = reason ? reason[1] ?? \"\" : message;\n if (/^PEER_NOT_FOUND: /.test(native)) return \"Your contact's app isn't reachable on HyperDHT: it may be closed\";\n if (/^(?:PEER_CONNECTION_FAILED|BAD_HOLEPUNCH_REPLY|HOLEPUNCH_[A-Z_]+): /.test(native)) return \"Your contact's app isn't answering on HyperDHT: it may be asleep or frozen\";\n return reason ? \"The contact did not answer\" : undefined;\n}\n\nasync function saveMark(ctx: ApiContext, params: Params, remove: boolean) {\n const target = chatOrGroup(ctx, str(params, \"chat\", true)), messageId = str(params, \"message\", true);\n const result = await node(ctx).saveMessage({ linkId: target.linkId, messageId, remove });\n // An id that names no message of the chat or group (a typo): said as pin and message details say it, in a group too\n // (the engine's line says \"chat\"); an unsave's with where the saved ids are.\n const where = target.group ? \"group\" : \"chat\";\n if (result.error && /not in this chat/.test(result.error)) {\n throw remove ? new CliError(\"not_found\", `No saved message ${JSON.stringify(messageId)} in this ${where} (ghostly saved list shows the saved ones)`)\n : noMessage(messageId, { group: target.group, ref: str(params, \"chat\", true) });\n }\n if (result.error) throw new CliError(\"bad_request\", result.error);\n return { [target.group ? \"group\" : \"chat\"]: target.id, messageId, saved: !remove };\n}\n\n/**\n * A page of a chat's or a group's history: only that page is read from the store (the newest, those before `before`,\n * or the oldest after `after`), so a long chat's is as quick as a short one's. `linesOf`: how the page's messages are\n * printed, once the page is read.\n */\ntype LinesOf = (page: readonly StoredMessage[]) => Promise<(message: StoredMessage) => MessageJson>;\nasync function historyOf(ctx: ApiContext, chat: string, params: Params, linesOf: LinesOf = async () => messageJson) {\n const limit = num(params, \"limit\", 50, { min: 1, max: 10_000, whole: true });\n const bound = (side: \"before\" | \"after\"): string | number | undefined => {\n const value = params[side] ?? undefined;\n if (value !== undefined && typeof value !== \"number\" && typeof value !== \"string\") throw new CliError(\"bad_request\", `${side} must be a timestamp or a message id`);\n return value;\n };\n const before = bound(\"before\"), after = bound(\"after\");\n const page = await node(ctx).messagePage({ linkId: chat, limit, before, ...(after !== undefined && { after }) }).catch((error: unknown) => {\n const missing = [before, after].find((id) => error instanceof Error && error.message === `No message ${id}`);\n if (missing === undefined) throw error;\n const group = chat.startsWith(\"group:\");\n throw noMessage(String(missing), { group, ref: str(params, group ? \"group\" : \"chat\", true) });\n });\n const originals = await originalsNow(ctx, chat, page.messages);\n const json = await linesOf(page.messages);\n return { messages: page.messages.map((m) => quoteChecked(json(m), m, originals)), more: page.more };\n}\n\n/**\n * The payment lines of a group's history page that are twins of a payment note's line (`groupPayTwins`), as the app\n * tells them. A note whose line is not on the page is read as its one row, as the originals of replies are.\n */\nasync function groupPayTwinsOf(ctx: ApiContext, group: GroupView, page: readonly StoredMessage[]): Promise<ReadonlyMap<string, string>> {\n const rows = page.filter((m) => m.paymentId && !m.groupPay);\n if (!rows.length) return new Map();\n const payments = state(ctx).payments ?? {};\n const notes = new Map(page.flatMap((m) => (m.groupPay ? [[m.groupPay.id, m.groupPay] as const] : [])));\n for (const id of new Set(rows.map((m) => groupPayNoteId(m.paymentId!, payments[m.paymentId!])))) {\n if (notes.has(id)) continue;\n const note = (await node(ctx).getMessage(`group:${group.id}`, groupPayLineId(id)))?.groupPay;\n if (note) notes.set(note.id, note);\n }\n return groupPayTwins(rows, notes, payments, group);\n}\n\n/** Past this many originals outside a page, its history is read once instead of row by row. */\nconst ORIGINAL_READS = 32;\n\n/** Each original a page's replies name, by its id: its row as it is now, or undefined when it is gone. */\ntype Originals = ReadonlyMap<string, StoredMessage | undefined>;\n\n/**\n * The originals a page's replies found here when they came, as they are now: gone (deleted on this device, or for\n * everyone by their author: WISP 400 § Delete for everyone), or the row, edited since or not. Each is looked for in the\n * page, else read as its one row, one at a time (a burst of reads stalls fake-indexeddb's scheduler); `whole` is the\n * chat's whole history when it was read already. Before, such a reply still said `found`, with the original's text.\n */\nasync function originalsNow(ctx: ApiContext, chat: string, page: readonly StoredMessage[], whole: readonly StoredMessage[] = page): Promise<Originals> {\n const here = new Map(whole.map((m) => [m.id, m]));\n const named = [...new Set(page.flatMap((m) => (m.replyTo?.messageId ? [m.replyTo.messageId] : [])))];\n const asked = named.filter((id) => !here.has(id));\n // Many (a long page of answers to old messages): the history once is cheaper than a burst of row reads.\n if (whole === page && asked.length > ORIGINAL_READS) return originalsNow(ctx, chat, page, await node(ctx).getMessages(chat));\n const originals = new Map<string, StoredMessage | undefined>(named.flatMap((id) => (here.has(id) ? [[id, here.get(id)]] : [])));\n // The whole history read: what is not in it is gone.\n for (const id of asked) originals.set(id, whole === page ? await node(ctx).getMessage(chat, id) : undefined);\n return originals;\n}\n\n/**\n * A reply's quote as the apps show it (`quoteFor`): an original gone reads \"Original message deleted\", not found and\n * none of its text; one edited since the reply quotes its text as it reads now. A button press keeps the question as\n * it was answered (WISP 406 · Message Buttons), and a card's or a file's line stays the one the reply carries.\n */\nfunction quoteChecked(json: MessageJson, message: StoredMessage, originals: Originals): MessageJson {\n const id = message.replyTo?.messageId;\n if (!json.replyTo || !id || !originals.has(id)) return json;\n const original = originals.get(id);\n if (!original) return { ...json, replyTo: { ...json.replyTo, snippet: \"\", found: false, deleted: true } };\n if (!original.edit || json.replyTo.button || original.card || original.file) return json;\n return { ...json, replyTo: { ...json.replyTo, snippet: replySnippet(original.text) } };\n}\n\n/**\n * Each method's check of its own words, the one its handler makes first: none needs the profile. A one-shot makes it\n * before the profile opens (main.ts `session`): a target that is no invoice, a token or mint URL that is none, or a word\n * that is no group link started every saved chat to be refused (with 10 chats, 20 relay requests and 0.4 s more).\n */\nconst SHAPES: Record<string, (params: Params) => unknown> = {\n \"pay\": payShape, \"wallet.redeem\": tokenShape, \"wallet.mint.add\": mintUrlShape, \"group.join\": groupLinkShape, \"service.add\": serviceShape,\n};\n\n/** Throws what `method` answers `params` whose shape it refuses, with no profile open; nothing for any other. */\nexport async function refuseBeforeStart(method: string, params: Params): Promise<void> {\n if (Object.hasOwn(SHAPES, method)) await SHAPES[method](params);\n}\n\nexport { findChat, findGroup, startNamedChats } from \"./apiKit\";\nexport { identityProvider } from \"./identities\";\nexport type { ApiContext } from \"./apiKit\";\nexport const API_METHODS: readonly string[] = Object.keys(METHODS);\n\n/**\n * Runs one method of the API: one the table lists itself (`constructor`, which every object has, is none). `call`: who\n * asked, from a daemon's connection (`host.ts`).\n */\nexport async function callApi(ctx: ApiContext, method: string, params: unknown = {}, call?: CallScope): Promise<unknown> {\n const run = Object.hasOwn(METHODS, method) ? METHODS[method] : undefined;\n if (!run) throw new CliError(\"not_found\", `No method ${method}`);\n if (params === null || typeof params !== \"object\" || Array.isArray(params)) throw new CliError(\"bad_request\", \"params must be an object\");\n return run(ctx, await withStoredIds(ctx, params as Params), call);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,gBAAgB,oBAAoB;AAC1C,IAAM,0BAAU,IAAI,QAA6C;AAMjE,SAAS,UAAU,KAA0C;CAC3D,IAAI,MAAM,QAAQ,IAAI,GAAG;CACzB,IAAI,CAAC,KAAK,QAAQ,IAAI,KAAM,sBAAM,IAAI,IAAI,CAAE;CAC5C,OAAO;AACT;AAEA,IAAM,SAAS,WAAyB,a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