@ghostlytools/cli 1.10.2 → 1.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/assets/{api-DcE4KylM.js → api-DgS7f5TT.js} +2 -2
- package/dist/assets/{api-EUGHGnRz.js → api-DkcMOWLX.js} +44 -19
- package/dist/assets/api-DkcMOWLX.js.map +1 -0
- package/dist/assets/{apiKit-CJVp_crp.js → apiKit-D6Oj-vFx.js} +27 -11
- package/dist/assets/apiKit-D6Oj-vFx.js.map +1 -0
- package/dist/assets/{apps-C54T_MOT.js → apps-B22SeD6T.js} +3 -3
- package/dist/assets/{apps-C54T_MOT.js.map → apps-B22SeD6T.js.map} +1 -1
- package/dist/assets/{apps-C-KbyLCa.js → apps-DgALLHzS.js} +1 -1
- package/dist/assets/{arkade-BmxJTa65.js → arkade-D5cPr_dV.js} +2 -2
- package/dist/assets/{arkade-BmxJTa65.js.map → arkade-D5cPr_dV.js.map} +1 -1
- package/dist/assets/{backup-C0Plp-DF.js → backup-DndsW2uX.js} +1 -1
- package/dist/assets/{backup-BxSH5BZG.js → backup-dzJLzg-k.js} +6 -6
- package/dist/assets/{backup-BxSH5BZG.js.map → backup-dzJLzg-k.js.map} +1 -1
- package/dist/assets/{blobFiles-BnjN_Vrz.js → blobFiles-XZ9PEXYy.js} +2 -2
- package/dist/assets/{blobFiles-BnjN_Vrz.js.map → blobFiles-XZ9PEXYy.js.map} +1 -1
- package/dist/assets/{buttons-B-ZJYdo0.js → buttons-ByKT_vP8.js} +4 -4
- package/dist/assets/{buttons-B-ZJYdo0.js.map → buttons-ByKT_vP8.js.map} +1 -1
- package/dist/assets/buttons-TVCNj280.js +2 -0
- package/dist/assets/{client-CDa87uYD.js → client-q7dVOtYb.js} +10 -4
- package/dist/assets/client-q7dVOtYb.js.map +1 -0
- package/dist/assets/{codec-D45W1L8n.js → codec-HD6iOn_D.js} +2 -2
- package/dist/assets/{codec-D45W1L8n.js.map → codec-HD6iOn_D.js.map} +1 -1
- package/dist/assets/{envelope-C3yFCQa-.js → envelope-C-0tfbOG.js} +2 -2
- package/dist/assets/{envelope-C3yFCQa-.js.map → envelope-C-0tfbOG.js.map} +1 -1
- package/dist/assets/{fileBytes-DjBYYyXT.js → fileBytes-BABGEF13.js} +2 -2
- package/dist/assets/{fileBytes-DjBYYyXT.js.map → fileBytes-BABGEF13.js.map} +1 -1
- package/dist/assets/{fileBytes-DMzrIdCu.js → fileBytes-CQQK2uOh.js} +1 -1
- package/dist/assets/{fileBytes-Douk1yOp.js → fileBytes-DqnfKIkj.js} +2 -2
- package/dist/assets/{fileBytes-Douk1yOp.js.map → fileBytes-DqnfKIkj.js.map} +1 -1
- package/dist/assets/fileBytesIdb-BtXATa7j.js +2 -0
- package/dist/assets/{fileBytesIdb-CkClu9YI.js → fileBytesIdb-DrXmDUSy.js} +2 -2
- package/dist/assets/{fileBytesIdb-CkClu9YI.js.map → fileBytesIdb-DrXmDUSy.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-WryQuOgK.js → fileBytesOpfs-udKCzcLe.js} +6 -9
- package/dist/assets/{fileBytesOpfs-WryQuOgK.js.map → fileBytesOpfs-udKCzcLe.js.map} +1 -1
- package/dist/assets/{fixedHosts-C6nCHjOa.js → fixedHosts-CN3CsslV.js} +7 -8
- package/dist/assets/fixedHosts-CN3CsslV.js.map +1 -0
- package/dist/assets/{groupFiles-DYopNE57.js → groupFiles-BFv9K_za.js} +256 -110
- package/dist/assets/groupFiles-BFv9K_za.js.map +1 -0
- package/dist/assets/{host-G5seUwaI.js → host-C-wwtVt2.js} +378 -60
- package/dist/assets/host-C-wwtVt2.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-B_uHjg_r.js → hyperdhtRelay-B9EQTm_M.js} +2 -2
- package/dist/assets/{hyperdhtRelay-B_uHjg_r.js.map → hyperdhtRelay-B9EQTm_M.js.map} +1 -1
- package/dist/assets/{irohWeb-C-2oslSU.js → irohWeb-o0H_NlCF.js} +2 -2
- package/dist/assets/{irohWeb-C-2oslSU.js.map → irohWeb-o0H_NlCF.js.map} +1 -1
- package/dist/assets/{main-Dk--nD7X.js → main-CLUIPy4d.js} +49 -30
- package/dist/assets/main-CLUIPy4d.js.map +1 -0
- package/dist/assets/{mainline-HPlVrl8R.js → mainline-B2qmNsib.js} +155 -3
- package/dist/assets/mainline-B2qmNsib.js.map +1 -0
- package/dist/assets/{networkReason-CfpO9ayz.js → networkReason-BEl-DDWd.js} +4 -4
- package/dist/assets/{networkReason-CfpO9ayz.js.map → networkReason-BEl-DDWd.js.map} +1 -1
- package/dist/assets/{nwc-BY7BPttn.js → nwc-BNkhjJHN.js} +3 -3
- package/dist/assets/{nwc-BY7BPttn.js.map → nwc-BNkhjJHN.js.map} +1 -1
- package/dist/assets/{nwcProvider-CfpbNUf7.js → nwcProvider-CvaRJdHT.js} +2 -2
- package/dist/assets/{nwcProvider-CfpbNUf7.js.map → nwcProvider-CvaRJdHT.js.map} +1 -1
- package/dist/assets/{ownDid-DJFZM2cV.js → ownDid-D67KNdJq.js} +3 -2
- package/dist/assets/ownDid-D67KNdJq.js.map +1 -0
- package/dist/assets/{profiles-DKmZGXp6.js → profiles-QDB7V_Qt.js} +7 -5
- package/dist/assets/profiles-QDB7V_Qt.js.map +1 -0
- package/dist/assets/{registry-BUm4cAzV.js → registry-BKkSnpjL.js} +126 -19
- package/dist/assets/registry-BKkSnpjL.js.map +1 -0
- package/dist/assets/{registry-CAzrtV0_.js → registry-DN5a8Ul6.js} +1 -1
- package/dist/assets/{resolve-CDD4X68j.js → resolve-DhpAggDP.js} +24 -5
- package/dist/assets/resolve-DhpAggDP.js.map +1 -0
- package/dist/assets/{server-DcOsgYDU.js → server-7w2O5wsv.js} +956 -277
- package/dist/assets/server-7w2O5wsv.js.map +1 -0
- package/dist/assets/{src-D31D1_oY.js → src-BZkY6N3J.js} +909 -198
- package/dist/assets/src-BZkY6N3J.js.map +1 -0
- package/dist/assets/{sshForges-DerRwMf3.js → sshForges-Cxjt3c51.js} +2 -2
- package/dist/assets/{sshForges-DerRwMf3.js.map → sshForges-Cxjt3c51.js.map} +1 -1
- package/dist/assets/{translate-C-sj0VJe.js → translate-v8wF1GcF.js} +2 -2
- package/dist/assets/{translate-C-sj0VJe.js.map → translate-v8wF1GcF.js.map} +1 -1
- package/dist/assets/{usdt-DwHqp625.js → usdt-63gYjM5E.js} +7 -4
- package/dist/assets/usdt-63gYjM5E.js.map +1 -0
- package/dist/assets/{waitNotice-D52RWbV4.js → waitNotice-Ce3YCinu.js} +27 -5
- package/dist/assets/waitNotice-Ce3YCinu.js.map +1 -0
- package/dist/assets/{words-Db9WgatT.js → words-PUnyO4ph.js} +4 -4
- package/dist/assets/words-PUnyO4ph.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-EUGHGnRz.js.map +0 -1
- package/dist/assets/apiKit-CJVp_crp.js.map +0 -1
- package/dist/assets/buttons-DA3wZfG0.js +0 -2
- package/dist/assets/client-CDa87uYD.js.map +0 -1
- package/dist/assets/fileBytesIdb-CD5Uv490.js +0 -2
- package/dist/assets/fixedHosts-C6nCHjOa.js.map +0 -1
- package/dist/assets/groupFiles-DYopNE57.js.map +0 -1
- package/dist/assets/host-G5seUwaI.js.map +0 -1
- package/dist/assets/main-Dk--nD7X.js.map +0 -1
- package/dist/assets/mainline-HPlVrl8R.js.map +0 -1
- package/dist/assets/ownDid-DJFZM2cV.js.map +0 -1
- package/dist/assets/profiles-DKmZGXp6.js.map +0 -1
- package/dist/assets/registry-BUm4cAzV.js.map +0 -1
- package/dist/assets/resolve-CDD4X68j.js.map +0 -1
- package/dist/assets/server-DcOsgYDU.js.map +0 -1
- package/dist/assets/src-D31D1_oY.js.map +0 -1
- package/dist/assets/usdt-DwHqp625.js.map +0 -1
- package/dist/assets/waitNotice-D52RWbV4.js.map +0 -1
- package/dist/assets/words-Db9WgatT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"api-EUGHGnRz.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","../../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/** The whole sound in `path`, in memory. */\nexport async function decodeSound(path: string): Promise<Sound> {\n const collector = new Collector();\n await streamSound(path, collector);\n return collector.sound();\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\n/** The sound in a file this module decodes itself, or null for a kind it leaves to ffmpeg. */\nexport async function decodeBytes(bytes: Uint8Array): Promise<Sound | null> {\n const collector = new Collector();\n return (await streamBytes(bytes, collector)) ? collector.sound() : null;\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/** Feeds `sink` the sound of a kind this module decodes itself; false for a kind it leaves to ffmpeg. */\nasync function streamBytes(bytes: Uint8Array, sink: SoundSink): Promise<boolean> {\n const kind = kindOf(bytes);\n if (kind === \"wav\") { streamWav(bytes, sink); return true; }\n if (kind === \"mp3\") { await streamMp3(slices(bytes, MP3_PIECE), sink); return true; }\n return kind ? streamOpusOf(kind, bytes, sink) : false;\n}\n\n/** As `streamBytes`, reading the file only as far as its decoder goes; a kind left to ffmpeg is not read past its head. */\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\nfunction* slices(bytes: Uint8Array, piece: number): Generator<Uint8Array> {\n for (let at = 0; at < bytes.length; at += piece) yield bytes.subarray(at, at + piece);\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/** PCM (8, 16, 24 or 32 bit) or float (32 or 64 bit) WAV. A data chunk whose size is unknown (a pipe) runs to the end. */\nexport function decodeWav(bytes: Uint8Array): Sound {\n const collector = new Collector();\n streamWav(bytes, collector);\n return collector.sound();\n}\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 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\nfunction streamWav(bytes: Uint8Array, sink: SoundSink): void {\n const header = wavHeader(bytes);\n if (!header) throw new NotSound(\"a WAV without sound\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const read = sampleReader(view, header.format, header.bits);\n if (!read) throw new Error(`a WAV in a format not read here (${header.format}, ${header.bits} bit)`);\n sink.start(header.sampleRate);\n pushWavFrames(view, header.from, Math.min(bytes.length, header.to), header.channels, header.bits / 8, read, sink);\n}\n\n/** As `streamWav`, reading the file a piece of frames at a time until the sink wants no more. */\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\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) {\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)) 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\") {\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 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\nexport async function decodeOpus(stream: OpusStream): Promise<Sound> {\n const collector = new Collector();\n await streamOpus(stream, collector);\n return collector.sound();\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\nexport async function decodeMp3(bytes: Uint8Array): Promise<Sound> {\n const collector = new Collector();\n await streamMp3(slices(bytes, MP3_PIECE), collector);\n return collector.sound();\n}\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 reject(new Error(error.code === \"ENOENT\" ? \"no decoder here for this kind of audio (install ffmpeg to read it)\" : `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 } from \"node:path\";\nimport { GROUP_FILE_LIMITS, LIMITS, NO_PICTURE_METADATA, NO_VIDEO_METADATA, PLAYABLE_AUDIO, VOICE_LIMITS, baseMime, claimedTime, parseVoiceMeta, randomBytes, readImageMeta, sanitizeFileName, sanitizeMime, toBase64Url, voiceDownloadName, withoutPictureMetadata, withoutVideoMetadata, type VoiceMeta } from \"@ghostly/core\";\nimport { FILE_BYTES_STEP, fileBytes, fileBytesOf } 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 { 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, list, node, num, oneOf, sentAt, state, str, waitForState, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { groupSendRefused } from \"./api\";\nimport { CliError } from \"./errors\";\nimport { guardText } from \"./secretGuard\";\nimport { endTyping } from \"./typing\";\nimport { measureVoice } from \"./voicePeaks\";\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 \".webm\": \"audio/webm\", \".mp4\": \"video/mp4\", \".mov\": \"video/quicktime\",\n};\n\nexport function mimeOf(path: string, given?: string): string {\n return sanitizeMime(given ?? TYPES[extname(path).toLowerCase()] ?? \"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 return (await findMessage(ctx, stored.linkId, (m) => m.file?.id === stored.id))?.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 */\nasync function findMessage(ctx: ApiContext, linkId: string, test: (m: StoredMessage) => boolean): 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 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) => findChatOrGroup(state(ctx).links, state(ctx).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 groupId = groupOfFile(fileId, state(ctx).groups.map((g) => g.id));\n if (groupId) {\n const named = params.chat === undefined ? undefined : chatOrGroupOf(ctx, params);\n if (named && !(\"group\" in named && named.group.id === groupId)) throw new CliError(\"not_found\", `No file ${fileId} in this ${\"group\" in named ? \"group\" : \"chat\"}`);\n return { linkId: `group:${groupId}`, where: { group: groupId } };\n }\n const link = params.chat === undefined\n ? state(ctx).links.find((l) => fileId.startsWith(`${l.id}-in-`) || fileId.startsWith(`${l.id}-out-`))\n : chatOf(ctx, params);\n if (!link) throw new CliError(\"not_found\", `No file ${fileId}`);\n if (!fileId.startsWith(`${link.id}-`)) throw new CliError(\"not_found\", `No file ${fileId} in this chat`);\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, mp4, mpeg, aac, m4a or wav)`);\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 or an MP4 or\n * QuickTime video without its metadata (where it was taken or recorded, the device, the time), before its size is read\n * and its digest computed. One whose metadata cannot be removed is refused, never sent as it was. A voice note goes as it is.\n */\nasync function sendable(path: string, mime: string, voice: VoiceMeta | undefined): Promise<Blob> {\n const source = await openAsBlob(path, { type: mime });\n if (voice) return source;\n try {\n return await withoutPictureMetadata(source, mime) ?? await withoutVideoMetadata(source, mime) ?? source;\n } catch (error) {\n if (error instanceof Error && (error.message === NO_PICTURE_METADATA || error.message === NO_VIDEO_METADATA)) throw new CliError(\"refused\", error.message);\n throw error;\n }\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, picked: number) {\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\"));\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 new CliError(\"not_found\", \"That message is not in this group, or 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 sendable(path, mime, voice);\n const size = source.size;\n const image = voice ? undefined : await readImageMeta(source, mime);\n const fileId = groupFileId(group.id, \"out\");\n const file: MessageFile = { id: fileId, name: sanitizeFileName(str(params, \"name\") ?? basename(path)), size, mime, ...(voice ? { voice } : {}), ...(image ? { image } : {}) };\n const timestamp = Date.now();\n const bytes = await fileBytes();\n const digest = await bytes.stage(fileId, source);\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\nexport const FILE_METHODS: Record<string, Method> = {\n async \"file.send\"(ctx, params) {\n // The contact (or every member) reads its name as a message's text (docs/CLI.md § Safety).\n guardText(str(params, \"name\"), bool(params, \"force\"), \"file's name\", \"send it\");\n const target = chatOrGroupOf(ctx, params);\n const path = resolve(str(params, \"path\", true));\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: none.\n const wait = oneOf(params, \"wait\", \"group\" in target ? [\"none\"] as const : [\"none\", \"sent\"] as const, !(\"group\" in target) && ctx.mode === \"one-shot\" ? \"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, info.size);\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 if (!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\"));\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 new CliError(\"not_found\", \"That message is not in this chat, or cannot be replied to\");\n }\n const { voice, warning } = await voiceOf(params, path, mime, info.size);\n const source = await sendable(path, mime, voice);\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 readImageMeta(source, mime);\n const wireId = toBase64Url(randomBytes(12));\n const file: MessageFile = { id: `${link.id}-out-${wireId}`, name: sanitizeFileName(str(params, \"name\") ?? basename(path)), size: source.size, mime, ...(voice ? { voice } : {}), ...(image ? { image } : {}) };\n const timestamp = sentAt();\n const bytes = await fileBytes();\n const digest = await bytes.stage(file.id, source);\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 if (wait === \"sent\") await FILE_METHODS[\"file.wait\"](ctx, { chat: link.id, file: file.id, timeout: seconds });\n return { chat: link.id, messageId: `me_${timestamp}`, file: { id: file.id, name: file.name, size: file.size, mime: file.mime, ...(voice ? { voice: true } : {}), ...(image ? { image } : {}) }, ...(warning ? { warning } : {}) };\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.\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 } : waitingGroupFile(f);\n return kept ? [[f.id, kept] as const] : [];\n }));\n if (\"group\" in target) {\n const kept = await keptOf(`group:${target.group.id}`);\n return { group: target.group.id, files: filesOf(await node(ctx).groupMessages({ groupId: target.group.id }), (id) => withWaitingFor(views[id] ?? kept.get(id))) };\n }\n const kept = await keptOf(target.link.id);\n return { chat: target.link.id, files: filesOf(await node(ctx).getMessages(target.link.id), (id) => withWaitingFor(views[id] ?? kept.get(id))) };\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 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 await node(ctx).fileAction({ linkId, fileId, action });\n return { ...where, file: fileId, action, transfer: state(ctx).transfers[fileId] ?? null };\n },\n\n /**\n * Until a transfer ends: done answers, failed is an `engine` error with the transfer's words (and whether `file\n * resend` can go on). A file whose transfer this run has not seen answers from the file store.\n */\n async \"file.wait\"(ctx, params) {\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 new CliError(\"not_found\", `No file ${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`).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 });\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\") {\n const name = (stored ?? await fileStore.get(fileId).catch(() => undefined))?.metadata?.name ?? \"The file\";\n throw new CliError(\"confirm\", `${name} (${megabytes(transfer.size)}) waits for you to take it: ghostly file accept ${fileId} (or file decline)`, { file: fileId, ...where, size: transfer.size, stage: \"asking\" });\n }\n return { ...where, file: fileId, state: \"done\", size: transfer.size };\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 if (bool(params, \"wait\")) await FILE_METHODS[\"file.wait\"](ctx, { file: fileId, timeout: params.timeout });\n const stored = await fileStore.get(fileId);\n if (!stored?.metadata) throw new CliError(\"not_found\", `No file ${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 const transfer = stored.direction === \"out\" ? undefined : state(ctx).transfers[fileId] ?? 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 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 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 // 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 if (there?.isDirectory()) return new CliError(\"bad_request\", `${target} is a folder: name a file, or use --dir ${target} (dir over the socket)`);\n if ((there && !force) || code === \"EEXIST\") return new CliError(\"confirm\", `${target} exists: pass --force (force: true over the socket) to replace it`);\n };\n let target = named;\n for (let n = 2, refused = await taken(target); refused; n += 1, refused = await taken(target)) {\n if (!free || refused.code !== \"confirm\" || n > 1000) throw refused;\n target = `${stem} (${n})${ext}`;\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 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 throw error;\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 for (let n = 2; !complete; n += 1) 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\" && n <= 1000) { target = `${stem} (${n})${ext}`; continue; }\n throw refused ?? error;\n }\n // A contact chose its bytes and its name (`.command`, `.lnk`): marked as downloaded. One sent from here needs none.\n if (stored.direction !== \"out\") await markDownloaded(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 { 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, node, num, oneOf, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError, asCliError } from \"./errors\";\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. */\ninterface Pace { last: number; next?: Record<string, unknown>; 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.\n */\nfunction guardSecrets(fields: unknown, params: Params, verb: string): void {\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, ctx.mode === \"one-shot\" ? \"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 });\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 const merged = withRun(mergeCard(base, { ...patch, ...(kind === \"task\" && { updatedAt: Date.now() }) }), 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, ctx.mode === \"one-shot\" ? \"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 const due = last + CARD_UPDATE_GAP_MS - Date.now();\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 queued = true;\n if (!pace.timer) pace.flushed = new Promise<void>((resolve) => {\n const send = () => {\n const next = pace.next;\n clearTimeout(pace.timer);\n pace.timer = undefined; pace.next = undefined; pace.flush = undefined; pace.last = Date.now();\n void (next ? editCard(ctx, target, message.id, next as unknown as StatusCard, text) : 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 }),\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 && ctx.mode === \"one-shot\" ? \"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 // 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\nconst timers = new WeakMap<ApiContext, Map<string, ReturnType<typeof setTimeout>>>();\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\nfunction timersOf(ctx: ApiContext): Map<string, ReturnType<typeof setTimeout>> {\n let map = timers.get(ctx);\n if (!map) timers.set(ctx, (map = new Map()));\n return map;\n}\n\nfunction schedule(ctx: ApiContext, linkId: string, until: number): void {\n const map = timersOf(ctx);\n clearTimeout(map.get(linkId));\n const timer = setTimeout(() => {\n map.delete(linkId);\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 }, 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 map.set(linkId, timer);\n}\n\n/** When the chat's hold ends, or null. */\nexport function holdOf(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 async function holdChat(ctx: ApiContext, link: LinkView, minutes: number): Promise<number> {\n const holds = readHolds(ctx);\n if (link.deliveryMode === \"dht\" && !holds[link.id]) throw new CliError(\"refused\", \"This chat is on DHT only already, by its own choice: chat transport auto leaves it\");\n if (!link.profile) throw new CliError(\"unavailable\", \"A chat of the older protocol has no DHT only\");\n const until = Date.now() + minutes * 60_000;\n if (link.deliveryMode !== \"dht\") {\n try { await node(ctx).setChatTransport({ linkId: link.id, transport: \"dht\" }); } catch (error) {\n throw new CliError(\"unavailable\", error instanceof Error ? error.message : String(error));\n }\n }\n holds[link.id] = { until, since: holds[link.id]?.since ?? Date.now() };\n writeHolds(ctx, holds);\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 * 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 async function releaseHold(ctx: ApiContext, linkId: string, reason: \"expired\" | \"connect\" | \"lifted\", chosen = false): Promise<boolean> {\n const holds = readHolds(ctx);\n if (!holds[linkId]) return false;\n clearTimeout(timersOf(ctx).get(linkId));\n timersOf(ctx).delete(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 delete holds[linkId];\n writeHolds(ctx, holds);\n ctx.hub.emit(\"chat.released\", `chat.released:${linkId}:${Date.now()}`, { chat: linkId, reason });\n return true;\n}\n\n/** At start: holds whose time is up end now, the others are timed again. */\nexport function resumeHolds(ctx: ApiContext): void {\n for (const [linkId, hold] of Object.entries(readHolds(ctx))) schedule(ctx, linkId, hold.until);\n}\n","import type { GroupView, LinkView, MessageFile, 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 lastMessageAt: number;\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, waiting, ready, failed. */\n pairing: 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\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,\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 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}\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 };\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 */\nexport function groupMessageJson(message: StoredMessage, group: Pick<GroupView, \"members\" | \"formerNames\"> | undefined): MessageJson {\n const json = 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 * 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,\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 invitation: group.invitation ? { chat: group.invitation.linkId, accepted: group.invitation.accepted, viaLink: !!group.invitation.viaLink, stage: group.invitation.stage ?? null } : 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 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_NAME_LENGTH, NO_PICTURE_METADATA, groupName, sanitizeAvatar, stripPictureMetadata } from \"@ghostly/core\";\nimport type { GroupView } from \"@ghostly/browser/shared/types\";\nimport { bool, cleanName, findOwnNamedChat, groupOf, node, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { CliError, localFileError } from \"./errors\";\nimport { guardText } from \"./secretGuard\";\nimport { groupJson } from \"./views\";\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).\n */\nexport function findMember(group: GroupView, ref: string, myName?: string) {\n const lower = ref.toLowerCase();\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) return matches[0];\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 if (!checked) throw new CliError(\"bad_request\", `A picture is 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): resize it first`);\n return checked;\n}\n\nasync function picture(params: Params): Promise<string | null> {\n if (bool(params, \"clear\")) return null;\n return pictureFrom(str(params, \"path\", true));\n}\n\n/** The member `params.member` names in `group`, this profile's own name said to be it. */\nconst member = (ctx: ApiContext, group: GroupView, params: Params) => findMember(group, str(params, \"member\", true), state(ctx).settings.nick);\n\nconst view = (ctx: ApiContext, id: string, params: Params) => groupJson(state(ctx).groups.find((g) => g.id === id) ?? 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 = groupOf(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 = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\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 = groupOf(ctx, params);\n await node(ctx).removeGroupMember({ groupId: group.id, key: member(ctx, group, params).key });\n return view(ctx, group.id, params);\n },\n async \"group.admin\"(ctx, params) {\n const group = groupOf(ctx, params);\n await node(ctx).makeGroupAdmin({ groupId: group.id, key: member(ctx, group, params).key });\n return view(ctx, group.id, params);\n },\n async \"group.hub\"(ctx, params) {\n const group = groupOf(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).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 = groupOf(ctx, params, \"chat rename <chat> <name...>\");\n const clean = cleanName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH);\n const name = clean && groupName(clean);\n if (!name) throw new CliError(\"bad_request\", `A group's name is 1 to ${MAX_GROUP_NAME_LENGTH} characters on one line`);\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 = groupOf(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 = groupOf(ctx, params);\n if (params.on === false) {\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, ...(bool(params, \"reset\") ? { reset: true } : {}) });\n return { group: group.id, link };\n },\n async \"group.picture\"(ctx, params) {\n const group = groupOf(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 \"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 type { IdentityProofProvider, IdentitySigner, SignerField, 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, findOwnNamedChat, node, num, 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\nfunction provider(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} proofs need a browser window: make them 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 = provider(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 const seconds = num(params, \"timeout\", 300, { min: 5, max: 3600 });\n const signal = AbortSignal.timeout(seconds * 1000);\n const proof = await signer.run({\n values, signal,\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()}`, { provider: p.id, url }); },\n onProgress: (message) => { ctx.hub.emit(\"identity.progress\", `identity.progress:${Date.now()}`, { provider: p.id, message }); },\n onApproval: (request) => {\n if (request) ctx.hub.emitLive(\"identity.approval\", `identity.approval:${Date.now()}`, { provider: p.id, ...(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 return await node(ctx).completeIdentityProof({ draftId, evidence: await session.sign(identityStatement(binding)) });\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\"), an engine failure to a bot.\n if (!signal.aborted || 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 = provider(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 link = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n const id = str(params, \"id\", true);\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).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 = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\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, type ClientRequest, type ClientResponse, type LocalFetch } from \"@ghostly/core\";\nimport { bool, chatOf, findOwnNamedChat, node, num, 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 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/** 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\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 */\nexport async function openServiceServer(send: ServiceSend, port = 0): Promise<OpenedService> {\n const name = `${randomBytes(16).toString(\"hex\")}.localhost`;\n const token = randomBytes(32).toString(\"hex\");\n const cookies = new Set<string>();\n let host = \"\";\n const server = createServer((request, response) => {\n if (request.headers.host?.toLowerCase() !== host) 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); });\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 host = `${name}:${(server.address() as AddressInfo).port}`;\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>): 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)) 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) ?? []), OPENED_SERVICE_CSP];\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 if (!state(ctx).services.some((s) => s.id === serviceId)) throw new CliError(\"not_found\", `No service ${JSON.stringify(serviceId)} (ghostly service list)`);\n return serviceId;\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 */\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 target = str(params, \"target\", true);\n let url: URL;\n try { url = new URL(target); } catch { throw new CliError(\"bad_request\", `Not a URL: ${target}`); }\n const here = LOOPBACK.has(url.hostname) || /^127\\.\\d+\\.\\d+\\.\\d+$/.test(url.hostname);\n if (!here) throw new CliError(\"refused\", \"Only a web app on this machine (127.0.0.1, localhost) can be shared\");\n // The engine's own check of the target (core http.ts `parseLocalTarget`), first: a query, a fragment, a user and\n // password or a scheme other than http(s) is the person's input to fix, `bad_request` naming it. Thrown by the engine,\n // they were plain errors, `engine` (exit 1): \"the engine failed\" (agents#894).\n try { parseLocalTarget(target); } catch (error) {\n const said = error instanceof Error ? error.message : String(error);\n // Named without its user, password, query and fragment: the parts refused here can hold a secret (a token).\n const shown = `${url.protocol}//${url.host}${url.pathname}`;\n throw new CliError(/^Only services on this machine/.test(said) ? \"refused\" : \"bad_request\", `${said}: ${shown}`);\n }\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: str(params, \"name\", true), 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 serviceId = serviceOf(ctx, params);\n await node(ctx).setServiceEnabled({ serviceId, enabled: !bool(params, \"off\") });\n return { service: serviceId, enabled: !bool(params, \"off\") };\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 = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n const shared = !bool(params, \"off\");\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\", \"An opened service lives in the daemon: start `ghostly daemon --detach` first\");\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 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 // 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 await new Promise<void>((resolve) => {\n entry.server.close(() => resolve());\n entry.server.closeAllConnections();\n });\n return { closed: key };\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, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { APP_PERMISSIONS, appCardUrl, appRef, isAppRef, isAppUrl, type AppPermission } from \"@ghostly/core\";\nimport { list, str, type ApiContext, type Method } from \"./apiKit\";\nimport { checkedBundle } from \"./apps\";\nimport { CliError } 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` is 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\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}\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/** 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 const unknown = grant.filter((p) => !(APP_PERMISSIONS as readonly string[]).includes(p));\n if (unknown.length) throw new CliError(\"bad_request\", `grant takes ${GRANTABLE.join(\" or \")}, not ${unknown.map((p) => JSON.stringify(p)).join(\", \")}`);\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 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 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).\n const cardUrl = appCardUrl(given ?? url ?? m.sources?.[0]);\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 return { unserved: app.ref, apps: next.length, ...offered(ctx, next) };\n },\n};\n","import type { AppFrameEvent } from \"@ghostly/core\";\nimport { servedApps } 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 /** Per chat: chat app id to reference, of the apps served when the contact last opened one there. */\n const known = new Map<string, Map<string, string>>();\n let count = 0;\n const learn = (chat: string): Map<string, string> => {\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 { /* not a paired chat: it has no app ids */ }\n }\n known.set(chat, ids);\n return ids;\n };\n return hub.onAppFrame((chat: string, frame: AppFrameEvent) => {\n // An open reads the served list again, so an app served or unserved since is taken or left from its next open.\n const app = (\"o\" in frame && frame.o === \"open\" ? learn(chat) : known.get(chat) ?? learn(chat)).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, 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 const sent: AppCard = { kind: \"app\", id: appCardId(app.ref), ref: app.ref, digest: app.digest, sequence: app.sequence, title: app.title, version: app.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","import { generateMnemonic } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\nimport type { WalletNetwork } from \"@ghostly/core\";\nimport type { EngineState, NetworkWalletsView, PaymentView, WalletInstanceView, WalletOffer, WalletType } from \"@ghostly/browser/shared/types\";\nimport { bool, chatOf, findOwnNamedChat, inviteTaken, node, num, oneOf, sentAt, state, str, type ApiContext, type Method, type Params } from \"./apiKit\";\nimport { paymentNetwork } from \"@ghostly/browser/engine/paymentAdapters/walletInstances\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport { ADDRESS_TYPES, CHAT_METHODS, PAY_METHODS, WALLET_TYPES } from \"./words\";\nimport { findSecret, secretWords } from \"./secretGuard\";\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 if (unknown) throw new CliError(\"bad_request\", `${provider} takes no --value ${unknown}: ${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 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 = str(params, \"card\");\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/** One wallet of the deck with its balance, in its own unit. Never a key, a phrase or a token. */\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 balance = card?.balance ?? null; status = card?.status ?? null; error = card?.error ?? null;\n break;\n }\n case \"arkade\": balance = view?.ark?.balance ?? null; address = view?.ark?.address ?? null; error = view?.ark?.error ?? null; break;\n case \"bark\": balance = view?.bark?.balance ?? null; error = view?.bark?.error ?? null; break;\n case \"spark\": balance = view?.spark?.balance ?? null; 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\": balance = view?.fedimint?.balance ?? null; error = view?.fedimint?.error ?? null; break;\n case \"usdt\": balance = view?.usdt?.balance ?? null; 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\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, 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\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/**\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.\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 [/^The faucet did not pay: This wallet has no test mint\\b/, \"unavailable\"],\n [/^Ghostly cannot ask this wallet's faucet by itself\\b/, \"unavailable\"],\n];\n\n/**\n * `chat pay` or `chat request` refused for want of a Cashu wallet of that network at all: the engine says the wallet\n * is short of sats, or that no mint could make an invoice, and names nothing to do. `refused` with the command that\n * makes one, as a 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): unknown {\n if ((state(ctx).wallet.wallets ?? []).some((w) => w.type === \"cashu\" && w.network === n)) return error;\n const name = n === \"mainnet\" ? \"Mainnet\" : \"Testnet\";\n return new CliError(\"refused\", `You have no ${name} Cashu wallet: ghostly wallet create cashu${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)$/;\n\nfunction walletRefusal(error: unknown): unknown {\n if (!(error instanceof Error) || error instanceof CliError) return error;\n const code = WALLET_REFUSALS.find(([pattern]) => pattern.test(error.message))?.[1];\n return code ? new CliError(code, error.message) : error;\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 return node(ctx).walletTestCoins({ type, network: \"testnet\", ...(card ? { card } : {}) });\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 return { network: n, history: (netView(state(ctx), n)?.history ?? []).slice(0, 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 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\") return { type, network: n, address: await node(ctx).bitcoinReceiveAddress({ network: 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 new CliError(\"unavailable\", `No ${type} wallet with an address on ${n}`);\n return { type, network: n, address };\n },\n\n async \"wallet.redeem\"(ctx, params) {\n return node(ctx).walletReceiveToken({ token: str(params, \"token\", true).trim() });\n },\n\n async \"wallet.mint.add\"(ctx, params) {\n return node(ctx).walletAddMint({ url: str(params, \"url\", true), ...(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 // 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 = str(params, \"card\");\n let invoice = text.replace(/^lightning:/i, \"\");\n let n: WalletNetwork;\n let note: string | undefined;\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 // 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 : findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n if (chat) inviteTaken(chat);\n if (isInvoice(text)) {\n // Which wallet pays is named, never guessed from the invoice: test mints issue `lnbc` invoices too, and a\n // guess must never be what makes real money move. Testnet unless `network` says mainnet.\n n = network(params);\n } else if (isLnurl(text)) {\n n = network(params);\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 } else throw new CliError(\"bad_request\", \"Not a Lightning invoice, Lightning address or LNURL\");\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 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 return { network: n, amount: quote.amount, feeReserve: quote.feeReserve, source: (quote as { source?: string }).source ?? quote.mint, paid: paid.paid };\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 = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\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 /** A request in a chat (the payment sheet's Request): the contact's app pays it. */\n async \"chat.request\"(ctx, params) {\n const memo = memoOf(params, \"request\");\n const link = chatOf(ctx, params);\n const amount = num(params, \"amount\", 0, { min: 1 });\n if (!amount) throw new CliError(\"bad_request\", \"amount is required\");\n const method = params.method === undefined ? undefined : oneOf(params, \"method\", PAY_METHODS, \"cashu\");\n const rail = params.rail === undefined ? undefined : oneOf(params, \"rail\", [\"cashu\", \"lightning\"] as const, \"cashu\");\n await federationsOpen(ctx);\n const n = network(params);\n const { paymentId } = await node(ctx).requestPayment({\n linkId: link.id, amount, timestamp: sentAt(), network: n,\n ...(memo ? { memo } : {}), ...(method ? { method } : {}), ...(rail ? { rail } : {}), ...(str(params, \"card\") ? { card: str(params, \"card\") } : {}),\n }).catch((error: unknown) => { throw (!method || method === \"cashu\") && error instanceof Error && NO_MINT.test(error.message) ? noWalletOf(ctx, n, error) : error; });\n return { chat: link.id, paymentId };\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 link = findOwnNamedChat(state(ctx).links, str(params, \"chat\", true), state(ctx).groups);\n const paymentId = str(params, \"payment\", true);\n const request = state(ctx).payments[paymentId];\n if (!request || request.linkId !== link.id || request.kind !== \"request\") throw new CliError(\"not_found\", `No request ${paymentId} in this chat`);\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) } : {}), ...(str(params, \"card\") ? { card: str(params, \"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 const on = 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 chat = params.chat === undefined ? null : chatOf(ctx, params).id;\n const payments = Object.values(state(ctx).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 link = chatOf(ctx, params);\n if (state(ctx).payments[str(params, \"payment\", true)]?.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 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, groupName, inviteLink, LIMITS, MAX_GROUP_NAME_LENGTH, 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 { 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 {\n bool, chatOf, chatOrGroup, cleanName, dhtOnly, findChat, findGroup, groupOf, groupPrefixed, inviteTaken, list, messageOf, node, num, oneOf, state, str, transportOffered, waitForState,\n type ApiContext, type Method, type Params,\n} from \"./apiKit\";\nimport { FILE_METHODS } from \"./files\";\nimport { checkShownName } from \"./profiles\";\nimport { waitForConfirmed, waitForEdit, waitForGroupFrame, waitForMessage, waitForRemoval } from \"./waits\";\nimport { STATUS_CARD_METHODS, secretIn } from \"./statusCards\";\nimport { BUTTON_METHODS, buttonsCard, pressable } from \"./buttons\";\nimport { HOLD_MAX_MINUTES, holdChat, holdOf, releaseHold } from \"./holds\";\nimport { endTyping, keepOneShot, keepTyping, sayTyping } from \"./typing\";\nimport { GROUP_ADMIN_METHODS, noMember } from \"./groupAdmin\";\nimport { withStoredIds } from \"./turnRefs\";\nimport { IDENTITY_METHODS } from \"./identities\";\nimport { X401_METHODS } from \"./x401\";\nimport { SERVICE_METHODS } 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 { WALLET_METHODS } from \"./wallets\";\nimport { TRANSPORT_NAMES } from \"./words\";\nimport { chatDetailsJson, chatJson, chatMessageJson, groupJson, groupMessageJson, 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 (anyone who reads it can join) and a pending chat's invite code (whoever reads it can take the chat)\n * are `<hidden>`.\n */\nexport function hideStateSecrets<T extends { settings: Settings; groups?: { entryLink?: string }[]; links?: { inviteCode?: string }[] }>(state: T) {\n return {\n ...state,\n settings: redactSettings(state.settings),\n ...(state.groups ? { groups: state.groups.map((g) => (g.entryLink ? { ...g, entryLink: \"<hidden>\" } : g)) } : {}),\n ...(state.links ? { links: state.links.map((l) => (l.inviteCode ? { ...l, inviteCode: \"<hidden>\" } : l)) } : {}),\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. */\nexport const SETTABLE: Record<string, \"strings\" | \"string\" | \"boolean\" | \"ice\"> = {\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\",\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 (`cleanName`): 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.\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 = cleanName(value, CHAT_NAME_LENGTH);\n if (clean === undefined) throw new CliError(\"bad_request\", `A chat's name is up to ${CHAT_NAME_LENGTH} characters on one line`);\n if (!clean) throw new CliError(\"bad_request\", `A chat's name needs a character that shows (an empty name gives back the contact's own)`);\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/** 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// ---------- methods ----------\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 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 },\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 async \"profile.get\"(ctx) {\n const { settings } = state(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(state(ctx).settings, 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(state(ctx).settings), ...(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: 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 - a.lastMessageAt || 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, (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 const wait = oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, \"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) throw /not in this chat|cannot be replied to/.test(result.error) ? new CliError(\"not_found\", result.error) : new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n if (!result.messageId) throw new CliError(\"bad_request\", \"Nothing to send\");\n let message = await node(ctx).getMessage(link.id, result.messageId);\n if (wait !== \"none\") message = await waitForMessage(ctx, link.id, result.messageId, wait, ms);\n return { chat: link.id, messageId: result.messageId, delivery: message?.delivery ?? null, ...(card ? { buttons: card.id, card, pressable: pressable(link) } : {}) };\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 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 = oneOf(params, \"wait\", [\"none\", \"confirmed\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).editMessage({ linkId: link.id, messageId, text });\n if (result.error) throw editRefused(await messageOf(ctx, link.id, messageId), messageId, \"chat\", result.error, result.refused);\n const id = result.messageId ?? messageId;\n let message = await node(ctx).getMessage(link.id, id);\n if (wait === \"confirmed\" && message?.edit?.pending) message = await waitForEdit(ctx, link.id, id, ms);\n return { chat: link.id, messageId: id, edits: message?.edit?.seq ?? 0, confirmed: !!message && !message.edit?.pending };\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 return {\n chat: link.id, typing, ...(typing ? { kind } : {}), ...(status ? { status } : {}),\n live: open(state(ctx)), sendTyping: state(ctx).settings.sendTyping !== false, ...(until ? { until } : {}),\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);\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);\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 return { chat: link.id, ...result, confirmed: !pending(node(ctx).chatUnconfirmed({ linkId: link.id })) };\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.\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\");\n const { wait, ms } = confirmWait(ctx, params);\n const result = await node(ctx).pinMessage({ linkId: target.linkId, ...(messageId && { messageId }), remove });\n if (result.error) throw 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 if (target.group) return { group: target.id, messageId: remove ? null : messageId, removed: remove };\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 return { chat: target.id, messageId: remove ? null : messageId, removed: remove, confirmed: !pending(node(ctx).chatUnconfirmed({ linkId: target.linkId })) };\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 from = chatOrGroup(ctx, str(params, \"chat\", true));\n const messageIds = 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 const to = list(params, \"to\").map((ref) => chatOrGroup(ctx, ref));\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 new CliError(\"not_found\", `No message ${id} in this ${from.group ? \"group\" : \"chat\"}`);\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 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 = 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 if (wait === \"sent\") for (const [i, result] of out.entries()) for (const messageId of result.messageIds) {\n if (to[i]!.group) { await waitForGroupFrame(ctx, to[i]!.id, messageId, undefined, ms); continue; }\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);\n }\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 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 if (!message) throw new CliError(\"not_found\", `No message ${messageId} in this chat`);\n // Before, both answered done and nothing was sent: the engine sends again whatever id it is given.\n if (message.sender !== \"me\") throw new CliError(\"not_found\", `No message ${messageId} of yours in this chat: 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 async \"chat.delete\"(ctx, params) {\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 const message = await messageOf(ctx, target.linkId, ref, (m) => m.sender === \"me\");\n if (!message) throw new CliError(\"not_found\", `No message ${ref} of yours in this ${target.group ? \"group\" : \"chat\"}: only your own messages are deleted for everyone`);\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 // `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\" ? await waitForGroupFrame(ctx, target.id, message.id, e, ms) : 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 };\n }\n if (wait === \"confirmed\") await 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 }) };\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 const ref = str(params, \"message\") ?? \"<message>\";\n const link = chatNotGroup(ctx, params, \"message delete\", `${/^[\\w.:<>-]+$/.test(ref) ? ref : JSON.stringify(ref)} --everyone`);\n const messageId = str(params, \"message\", true);\n if (!(await node(ctx).getMessage(link.id, messageId))) throw new CliError(\"not_found\", `No message ${messageId} in this chat`);\n await node(ctx).deleteMessage({ linkId: link.id, messageId });\n return { chat: link.id, messageId, deleted: messageId, everyone: false };\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 details = await node(ctx).messageDetails({ linkId: target.linkId, messageId: str(params, \"message\", true) });\n if (!details) throw new CliError(\"not_found\", `No message ${String(params.message)} in this ${target.group ? \"group\" : \"chat\"}`);\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 await node(ctx).removeLink({ linkId: link.id });\n ctx.calls.forgetChat(link.id);\n return { removed: link.id };\n },\n async \"chat.transport\"(ctx, params) {\n const link = chatOf(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 = chatOf(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 = chatOf(ctx, params);\n if (params.hold === undefined) {\n node(ctx).disconnect({ linkId: link.id });\n return chatJson(findChat(state(ctx).links, link.id));\n }\n const minutes = num(params, \"hold\", 0, { min: 0, max: HOLD_MAX_MINUTES });\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 = chatOf(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 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`).\n const ok = until === \"live\" ? isLive(now)\n : until === \"text\" ? now.textDelivery === \"stream\" || now.textDelivery === \"dht\" || now.textDelivery === \"hold\"\n : !!now.pairingProgress?.peerSeen || now.pairing?.status === \"ready\" || isLive(now);\n return ok ? now : undefined;\n }, ms, `chat ${link.id} to be ${until}`);\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 clean = cleanName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH);\n const name = clean && groupName(clean);\n if (!name) throw new CliError(\"bad_request\", `A group's name is 1 to ${MAX_GROUP_NAME_LENGTH} characters on one line`);\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 { group: groupId, link };\n },\n async \"group.join\"(ctx, params) {\n let groupId: string;\n try {\n ({ groupId } = await node(ctx).joinGroupByLink({ link: str(params, \"link\", true) }));\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 error;\n }\n return { group: 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 - a.lastMessageAt) };\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, (m) => groupMessageJson(m, group));\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 a secret or a Cashu token; 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 if (result.error) throw 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 { group: group.id, messageId, sent: edges > 0, edges, ...(card ? { buttons: card.id, card } : {}) };\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 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 editRefused(await messageOf(ctx, linkId, messageId), messageId, \"group\", result.error, result.refused);\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 async \"group.react\"(ctx, params) {\n const group = groupOf(ctx, params, \"react <chat> <message> <emoji>\");\n return { group: group.id, ...(await react(ctx, `group:${group.id}`, params)) };\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.\n if (typing && group.status !== \"active\") throw new CliError(\"refused\", group.statusReason ?? \"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 = (s: EngineState) => (s.groups.find((g) => g.id === group.id) ?? 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) > 0);\n return {\n group: group.id, typing, ...(typing ? { kind } : {}), ...(status ? { status } : {}),\n reached: reached(state(ctx)), sendTyping: state(ctx).settings.sendTyping !== false, ...(until ? { until } : {}),\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 { admin } = await node(ctx).leaveGroup({ groupId: group.id });\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 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(num(params, \"since\", 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 not in 1.5: no app shows it, and the Desktop's\n // own transports do not follow it yet. Nobody turns it on through here either, until the release that shows it;\n // 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);\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\") noCallOn(ctx, args.linkId, \"remove the chat\");\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 try {\n const result = (await target.call(node(ctx), args)) ?? null;\n // The chat is gone, as with `chat remove`: auto-answer no longer names it.\n if (method === \"removeLink\") ctx.calls.forgetChat(str(args ?? {}, \"linkId\", 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): 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 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]);\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\")];\n if (method === \"forwardMessages\") {\n const ids = Array.isArray(args.messageIds) ? args.messageIds.filter((id): id is string => typeof id === \"string\") : [];\n const linkId = args.linkId;\n texts = typeof linkId === \"string\" && linkId ? 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 `react` and `pin` in a 1:1 chat wait for the contact: a one-shot until it confirmed (as `edit`), since what\n * is not said yet leaves with the process; a daemon goes on saying it, so it answers at once unless asked to wait.\n */\nfunction confirmWait(ctx: ApiContext, params: Params): { wait: \"none\" | \"confirmed\"; ms: number } {\n const wait = oneOf(params, \"wait\", [\"none\", \"confirmed\"] as const, ctx.mode === \"one-shot\" ? \"confirmed\" : \"none\");\n return { wait, ms: num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000 };\n}\n\n/** Reacts to a message of a chat or a group (`group:<id>`): `emoji`, or `remove` for \"\" (WISP 400 § Reactions). */\nasync function react(ctx: ApiContext, linkId: string, params: Params): Promise<{ messageId: string; emoji: string | null; removed: boolean }> {\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 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 };\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/**\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) => 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 = /^[\\w.:-]+$/.test(named) ? named : JSON.stringify(named);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat: ${hint(shown)}`, { 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), naming the id\n * to give, as `button update` and `task update` do; before, a mistyped or lost id read \"Only your own text messages\n * can be edited\" (`refused`, exit 1), as if the message were someone else's.\n */\nfunction editRefused(message: StoredMessage | undefined, ref: string, where: \"chat\" | \"group\", error: string, refused: boolean | undefined): CliError {\n if (refused && !message)\n return new CliError(\"not_found\", `No message ${JSON.stringify(ref)} in this ${where}: give the messageId ${where === \"group\" ? \"group send\" : \"send\"} printed`);\n return new CliError(refused ? \"refused\" : \"unavailable\", error);\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 if (asCliError(error).code !== \"timeout\") throw error;\n } finally { clearTimeout(timer); }\n const shown = /^[\\w.:-]+$/.test(link.label ?? \"\") ? link.label! : link.id;\n throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the contact did not answer. ${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`}`, { chat: link.id });\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 unsave whose id names neither a saved message nor one of the chat's (a typo): said, with where the ids are.\n if (result.error && remove && /not in this chat/.test(result.error)) throw new CliError(\"not_found\", `No saved message ${JSON.stringify(messageId)} in this chat (ghostly saved list shows the saved ones)`);\n if (result.error) throw new CliError(/not in this chat/.test(result.error) ? \"not_found\" : \"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.\n */\nasync function historyOf(ctx: ApiContext, chat: string, params: Params, json: (message: StoredMessage) => MessageJson = 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 throw error instanceof Error && [before, after].some((id) => error.message === `No message ${id}`) ? new CliError(\"not_found\", error.message) : error;\n });\n const originals = await originalsNow(ctx, chat, page.messages);\n return { messages: page.messages.map((m) => quoteChecked(json(m), m, originals)), more: page.more };\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\nexport { findChat, findGroup, startNamedChats } from \"./apiKit\";\nexport type { ApiContext } from \"./apiKit\";\nexport const API_METHODS: readonly string[] = Object.keys(METHODS);\n\n/** Runs one method of the API: one the table lists itself (`constructor`, which every object has, is none). */\nexport async function callApi(ctx: ApiContext, method: string, params: unknown = {}): 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));\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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