@glyphteck/veyl 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -38994,12 +38994,6 @@ function mnemonicFromWalletEntropy(entropy) {
38994
38994
  }
38995
38995
  return entropyToMnemonic(entropyBytesValue, wordlist);
38996
38996
  }
38997
- function deriveLegacyWalletEntropy(seed) {
38998
- const entropy = deriveSeed(seed, "wallet-mnemonic");
38999
- const out = new Uint8Array(entropy.subarray(0, WALLET_MNEMONIC_ENTROPY_BYTES));
39000
- cleanBytes(entropy);
39001
- return out;
39002
- }
39003
38997
  function getKeyPair(seed) {
39004
38998
  const priv = new Uint8Array(seed);
39005
38999
  priv[0] &= 248;
@@ -39086,15 +39080,6 @@ async function openAccountSessionFromSecrets(walletEntropy, chatSeed, { SparkWal
39086
39080
  cleanBytes(chatSeed, chatPubKey);
39087
39081
  }
39088
39082
  }
39089
- async function openLegacyAccountSession(masterSeed, options = {}) {
39090
- const walletEntropy = deriveLegacyWalletEntropy(masterSeed);
39091
- const chatSeed = deriveSeed(masterSeed, "chat");
39092
- try {
39093
- return await openAccountSessionFromSecrets(walletEntropy, chatSeed, options);
39094
- } finally {
39095
- cleanBytes(walletEntropy, chatSeed);
39096
- }
39097
- }
39098
39083
  async function openRegistryAccountSession(masterSeed, registryEnvelope, options = {}) {
39099
39084
  const registry = await openSecretRegistry(masterSeed, registryEnvelope);
39100
39085
  const walletEntropy = getDefaultWalletEntropy(registry);
@@ -39109,7 +39094,7 @@ async function openRegistryAccountSession(masterSeed, registryEnvelope, options
39109
39094
  import { Buffer as Buffer4 } from "buffer";
39110
39095
  import process5 from "process";
39111
39096
 
39112
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/chunk-BCcL9Bmk.js
39097
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/chunk-BCcL9Bmk.js
39113
39098
  var __toBinaryNode = (base642) => new Uint8Array(Buffer.from(base642, "base64"));
39114
39099
 
39115
39100
  // ../../node_modules/.bun/@bufbuild+protobuf@2.12.0/node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js
@@ -39725,7 +39710,7 @@ function assertFloat32(arg) {
39725
39710
  throw new Error("invalid float32: " + arg);
39726
39711
  }
39727
39712
 
39728
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/empty-CbimPmjm.js
39713
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/empty-CbimPmjm.js
39729
39714
  function createBaseTimestamp() {
39730
39715
  return {
39731
39716
  seconds: 0,
@@ -39968,7 +39953,7 @@ var Empty = {
39968
39953
  }
39969
39954
  };
39970
39955
 
39971
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/proto/spark.js
39956
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/proto/spark.js
39972
39957
  var Network = /* @__PURE__ */ function(Network2) {
39973
39958
  Network2[Network2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
39974
39959
  Network2[Network2["MAINNET"] = 1] = "MAINNET";
@@ -57119,7 +57104,7 @@ var DefaultRequester = class extends Requester {
57119
57104
  }
57120
57105
  };
57121
57106
 
57122
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/sdk-types-DJDUa17y.js
57107
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/sdk-types-DJDUa17y.js
57123
57108
  var BitcoinNetwork = /* @__PURE__ */ function(BitcoinNetwork2) {
57124
57109
  BitcoinNetwork2["FUTURE_VALUE"] = "FUTURE_VALUE";
57125
57110
  BitcoinNetwork2["MAINNET"] = "MAINNET";
@@ -57980,7 +57965,7 @@ function mapTransferToWalletTransfer(proto, identityPublicKey, userRequest) {
57980
57965
  };
57981
57966
  }
57982
57967
 
57983
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/multisig-BPUmc7A3.js
57968
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/multisig-BPUmc7A3.js
57984
57969
  function createBaseMultisigConfig() {
57985
57970
  return {
57986
57971
  version: 0,
@@ -58205,7 +58190,7 @@ function isSet3(value) {
58205
58190
  return value !== null && value !== undefined;
58206
58191
  }
58207
58192
 
58208
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/proto/spark_token.js
58193
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/proto/spark_token.js
58209
58194
  var TokenOutputStatus = /* @__PURE__ */ function(TokenOutputStatus2) {
58210
58195
  TokenOutputStatus2[TokenOutputStatus2["TOKEN_OUTPUT_STATUS_UNSPECIFIED"] = 0] = "TOKEN_OUTPUT_STATUS_UNSPECIFIED";
58211
58196
  TokenOutputStatus2[TokenOutputStatus2["TOKEN_OUTPUT_STATUS_AVAILABLE"] = 1] = "TOKEN_OUTPUT_STATUS_AVAILABLE";
@@ -67598,7 +67583,7 @@ class Transaction {
67598
67583
  // ../../node_modules/.bun/@scure+btc-signer@1.8.1/node_modules/@scure/btc-signer/esm/index.js
67599
67584
  /*! scure-btc-signer - MIT License (c) 2022 Paul Miller (paulmillr.com) */
67600
67585
 
67601
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/spark-wallet-DEFcyFjN.js
67586
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/spark-wallet-DEFcyFjN.js
67602
67587
  var import_nice_grpc_common = __toESM(require_lib(), 1);
67603
67588
 
67604
67589
  // ../../node_modules/.bun/@scure+bip32@1.7.0/node_modules/@scure/bip32/lib/esm/index.js
@@ -70216,7 +70201,7 @@ class Mutex {
70216
70201
  // ../../node_modules/.bun/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs
70217
70202
  var import__ = __toESM(require_eventemitter3(), 1);
70218
70203
 
70219
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/spark-wallet-DEFcyFjN.js
70204
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/spark-wallet-DEFcyFjN.js
70220
70205
  var import_light_bolt11_decoder = __toESM(require_bolt11(), 1);
70221
70206
  var SparkFrostBase = class {
70222
70207
  generateAdaptorFromSignature(signature) {
@@ -89330,7 +89315,7 @@ function isTokenTransactionStreamEvent(event) {
89330
89315
  return Boolean(event?.$case === "tokenTransaction" && event.tokenTransaction.tokenTransactionHash);
89331
89316
  }
89332
89317
 
89333
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/buffer-C7zVfCZb.js
89318
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/buffer-C7zVfCZb.js
89334
89319
  import { Buffer as Buffer2 } from "buffer";
89335
89320
  if (typeof globalThis.Buffer === "undefined")
89336
89321
  globalThis.Buffer = Buffer2;
@@ -89341,7 +89326,7 @@ if (typeof window !== "undefined") {
89341
89326
  window.globalThis = window;
89342
89327
  }
89343
89328
 
89344
- // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+04a16a716d9f5b94/node_modules/@buildonspark/spark-sdk/dist/index.browser.js
89329
+ // ../../node_modules/.bun/@buildonspark+spark-sdk@0.8.8+bee703889d31789e/node_modules/@buildonspark/spark-sdk/dist/index.browser.js
89345
89330
  var import_nice_grpc_common2 = __toESM(require_lib(), 1);
89346
89331
  var import_nice_grpc_client_middleware_retry = __toESM(require_lib4(), 1);
89347
89332
  var import_nice_grpc_web = __toESM(require_lib5(), 1);
@@ -92128,7 +92113,7 @@ var CHAT_READY_DOWNLOAD_MAX_BYTES = 8 * MIB_BYTES;
92128
92113
  var CHAT_MESSAGE_FILE_CACHE_MAX_BYTES = 64 * MIB_BYTES;
92129
92114
  var CHAT_UNSAVED_TTL_DAYS = 21;
92130
92115
  var CHAT_UNSAVED_TTL_MS = CHAT_UNSAVED_TTL_DAYS * DAY_MS;
92131
- var CHAT_SEEN_TTL_MS = DAY_MS;
92116
+ var CHAT_AFTER_SEEN_MS = DAY_MS;
92132
92117
  var CHAT_MEDIA_TTL_DAYS = CHAT_UNSAVED_TTL_DAYS;
92133
92118
  var CHAT_MEDIA_TTL_MS = CHAT_MEDIA_TTL_DAYS * DAY_MS;
92134
92119
  var CHAT_UPLOAD_MAX_BYTES = 64 * MIB_BYTES;
@@ -92136,10 +92121,12 @@ var CHAT_AUDIO_TRANSCODE_BITRATE_BPS = 128000;
92136
92121
  var CHAT_VIDEO_TRANSCODE_VIDEO_BITRATE_BPS = 768000;
92137
92122
  var CHAT_VIDEO_TRANSCODE_AUDIO_BITRATE_BPS = CHAT_AUDIO_TRANSCODE_BITRATE_BPS;
92138
92123
  var CHAT_MESSAGE_BATCH_SIZE = 40;
92124
+ var CHAT_TTL_WRITE_BATCH_SIZE = 400;
92139
92125
  var CHAT_LIST_PAGE_SIZE = 20;
92140
92126
  var CHAT_INBOX_PING_PAGE_SIZE = 25;
92141
92127
  var CHAT_LIST_STATUS_CACHE_MS = 30 * MS_PER_SECOND;
92142
92128
  var CHAT_MEDIA_WARM_TYPES = Object.freeze(["img", "gif", "mp4"]);
92129
+ var CHAT_READ_WRITE_INTERVAL_MS = 5 * MS_PER_SECOND;
92143
92130
  var CHAT_SEND_QUEUE_RATE_LIMIT_WINDOW_MS = 10 * MS_PER_SECOND;
92144
92131
  var CHAT_MESSAGE_BODY_MAX_BYTES = 64 * KIB_BYTES;
92145
92132
  var CHAT_LAST_MESSAGE_BODY_MAX_BYTES = 64 * KIB_BYTES;
@@ -92169,6 +92156,7 @@ var WALLET_PENDING_TRANSFER_WARM_AGE_MS = 10 * MINUTE_MS;
92169
92156
  var WALLET_PENDING_TRANSFER_WARM_RETRY_MS = 15 * MS_PER_SECOND;
92170
92157
  var WALLET_PENDING_TRANSFER_STALE_RETRY_MS = 2 * MINUTE_MS;
92171
92158
  var WALLET_PENDING_TRANSFER_STUCK_RETRY_MS = 10 * MINUTE_MS;
92159
+ var WALLET_TRANSFER_CACHE_WRITE_DELAY_MS = 3 * MS_PER_SECOND;
92172
92160
 
92173
92161
  // ../../shared/chat/filepayload.js
92174
92162
  "use client";
@@ -92296,8 +92284,8 @@ var CHAT_RETENTION_LABELS = Object.freeze({
92296
92284
  [CHAT_RETENTION_SEEN]: "delete after seen",
92297
92285
  [CHAT_RETENTION_24H]: "keep for 24h"
92298
92286
  });
92299
- var DEFAULT_MESSAGE_TTL_MS = CHAT_UNSAVED_TTL_MS;
92300
- var SEEN_MESSAGE_TTL_MS = CHAT_SEEN_TTL_MS;
92287
+ var MESSAGE_STORAGE_TTL_MS = CHAT_UNSAVED_TTL_MS;
92288
+ var AFTER_SEEN_MS = CHAT_AFTER_SEEN_MS;
92301
92289
  function hasChatRetention(value) {
92302
92290
  const retention = cleanText(value);
92303
92291
  return CHAT_RETENTION_VALUES.includes(retention);
@@ -92333,16 +92321,14 @@ function isTtlExpired(value, now = Date.now()) {
92333
92321
  const ms = ttlMillis(value);
92334
92322
  return ms != null && ms <= now;
92335
92323
  }
92336
- function newMessageTtlMs(retention = DEFAULT_CHAT_RETENTION, now = Date.now()) {
92337
- switch (cleanChatRetention(retention)) {
92338
- case CHAT_RETENTION_SEEN:
92339
- case CHAT_RETENTION_24H:
92340
- default:
92341
- return now + DEFAULT_MESSAGE_TTL_MS;
92342
- }
92324
+ function newMessageStorageTtlMs(now = Date.now()) {
92325
+ return now + MESSAGE_STORAGE_TTL_MS;
92343
92326
  }
92344
- function seenMessageTtlMs(now = Date.now()) {
92345
- return now + SEEN_MESSAGE_TTL_MS;
92327
+ function messageExpiryMs(retention, seenAt) {
92328
+ if (!Number.isFinite(seenAt)) {
92329
+ return null;
92330
+ }
92331
+ return cleanChatRetention(retention) === CHAT_RETENTION_24H ? seenAt + AFTER_SEEN_MS : seenAt;
92346
92332
  }
92347
92333
 
92348
92334
  // ../../shared/links.js
@@ -92568,7 +92554,6 @@ function targetMessageMs(target, byKey) {
92568
92554
  }
92569
92555
 
92570
92556
  // ../../shared/chat/messages/control.js
92571
- var retainedMessageCache = new WeakMap;
92572
92557
  function cleanReactionEmoji(value) {
92573
92558
  const emoji = cleanText(value);
92574
92559
  return emoji || DEFAULT_REACTION_EMOJI;
@@ -92591,13 +92576,6 @@ function isPeerMsg(msg, chatPK) {
92591
92576
  function isServerConfirmedMsg(msg) {
92592
92577
  return !!msg?.id && !String(msg.id).startsWith("local:") && !msg.pending && !msg.failed;
92593
92578
  }
92594
- function messageOrderMs(message) {
92595
- const ms = getMessageOrderMs(message);
92596
- return Number.isFinite(ms) ? ms : null;
92597
- }
92598
- function hasAnyMsgKey(msg, keys) {
92599
- return messageHasKey(msg, keys);
92600
- }
92601
92579
  function makeReadReceipt(target) {
92602
92580
  const upto = cleanTarget(target);
92603
92581
  if (!upto) {
@@ -92699,236 +92677,6 @@ function canStoreMsg(msg) {
92699
92677
  }
92700
92678
  return canShowMsg(msg) || isControlMsg(msg) || isActionMutationMsg(msg);
92701
92679
  }
92702
- function needsRetentionProjection(messages) {
92703
- for (const msg of messages || []) {
92704
- if (isSystemMsg(msg) || isReadReceiptMsg(msg) || isHiddenCheckpointMsg(msg)) {
92705
- return true;
92706
- }
92707
- }
92708
- return false;
92709
- }
92710
- function receiptCoverageTarget(receipt, byKey) {
92711
- const targetKey = cleanText(receipt?.upto);
92712
- if (!targetKey) {
92713
- return null;
92714
- }
92715
- const target = byKey.get(targetKey);
92716
- const targetMs = messageOrderMs(target) ?? messageOrderMs({ cid: targetKey }) ?? messageOrderMs(receipt);
92717
- const receiptMs = messageOrderMs(receipt);
92718
- if (targetMs == null || receiptMs == null) {
92719
- return null;
92720
- }
92721
- return {
92722
- target,
92723
- targetMs,
92724
- receiptMs
92725
- };
92726
- }
92727
- function makeReceiptCoverage(messages, byKey, chatPK, peerChatPK) {
92728
- const peerMessageReceipts = [];
92729
- const ownMessageReceipts = [];
92730
- for (const msg of messages || []) {
92731
- if (!isServerConfirmedMsg(msg) || !isReadReceiptMsg(msg)) {
92732
- continue;
92733
- }
92734
- const coverage = receiptCoverageTarget(msg, byKey);
92735
- if (!coverage) {
92736
- continue;
92737
- }
92738
- const receiptFromPeer = isPeerMsg(msg, chatPK);
92739
- if (receiptFromPeer) {
92740
- if (peerChatPK && msg?.s !== peerChatPK) {
92741
- continue;
92742
- }
92743
- if (coverage.target && isPeerMsg(coverage.target, chatPK)) {
92744
- continue;
92745
- }
92746
- ownMessageReceipts.push(coverage);
92747
- } else {
92748
- if (coverage.target && !isPeerMsg(coverage.target, chatPK)) {
92749
- continue;
92750
- }
92751
- peerMessageReceipts.push(coverage);
92752
- }
92753
- }
92754
- peerMessageReceipts.sort((a, b) => b.targetMs - a.targetMs);
92755
- ownMessageReceipts.sort((a, b) => b.targetMs - a.targetMs);
92756
- return {
92757
- peer: { receipts: peerMessageReceipts, index: 0, seenAt: null },
92758
- own: { receipts: ownMessageReceipts, index: 0, seenAt: null }
92759
- };
92760
- }
92761
- function receiptCoverageSeenAt(state, messageMs) {
92762
- if (!state || messageMs == null) {
92763
- return null;
92764
- }
92765
- while (state.index < state.receipts.length && state.receipts[state.index].targetMs >= messageMs) {
92766
- const receiptMs = state.receipts[state.index].receiptMs;
92767
- state.seenAt = state.seenAt == null ? receiptMs : Math.min(state.seenAt, receiptMs);
92768
- state.index += 1;
92769
- }
92770
- return state.seenAt;
92771
- }
92772
- function hasRetentionControls(messages) {
92773
- for (const msg of messages || []) {
92774
- if (isServerConfirmedMsg(msg) && (isReadReceiptMsg(msg) || isHiddenCheckpointMsg(msg))) {
92775
- return true;
92776
- }
92777
- }
92778
- return false;
92779
- }
92780
- function hiddenCheckpointCoverageTarget(checkpoint, byKey) {
92781
- const targetKey = cleanText(checkpoint?.upto);
92782
- if (!targetKey) {
92783
- return null;
92784
- }
92785
- const target = byKey.get(targetKey);
92786
- const targetMs = targetMessageMs(targetKey, byKey);
92787
- const targetFrom = cleanText(target?.s) || cleanText(target?.from) || cleanText(checkpoint?.targetFrom);
92788
- if (targetMs == null || !targetFrom) {
92789
- return null;
92790
- }
92791
- return { targetMs, targetFrom };
92792
- }
92793
- function makeHiddenCheckpointCoverage(messages, byKey, chatPK, peerChatPK) {
92794
- const own = cleanText(chatPK);
92795
- const peer = cleanText(peerChatPK);
92796
- const coverage = { peerTargetMs: null, ownTargetMs: null };
92797
- if (!own) {
92798
- return coverage;
92799
- }
92800
- for (const msg of messages || []) {
92801
- if (!isServerConfirmedMsg(msg) || !isHiddenCheckpointMsg(msg)) {
92802
- continue;
92803
- }
92804
- const checkpointFrom = cleanText(msg?.s);
92805
- if (checkpointFrom !== own && (!peer || checkpointFrom !== peer)) {
92806
- continue;
92807
- }
92808
- const target = hiddenCheckpointCoverageTarget(msg, byKey);
92809
- if (!target) {
92810
- continue;
92811
- }
92812
- const targetFrom = target.targetFrom;
92813
- if (targetFrom === own) {
92814
- coverage.ownTargetMs = coverage.ownTargetMs == null ? target.targetMs : Math.max(coverage.ownTargetMs, target.targetMs);
92815
- } else if (!peer || targetFrom === peer) {
92816
- coverage.peerTargetMs = coverage.peerTargetMs == null ? target.targetMs : Math.max(coverage.peerTargetMs, target.targetMs);
92817
- }
92818
- }
92819
- return coverage;
92820
- }
92821
- function canRetentionControlsHideMessages(messages, now) {
92822
- let hasSeenRetention = false;
92823
- let hasExpiredSeenWindow = false;
92824
- let hasCheckpoint = false;
92825
- for (const msg of messages || []) {
92826
- if (isServerConfirmedMsg(msg) && isReadReceiptMsg(msg)) {
92827
- const ms = messageOrderMs(msg);
92828
- if (ms != null && seenMessageTtlMs(ms) <= now) {
92829
- hasExpiredSeenWindow = true;
92830
- }
92831
- continue;
92832
- }
92833
- if (isServerConfirmedMsg(msg) && isHiddenCheckpointMsg(msg)) {
92834
- hasCheckpoint = true;
92835
- continue;
92836
- }
92837
- if (getMessageRetention(msg) === CHAT_RETENTION_SEEN) {
92838
- hasSeenRetention = true;
92839
- }
92840
- if (hasSeenRetention && (hasExpiredSeenWindow || hasCheckpoint)) {
92841
- return true;
92842
- }
92843
- }
92844
- return hasSeenRetention || hasExpiredSeenWindow || hasCheckpoint;
92845
- }
92846
- function collectSeenHiddenMessages(messages, chatPK, peerChatPK, options = {}) {
92847
- if (!Array.isArray(messages) || !messages.length || !chatPK) {
92848
- return { hidden: [], nextMs: null };
92849
- }
92850
- if (!hasRetentionControls(messages)) {
92851
- return { hidden: [], nextMs: null };
92852
- }
92853
- const keepKeys = options?.keepKeys instanceof Set ? options.keepKeys : new Set(Array.isArray(options?.keepKeys) ? options.keepKeys.filter(Boolean) : []);
92854
- const now = Number.isFinite(options?.now) ? options.now : Date.now();
92855
- if (options?.next !== true && !canRetentionControlsHideMessages(messages, now)) {
92856
- return { hidden: [], nextMs: null };
92857
- }
92858
- const byKey = indexMessagesByKey(messages, { keep: "last" });
92859
- const coverage = makeReceiptCoverage(messages, byKey, chatPK, peerChatPK);
92860
- const checkpointCoverage = makeHiddenCheckpointCoverage(messages, byKey, chatPK, peerChatPK);
92861
- if (!coverage.peer.receipts.length && !coverage.own.receipts.length && checkpointCoverage.peerTargetMs == null && checkpointCoverage.ownTargetMs == null) {
92862
- return { hidden: [], nextMs: null };
92863
- }
92864
- const hidden = [];
92865
- let nextMs = null;
92866
- const candidates = [];
92867
- for (const msg of messages) {
92868
- if (!hasAnyMsgKey(msg, keepKeys) && isServerConfirmedMsg(msg) && !isControlMsg(msg) && !isSystemMsg(msg) && canShowMsg(msg) && msg.ttl != null) {
92869
- const ms = messageOrderMs(msg);
92870
- if (ms != null) {
92871
- candidates.push({ msg, ms, fromPeer: isPeerMsg(msg, chatPK) });
92872
- }
92873
- }
92874
- }
92875
- candidates.sort((a, b) => b.ms - a.ms);
92876
- for (const candidate of candidates) {
92877
- const retention = getMessageRetention(candidate.msg);
92878
- const checkpointTargetMs = candidate.fromPeer ? checkpointCoverage.peerTargetMs : checkpointCoverage.ownTargetMs;
92879
- if (options?.hideSeen !== false && retention === CHAT_RETENTION_SEEN && checkpointTargetMs != null && candidate.ms <= checkpointTargetMs) {
92880
- hidden.push(candidate.msg);
92881
- continue;
92882
- }
92883
- const seenAt = receiptCoverageSeenAt(candidate.fromPeer ? coverage.peer : coverage.own, candidate.ms);
92884
- if (seenAt == null) {
92885
- continue;
92886
- }
92887
- if (retention === CHAT_RETENTION_SEEN) {
92888
- if (options?.hideSeen !== false) {
92889
- hidden.push(candidate.msg);
92890
- }
92891
- continue;
92892
- }
92893
- const hideAt = seenMessageTtlMs(seenAt);
92894
- if (hideAt <= now) {
92895
- hidden.push(candidate.msg);
92896
- } else if (nextMs == null || hideAt < nextMs) {
92897
- nextMs = hideAt;
92898
- }
92899
- }
92900
- return { hidden, nextMs };
92901
- }
92902
- function filterSeenMessages(messages, chatPK, peerChatPK, options = {}) {
92903
- const state = collectProjectedSeenHiddenState(messages, chatPK, peerChatPK, options);
92904
- const projectedMessages = state.messages;
92905
- const hidden = state.hidden;
92906
- if (!hidden.length) {
92907
- return projectedMessages;
92908
- }
92909
- const hiddenKeys = collectMessageKeys(hidden);
92910
- return projectedMessages.filter((msg) => !hasAnyMsgKey(msg, hiddenKeys));
92911
- }
92912
- function getDisplayMessages(messages, chatPK, peerChatPK, options = {}) {
92913
- return filterSeenMessages(messages, chatPK, peerChatPK, options);
92914
- }
92915
- function collectProjectedSeenHiddenState(messages, chatPK, peerChatPK, options = {}) {
92916
- const actionMessages = applyMessageActions(messages);
92917
- if (!needsRetentionProjection(actionMessages)) {
92918
- return {
92919
- messages: actionMessages || [],
92920
- hidden: [],
92921
- nextMs: null
92922
- };
92923
- }
92924
- const projectedMessages = applyMessageRetentionTimeline(actionMessages, options.fallback);
92925
- const state = collectSeenHiddenMessages(projectedMessages, chatPK, peerChatPK, options);
92926
- return {
92927
- messages: projectedMessages,
92928
- hidden: state.hidden,
92929
- nextMs: state.nextMs
92930
- };
92931
- }
92932
92680
  function actionTarget(msg) {
92933
92681
  return cleanText(msg?.actionTarget) || cleanText(msg?.target) || cleanText(msg?.id);
92934
92682
  }
@@ -92944,7 +92692,7 @@ function actionPatch(msg) {
92944
92692
  actionId,
92945
92693
  actionOp,
92946
92694
  actionTarget: actionTarget2,
92947
- actor,
92695
+ signingPublicKey,
92948
92696
  target,
92949
92697
  ...payload
92950
92698
  } = msg || {};
@@ -93032,53 +92780,241 @@ function applyMessageActions(messages) {
93032
92780
  }
93033
92781
  return out.filter(Boolean);
93034
92782
  }
92783
+
92784
+ // ../../shared/chat/messages/expiry.js
92785
+ var retainedMessageCache = new WeakMap;
92786
+ function messageOrderMs(message) {
92787
+ const ms = getMessageOrderMs(message);
92788
+ return Number.isFinite(ms) ? ms : null;
92789
+ }
92790
+ function hasExpiryControls(messages) {
92791
+ return (messages || []).some((message) => isServerConfirmedMsg(message) && (isReadReceiptMsg(message) || isHiddenCheckpointMsg(message)));
92792
+ }
92793
+ function needsRetentionTimeline(messages) {
92794
+ return (messages || []).some(isSystemMsg);
92795
+ }
92796
+ function withCachedRetention(message, retention) {
92797
+ const nextRetention = cleanChatRetention(retention);
92798
+ if (message.retention === nextRetention) {
92799
+ return message;
92800
+ }
92801
+ let byRetention = retainedMessageCache.get(message);
92802
+ if (!byRetention) {
92803
+ byRetention = new Map;
92804
+ retainedMessageCache.set(message, byRetention);
92805
+ }
92806
+ const cached = byRetention.get(nextRetention);
92807
+ if (cached) {
92808
+ return cached;
92809
+ }
92810
+ const next = { ...message, retention: nextRetention };
92811
+ byRetention.set(nextRetention, next);
92812
+ return next;
92813
+ }
93035
92814
  function applyMessageRetentionTimeline(messages, fallback = DEFAULT_CHAT_RETENTION) {
93036
92815
  if (!Array.isArray(messages) || !messages.length) {
93037
92816
  return messages || [];
93038
92817
  }
93039
92818
  let retention = cleanChatRetention(fallback);
93040
- let timelineActive = false;
93041
92819
  let changed = false;
93042
- const next = messages.map((msg) => {
93043
- if (!msg || typeof msg !== "object" || Array.isArray(msg)) {
93044
- return msg;
93045
- }
93046
- if (isSystemMsg(msg)) {
93047
- retention = cleanChatRetention(msg.retention);
93048
- timelineActive = true;
93049
- return msg;
92820
+ const next = messages.map((message) => {
92821
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
92822
+ return message;
93050
92823
  }
93051
- if (isControlMsg(msg) || !canShowMsg(msg)) {
93052
- return msg;
92824
+ if (isSystemMsg(message)) {
92825
+ retention = cleanChatRetention(message.retention);
92826
+ return message;
93053
92827
  }
93054
- if (hasChatRetention(msg.retention)) {
93055
- return msg;
92828
+ if (isControlMsg(message) || !canShowMsg(message) || hasChatRetention(message.retention)) {
92829
+ return message;
93056
92830
  }
93057
- const next2 = withCachedMessageRetention(msg, retention);
93058
- if (next2 !== msg) {
92831
+ const retained = withCachedRetention(message, retention);
92832
+ if (retained !== message) {
93059
92833
  changed = true;
93060
92834
  }
93061
- return next2;
92835
+ return retained;
93062
92836
  });
93063
92837
  return changed ? next : messages;
93064
92838
  }
93065
- function withCachedMessageRetention(msg, retention) {
93066
- const nextRetention = cleanChatRetention(retention);
93067
- if (msg.retention === nextRetention) {
93068
- return msg;
92839
+ function receiptTarget(receipt, byKey) {
92840
+ const targetKey = cleanText(receipt?.upto);
92841
+ if (!targetKey) {
92842
+ return null;
93069
92843
  }
93070
- let byRetention = retainedMessageCache.get(msg);
93071
- if (!byRetention) {
93072
- byRetention = new Map;
93073
- retainedMessageCache.set(msg, byRetention);
92844
+ const target = byKey.get(targetKey);
92845
+ const targetMs = messageOrderMs(target) ?? messageOrderMs({ cid: targetKey }) ?? messageOrderMs(receipt);
92846
+ const seenAt = messageOrderMs(receipt);
92847
+ const receiptKey = getMessageKey(receipt);
92848
+ return targetMs == null || seenAt == null || !receiptKey ? null : { receiptKey, target, targetMs, seenAt };
92849
+ }
92850
+ function makeReceiptCoverage(messages, byKey, selfChatPublicKey, peerChatPublicKey) {
92851
+ const peerMessages = [];
92852
+ const ownMessages = [];
92853
+ for (const message of messages || []) {
92854
+ if (!isServerConfirmedMsg(message) || !isReadReceiptMsg(message)) {
92855
+ continue;
92856
+ }
92857
+ const receipt = receiptTarget(message, byKey);
92858
+ if (!receipt) {
92859
+ continue;
92860
+ }
92861
+ if (isPeerMsg(message, selfChatPublicKey)) {
92862
+ if (peerChatPublicKey && message.s !== peerChatPublicKey || receipt.target && isPeerMsg(receipt.target, selfChatPublicKey)) {
92863
+ continue;
92864
+ }
92865
+ ownMessages.push(receipt);
92866
+ } else {
92867
+ if (receipt.target && !isPeerMsg(receipt.target, selfChatPublicKey)) {
92868
+ continue;
92869
+ }
92870
+ peerMessages.push(receipt);
92871
+ }
93074
92872
  }
93075
- const cached = byRetention.get(nextRetention);
93076
- if (cached) {
93077
- return cached;
92873
+ peerMessages.sort((left, right) => right.targetMs - left.targetMs || left.seenAt - right.seenAt);
92874
+ ownMessages.sort((left, right) => right.targetMs - left.targetMs || left.seenAt - right.seenAt);
92875
+ return {
92876
+ peer: { items: peerMessages, index: 0, current: null },
92877
+ own: { items: ownMessages, index: 0, current: null }
92878
+ };
92879
+ }
92880
+ function coveringReceipt(state, messageMs) {
92881
+ while (state && state.index < state.items.length && state.items[state.index].targetMs >= messageMs) {
92882
+ const next = state.items[state.index];
92883
+ if (!state.current || next.seenAt < state.current.seenAt) {
92884
+ state.current = next;
92885
+ }
92886
+ state.index += 1;
93078
92887
  }
93079
- const next = { ...msg, retention: nextRetention };
93080
- byRetention.set(nextRetention, next);
93081
- return next;
92888
+ return state?.current ?? null;
92889
+ }
92890
+ function checkpointTarget(checkpoint, byKey) {
92891
+ const targetKey = cleanText(checkpoint?.upto);
92892
+ if (!targetKey) {
92893
+ return null;
92894
+ }
92895
+ const target = byKey.get(targetKey);
92896
+ const targetMs = targetMessageMs(targetKey, byKey);
92897
+ const targetFrom = cleanText(target?.s) || cleanText(target?.from) || cleanText(checkpoint?.targetFrom);
92898
+ const hiddenAt = messageOrderMs(checkpoint);
92899
+ return targetMs == null || !targetFrom || hiddenAt == null ? null : { targetMs, targetFrom, hiddenAt };
92900
+ }
92901
+ function makeCheckpointCoverage(messages, byKey, selfChatPublicKey, peerChatPublicKey) {
92902
+ const peerMessages = [];
92903
+ const ownMessages = [];
92904
+ const self2 = cleanText(selfChatPublicKey);
92905
+ const peer = cleanText(peerChatPublicKey);
92906
+ for (const message of messages || []) {
92907
+ if (!isServerConfirmedMsg(message) || !isHiddenCheckpointMsg(message)) {
92908
+ continue;
92909
+ }
92910
+ const checkpointFrom = cleanText(message.s);
92911
+ if (checkpointFrom !== self2 && (!peer || checkpointFrom !== peer)) {
92912
+ continue;
92913
+ }
92914
+ const checkpoint = checkpointTarget(message, byKey);
92915
+ if (!checkpoint) {
92916
+ continue;
92917
+ }
92918
+ if (checkpoint.targetFrom === self2) {
92919
+ ownMessages.push(checkpoint);
92920
+ } else if (!peer || checkpoint.targetFrom === peer) {
92921
+ peerMessages.push(checkpoint);
92922
+ }
92923
+ }
92924
+ peerMessages.sort((left, right) => right.targetMs - left.targetMs || left.hiddenAt - right.hiddenAt);
92925
+ ownMessages.sort((left, right) => right.targetMs - left.targetMs || left.hiddenAt - right.hiddenAt);
92926
+ return {
92927
+ peer: { items: peerMessages, index: 0, current: null },
92928
+ own: { items: ownMessages, index: 0, current: null }
92929
+ };
92930
+ }
92931
+ function coveringCheckpoint(state, messageMs) {
92932
+ while (state && state.index < state.items.length && state.items[state.index].targetMs >= messageMs) {
92933
+ const next = state.items[state.index];
92934
+ if (!state.current || next.targetMs > state.current.targetMs || next.targetMs === state.current.targetMs && next.hiddenAt < state.current.hiddenAt) {
92935
+ state.current = next;
92936
+ }
92937
+ state.index += 1;
92938
+ }
92939
+ return state?.current ?? null;
92940
+ }
92941
+ function heldKeys(value) {
92942
+ if (value instanceof Set) {
92943
+ return value;
92944
+ }
92945
+ return new Set(Array.isArray(value) ? value.filter(Boolean) : []);
92946
+ }
92947
+ function analyzeMessageExpiry(messages, selfChatPublicKey, peerChatPublicKey, options = {}) {
92948
+ const actionMessages = applyMessageActions(messages);
92949
+ const projectedMessages = needsRetentionTimeline(actionMessages) ? applyMessageRetentionTimeline(actionMessages, options.fallback) : actionMessages || [];
92950
+ if (!projectedMessages.length || !selfChatPublicKey || !hasExpiryControls(projectedMessages)) {
92951
+ return {
92952
+ messages: projectedMessages,
92953
+ visible: projectedMessages,
92954
+ expired: [],
92955
+ heldExpired: [],
92956
+ nextExpiryAt: null,
92957
+ requiredReceiptKeys: new Set
92958
+ };
92959
+ }
92960
+ const byKey = indexMessagesByKey(projectedMessages, { keep: "last" });
92961
+ const receipts = makeReceiptCoverage(projectedMessages, byKey, selfChatPublicKey, peerChatPublicKey);
92962
+ const checkpoints = makeCheckpointCoverage(projectedMessages, byKey, selfChatPublicKey, peerChatPublicKey);
92963
+ const keepKeys = heldKeys(options.keepKeys);
92964
+ const now = Number.isFinite(options.now) ? options.now : Date.now();
92965
+ const candidates = [];
92966
+ for (const message of projectedMessages) {
92967
+ if (!isServerConfirmedMsg(message) || isControlMsg(message) || isSystemMsg(message) || !canShowMsg(message) || message.ttl == null) {
92968
+ continue;
92969
+ }
92970
+ const orderMs = messageOrderMs(message);
92971
+ if (orderMs != null) {
92972
+ candidates.push({ message, orderMs, fromPeer: isPeerMsg(message, selfChatPublicKey) });
92973
+ }
92974
+ }
92975
+ candidates.sort((left, right) => right.orderMs - left.orderMs);
92976
+ const expired = [];
92977
+ const heldExpired = [];
92978
+ const requiredReceiptKeys = new Set;
92979
+ let nextExpiryAt = null;
92980
+ for (const candidate of candidates) {
92981
+ const direction = candidate.fromPeer ? "peer" : "own";
92982
+ const receipt = coveringReceipt(receipts[direction], candidate.orderMs);
92983
+ const checkpoint = coveringCheckpoint(checkpoints[direction], candidate.orderMs);
92984
+ const retention = getMessageRetention(candidate.message);
92985
+ const seenAt = retention === CHAT_RETENTION_SEEN ? receipt?.seenAt ?? checkpoint?.hiddenAt ?? null : receipt?.seenAt ?? null;
92986
+ if (retention !== CHAT_RETENTION_SEEN && receipt) {
92987
+ requiredReceiptKeys.add(receipt.receiptKey);
92988
+ }
92989
+ const expiresAt = messageExpiryMs(retention, seenAt);
92990
+ if (expiresAt == null) {
92991
+ continue;
92992
+ }
92993
+ if (expiresAt > now) {
92994
+ nextExpiryAt = nextExpiryAt == null ? expiresAt : Math.min(nextExpiryAt, expiresAt);
92995
+ continue;
92996
+ }
92997
+ if (messageHasKey(candidate.message, keepKeys)) {
92998
+ heldExpired.push(candidate.message);
92999
+ } else {
93000
+ expired.push(candidate.message);
93001
+ }
93002
+ }
93003
+ if (!expired.length) {
93004
+ return { messages: projectedMessages, visible: projectedMessages, expired, heldExpired, nextExpiryAt, requiredReceiptKeys };
93005
+ }
93006
+ const expiredKeys = collectMessageKeys(expired);
93007
+ return {
93008
+ messages: projectedMessages,
93009
+ visible: projectedMessages.filter((message) => !messageHasKey(message, expiredKeys)),
93010
+ expired,
93011
+ heldExpired,
93012
+ nextExpiryAt,
93013
+ requiredReceiptKeys
93014
+ };
93015
+ }
93016
+ function getDisplayMessages(messages, selfChatPublicKey, peerChatPublicKey, options = {}) {
93017
+ return analyzeMessageExpiry(messages, selfChatPublicKey, peerChatPublicKey, options).visible;
93082
93018
  }
93083
93019
 
93084
93020
  // ../../shared/chat/messages/compose.js
@@ -93429,21 +93365,21 @@ function markError(diag, label, startedAt, error, data = {}) {
93429
93365
 
93430
93366
  // ../../shared/crypto/sign.js
93431
93367
  "use client";
93432
- var CHAT_ACTOR_SIGN_SCOPE = "chat-actor-sign-v2";
93368
+ var CHAT_SIGNING_SCOPE = "chat-actor-sign-v2";
93433
93369
  function orderKeys(a, b) {
93434
93370
  if (!a || !b) {
93435
93371
  throw new Error("chat keys required");
93436
93372
  }
93437
93373
  return a <= b ? [a, b] : [b, a];
93438
93374
  }
93439
- function deriveChatActorSecret(chatPrivKey, chatId, chatPK, peerChatPK) {
93375
+ function deriveChatSigningSecret(chatPrivKey, chatId, chatPK, peerChatPK) {
93440
93376
  if (!chatPrivKey || !chatId || !chatPK || !peerChatPK) {
93441
- throw new Error("chat actor key material required");
93377
+ throw new Error("chat signing key material required");
93442
93378
  }
93443
- return deriveKey2(toBytes(chatPrivKey, "chat private key"), CHAT_ACTOR_SIGN_SCOPE, [chatId, ...orderKeys(chatPK, peerChatPK)]);
93379
+ return deriveKey2(toBytes(chatPrivKey, "chat private key"), CHAT_SIGNING_SCOPE, [chatId, ...orderKeys(chatPK, peerChatPK)]);
93444
93380
  }
93445
- function getChatActorKey(chatPrivKey, chatId, chatPK, peerChatPK) {
93446
- const secret = deriveChatActorSecret(chatPrivKey, chatId, chatPK, peerChatPK);
93381
+ function getChatSigningKey(chatPrivKey, chatId, chatPK, peerChatPK) {
93382
+ const secret = deriveChatSigningSecret(chatPrivKey, chatId, chatPK, peerChatPK);
93447
93383
  try {
93448
93384
  return {
93449
93385
  secret,
@@ -93454,15 +93390,15 @@ function getChatActorKey(chatPrivKey, chatId, chatPK, peerChatPK) {
93454
93390
  throw error;
93455
93391
  }
93456
93392
  }
93457
- function signChatBytes(actorKey, bytes) {
93458
- if (!actorKey?.secret || !actorKey?.publicKey) {
93459
- throw new Error("chat actor key required");
93393
+ function signChatBytes(signingKey, bytes) {
93394
+ if (!signingKey?.secret || !signingKey?.publicKey) {
93395
+ throw new Error("chat signing key required");
93460
93396
  }
93461
- return toHex(ed25519.sign(toBytes(bytes, "signing bytes"), actorKey.secret));
93397
+ return toHex(ed25519.sign(toBytes(bytes, "signing bytes"), signingKey.secret));
93462
93398
  }
93463
93399
  function verifyChatBytes(publicKey, sig, bytes) {
93464
93400
  try {
93465
- return ed25519.verify(fromHexBytes(sig, "chat signature"), toBytes(bytes, "signed bytes"), fromHex(publicKey, "chat actor public key"));
93401
+ return ed25519.verify(fromHexBytes(sig, "chat signature"), toBytes(bytes, "signed bytes"), fromHex(publicKey, "chat signing public key"));
93466
93402
  } catch {
93467
93403
  return false;
93468
93404
  }
@@ -93504,12 +93440,12 @@ async function openPair(chatPK, chatPrivKey, peerChatPK, options = {}) {
93504
93440
  const linkRoot = deriveKey2(secret, "chat-link-root-v1", orderedKeys);
93505
93441
  const root = chatId ? deriveKey2(secret, "chat-root-v2", [chatId, ...orderedKeys]) : null;
93506
93442
  const bodyKey = root ? deriveKey2(root, "chat-msg-body-key-v2") : null;
93507
- const actor = chatId ? getChatActorKey(privKeyBytes, chatId, chatPK, peerChatPK) : null;
93443
+ const signingKey = chatId ? getChatSigningKey(privKeyBytes, chatId, chatPK, peerChatPK) : null;
93508
93444
  cleanBytes(sharedSecret);
93509
- return { linkId, chatId, chatPK, peerChatPK, linkRoot, root, bodyKey, actor };
93445
+ return { linkId, chatId, chatPK, peerChatPK, linkRoot, root, bodyKey, signingKey };
93510
93446
  }
93511
93447
  function closePair(pair) {
93512
- cleanBytes(pair?.linkRoot, pair?.root, pair?.bodyKey, pair?.actor?.secret);
93448
+ cleanBytes(pair?.linkRoot, pair?.root, pair?.bodyKey, pair?.signingKey?.secret);
93513
93449
  }
93514
93450
  function getPairAad(pair, scope, ...parts) {
93515
93451
  if (!pair?.chatId) {
@@ -93580,7 +93516,7 @@ function normalizePlainPayload(payload) {
93580
93516
  return payload;
93581
93517
  }
93582
93518
  function makeMsgAction(pair, head, message, options = {}) {
93583
- if (!pair?.chatId || !pair?.actor?.publicKey) {
93519
+ if (!pair?.chatId || !pair?.signingKey?.publicKey) {
93584
93520
  throw new Error("chat action pair required");
93585
93521
  }
93586
93522
  const payload = getPayload(message);
@@ -93591,7 +93527,7 @@ function makeMsgAction(pair, head, message, options = {}) {
93591
93527
  id: cleanText(options?.id) || head.cid,
93592
93528
  ...target ? { target } : {},
93593
93529
  s: pair.chatPK,
93594
- actor: pair.actor.publicKey,
93530
+ actor: pair.signingKey.publicKey,
93595
93531
  ts: Number.isFinite(options?.ts) ? options.ts : Date.now(),
93596
93532
  p: payload
93597
93533
  };
@@ -93644,12 +93580,12 @@ function unpackMsgBody(body) {
93644
93580
  ct: bytes.subarray(MSG_BODY_HEADER_BYTES)
93645
93581
  };
93646
93582
  }
93647
- function expectedActorForSender(pair, sender, actors) {
93583
+ function expectedSigningKeyForSender(pair, sender, signingKeysByChatKey) {
93648
93584
  if (sender === pair?.chatPK) {
93649
- return cleanText(pair?.actor?.publicKey);
93585
+ return cleanText(pair?.signingKey?.publicKey);
93650
93586
  }
93651
- if (sender === pair?.peerChatPK && actors && typeof actors === "object" && !Array.isArray(actors)) {
93652
- return cleanText(actors[sender]);
93587
+ if (sender === pair?.peerChatPK && signingKeysByChatKey && typeof signingKeysByChatKey === "object" && !Array.isArray(signingKeysByChatKey)) {
93588
+ return cleanText(signingKeysByChatKey[sender]);
93653
93589
  }
93654
93590
  return "";
93655
93591
  }
@@ -93666,17 +93602,17 @@ function normalizeOpenedAction(pair, head, action, options = {}) {
93666
93602
  if (sender !== pair.chatPK && sender !== pair.peerChatPK) {
93667
93603
  throw new Error("chat action sender mismatch");
93668
93604
  }
93669
- const actor = cleanText(action.actor);
93670
- const expectedActor = expectedActorForSender(pair, sender, options?.actors);
93671
- if (!expectedActor || actor !== expectedActor) {
93672
- throw new Error("chat action actor mismatch");
93605
+ const signingPublicKey = cleanText(action.actor);
93606
+ const expectedSigningPublicKey = expectedSigningKeyForSender(pair, sender, options?.signingKeysByChatKey);
93607
+ if (!expectedSigningPublicKey || signingPublicKey !== expectedSigningPublicKey) {
93608
+ throw new Error("chat action signer mismatch");
93673
93609
  }
93674
93610
  return {
93675
93611
  op,
93676
93612
  id,
93677
93613
  target: cleanText(action.target),
93678
93614
  sender,
93679
- actor,
93615
+ signingPublicKey,
93680
93616
  ts: cleanActionTimestamp(action.ts),
93681
93617
  payload: normalizePlainPayload(action.p)
93682
93618
  };
@@ -93689,7 +93625,7 @@ async function sealMsgBody(pair, head, action) {
93689
93625
  const body = encoder.encode(JSON.stringify(action));
93690
93626
  try {
93691
93627
  const { nonce, ct } = await sealBox(pair.bodyKey, body, aad);
93692
- const sig = signChatBytes(pair.actor, getSignatureInput(aad, nonce, ct));
93628
+ const sig = signChatBytes(pair.signingKey, getSignatureInput(aad, nonce, ct));
93693
93629
  return packMsgBody({ nonce, sig, ct });
93694
93630
  } finally {
93695
93631
  cleanBytes(body);
@@ -93705,31 +93641,31 @@ async function openMsgPlaintext(pair, nonce, ct, aad, options = {}) {
93705
93641
  }
93706
93642
  return openBox(pair.bodyKey, nonce, ct, aad);
93707
93643
  }
93708
- async function verifyMsgSignature(actor, sig, bytes, options = {}) {
93644
+ async function verifyMsgSignature(signingPublicKey, sig, bytes, options = {}) {
93709
93645
  const crypto3 = options?.crypto;
93710
93646
  if (typeof crypto3?.isAvailable === "function" && !crypto3.isAvailable()) {
93711
- return verifyChatBytes(actor, toHex(sig), bytes);
93647
+ return verifyChatBytes(signingPublicKey, toHex(sig), bytes);
93712
93648
  }
93713
93649
  if (typeof crypto3?.verifyChatBytes === "function") {
93714
- return crypto3.verifyChatBytes(actor, sig, bytes);
93650
+ return crypto3.verifyChatBytes(signingPublicKey, sig, bytes);
93715
93651
  }
93716
- return verifyChatBytes(actor, toHex(sig), bytes);
93652
+ return verifyChatBytes(signingPublicKey, toHex(sig), bytes);
93717
93653
  }
93718
- function expectedSignatureActors(pair, actors) {
93654
+ function expectedSigningKeys(pair, signingKeysByChatKey) {
93719
93655
  const values = [];
93720
93656
  const seen = new Set;
93721
93657
  const add3 = (value) => {
93722
- const actor = cleanText(value);
93723
- if (!actor || seen.has(actor)) {
93658
+ const signingPublicKey = cleanText(value);
93659
+ if (!signingPublicKey || seen.has(signingPublicKey)) {
93724
93660
  return;
93725
93661
  }
93726
- seen.add(actor);
93727
- values.push(actor);
93662
+ seen.add(signingPublicKey);
93663
+ values.push(signingPublicKey);
93728
93664
  };
93729
- add3(pair?.actor?.publicKey);
93730
- if (actors && typeof actors === "object" && !Array.isArray(actors)) {
93731
- add3(actors[pair?.chatPK]);
93732
- add3(actors[pair?.peerChatPK]);
93665
+ add3(pair?.signingKey?.publicKey);
93666
+ if (signingKeysByChatKey && typeof signingKeysByChatKey === "object" && !Array.isArray(signingKeysByChatKey)) {
93667
+ add3(signingKeysByChatKey[pair?.chatPK]);
93668
+ add3(signingKeysByChatKey[pair?.peerChatPK]);
93733
93669
  }
93734
93670
  return values;
93735
93671
  }
@@ -93737,12 +93673,12 @@ async function verifyExpectedSignatureBeforeOpen(pair, sig, bytes, options = {})
93737
93673
  if (!options?.crypto?.preverifyBeforeOpen) {
93738
93674
  return true;
93739
93675
  }
93740
- const actors = expectedSignatureActors(pair, options?.actors);
93741
- if (actors.length < 2) {
93676
+ const signingKeysByChatKey = expectedSigningKeys(pair, options?.signingKeysByChatKey);
93677
+ if (signingKeysByChatKey.length < 2) {
93742
93678
  return true;
93743
93679
  }
93744
- for (const actor of actors) {
93745
- if (await verifyMsgSignature(actor, sig, bytes, options)) {
93680
+ for (const signingPublicKey of signingKeysByChatKey) {
93681
+ if (await verifyMsgSignature(signingPublicKey, sig, bytes, options)) {
93746
93682
  return true;
93747
93683
  }
93748
93684
  }
@@ -93774,7 +93710,7 @@ async function openMsg(pair, data, options = {}) {
93774
93710
  try {
93775
93711
  const action = JSON.parse(decoder.decode(plaintext));
93776
93712
  const normalized = normalizeOpenedAction(pair, head, action, options);
93777
- if (!await verifyMsgSignature(normalized.actor, sig, signatureInput, options)) {
93713
+ if (!await verifyMsgSignature(normalized.signingPublicKey, sig, signatureInput, options)) {
93778
93714
  throw new Error("invalid chat action signature");
93779
93715
  }
93780
93716
  return {
@@ -93784,7 +93720,7 @@ async function openMsg(pair, data, options = {}) {
93784
93720
  actionId: normalized.id,
93785
93721
  actionOp: normalized.op,
93786
93722
  actionTarget: normalized.target,
93787
- actor: normalized.actor,
93723
+ signingPublicKey: normalized.signingPublicKey,
93788
93724
  from: normalized.sender,
93789
93725
  s: normalized.sender
93790
93726
  };
@@ -93895,9 +93831,11 @@ function entryAad(entryId) {
93895
93831
  async function sealOwnChatEntry(chatPrivKey, entryId, entry) {
93896
93832
  const key = entryKey(chatPrivKey, entryId);
93897
93833
  try {
93834
+ const { signingKeysByChatKey, ...entryFields } = entry || {};
93898
93835
  const body = {
93899
93836
  v: CHAT_ENTRY_VERSION,
93900
- ...entry,
93837
+ ...entryFields,
93838
+ actors: signingKeysByChatKey || {},
93901
93839
  settings: normalizeChatSettings(entry?.settings)
93902
93840
  };
93903
93841
  const { nonce, ct } = await sealJson(key, body, entryAad(entryId));
@@ -93914,8 +93852,10 @@ async function openOwnChatEntry(chatPrivKey, entryId, body) {
93914
93852
  if (entry?.v !== CHAT_ENTRY_VERSION || !entry?.linkId || !entry?.chatId || !entry?.peerChatPK) {
93915
93853
  throw new Error("invalid chat entry");
93916
93854
  }
93855
+ const { actors, ...entryFields } = entry;
93917
93856
  return {
93918
- ...entry,
93857
+ ...entryFields,
93858
+ signingKeysByChatKey: actors || {},
93919
93859
  settings: normalizeChatSettings(entry.settings)
93920
93860
  };
93921
93861
  } finally {
@@ -93929,10 +93869,10 @@ function makeOwnChatEntry(pair, fields = {}) {
93929
93869
  chatId: pair.chatId,
93930
93870
  peerChatPK: pair.peerChatPK,
93931
93871
  peerUid: cleanText(fields.peerUid),
93932
- actors: {
93933
- ...fields.actors || {},
93934
- [pair.chatPK]: pair.actor.publicKey,
93935
- ...fields.peerActorPK ? { [pair.peerChatPK]: fields.peerActorPK } : {}
93872
+ signingKeysByChatKey: {
93873
+ ...fields.signingKeysByChatKey || {},
93874
+ [pair.chatPK]: pair.signingKey.publicKey,
93875
+ ...fields.peerSigningPublicKey ? { [pair.peerChatPK]: fields.peerSigningPublicKey } : {}
93936
93876
  },
93937
93877
  settings: normalizeChatSettings(fields.settings),
93938
93878
  preview: fields.preview || null,
@@ -93968,7 +93908,7 @@ async function sealPing(senderChatPK, senderPrivKey, recipientChatPK, fields = {
93968
93908
  let key = null;
93969
93909
  try {
93970
93910
  pair = await openChatPair(senderChatPK, senderPrivKey, recipientChatPK, { chatId: fields.chatId });
93971
- if (!pair?.chatId || !pair?.actor?.publicKey || !pair?.linkRoot) {
93911
+ if (!pair?.chatId || !pair?.signingKey?.publicKey || !pair?.linkRoot) {
93972
93912
  throw new Error("chat ping pair required");
93973
93913
  }
93974
93914
  eph = getKeyPair(randomBytes3(32));
@@ -93984,7 +93924,7 @@ async function sealPing(senderChatPK, senderPrivKey, recipientChatPK, fields = {
93984
93924
  chatId: pair.chatId,
93985
93925
  senderChatPK,
93986
93926
  senderUid: cleanText(fields.senderUid),
93987
- actorPK: pair.actor.publicKey,
93927
+ actorPK: pair.signingKey.publicKey,
93988
93928
  messageId: cleanText(fields.messageId),
93989
93929
  ts: Number.isFinite(fields.ts) ? fields.ts : Date.now()
93990
93930
  };
@@ -94014,26 +93954,27 @@ async function openPing(chatPK, chatPrivKey, ping) {
94014
93954
  const key = deriveKey2(shared.subarray(0, 32), "chat-inbox-ping-v1", [epk, chatPK]);
94015
93955
  try {
94016
93956
  const { nonce, ct } = unpackBodyData(ping.body);
94017
- const payload = await openJson(key, nonce, ct, canonicalBytes({ v: CHAT_PING_VERSION, epk }, "chat ping aad"));
94018
- const senderChatPK = cleanText(payload?.senderChatPK);
94019
- if (!senderChatPK || payload?.v !== CHAT_PING_VERSION || payload?.protocol !== CHAT_PROTOCOL_VERSION) {
93957
+ const wirePayload = await openJson(key, nonce, ct, canonicalBytes({ v: CHAT_PING_VERSION, epk }, "chat ping aad"));
93958
+ const senderChatPK = cleanText(wirePayload?.senderChatPK);
93959
+ if (!senderChatPK || wirePayload?.v !== CHAT_PING_VERSION || wirePayload?.protocol !== CHAT_PROTOCOL_VERSION) {
94020
93960
  throw new Error("invalid chat ping payload");
94021
93961
  }
94022
93962
  linkPair = await openChatPair(chatPK, chatPrivKey, senderChatPK);
94023
- if (payload.linkId !== linkPair.linkId || payload.proof !== pingProof(linkPair.linkRoot, payload)) {
93963
+ if (wirePayload.linkId !== linkPair.linkId || wirePayload.proof !== pingProof(linkPair.linkRoot, wirePayload)) {
94024
93964
  throw new Error("invalid chat ping proof");
94025
93965
  }
94026
- const pair = await openChatPair(chatPK, chatPrivKey, senderChatPK, { chatId: payload.chatId });
94027
- if (!pair?.chatId || !pair?.actor?.publicKey) {
93966
+ const pair = await openChatPair(chatPK, chatPrivKey, senderChatPK, { chatId: wirePayload.chatId });
93967
+ if (!pair?.chatId || !pair?.signingKey?.publicKey) {
94028
93968
  closeChatPair(pair);
94029
93969
  throw new Error("invalid chat ping chat");
94030
93970
  }
93971
+ const { actorPK, ...payloadFields } = wirePayload;
94031
93972
  return {
94032
93973
  pair,
94033
93974
  payload: {
94034
- ...payload,
93975
+ ...payloadFields,
94035
93976
  senderChatPK,
94036
- actorPK: cleanText(payload.actorPK)
93977
+ signingPublicKey: cleanText(actorPK)
94037
93978
  }
94038
93979
  };
94039
93980
  } finally {
@@ -94050,27 +93991,24 @@ function makeTtlMs(value) {
94050
93991
  const ms = timestampMs(value, null, { positive: true });
94051
93992
  return ms == null ? null : ms;
94052
93993
  }
94053
- function getMessageTtlMs(retention) {
94054
- return makeTtlMs(newMessageTtlMs(retention));
93994
+ function newStorageTtlMs() {
93995
+ return makeTtlMs(newMessageStorageTtlMs());
94055
93996
  }
94056
93997
  async function profileByChatPK(cloud, chatPK) {
94057
93998
  if (!cloud || !chatPK) {
94058
93999
  return null;
94059
94000
  }
94060
- const peer = await cloud.search.peer.byChatPK(chatPK).catch(() => null);
94001
+ const peer = await cloud.search.peer.byChatPK(chatPK);
94061
94002
  if (!peer) {
94062
94003
  return null;
94063
94004
  }
94064
- return {
94065
- uid: cleanText(peer.uid),
94066
- actorPK: cleanText(peer.actorPK)
94067
- };
94005
+ return { uid: cleanText(peer.uid) };
94068
94006
  }
94069
94007
  async function readOwnEntry(cloud, uid, chatPrivKey, entryId) {
94070
94008
  if (!cloud || !uid || !chatPrivKey || !entryId) {
94071
94009
  return null;
94072
94010
  }
94073
- const record = await cloud.user.chats.read(uid, entryId).catch(() => null);
94011
+ const record = await cloud.user.chats.read(uid, entryId);
94074
94012
  if (!record) {
94075
94013
  return null;
94076
94014
  }
@@ -94104,16 +94042,16 @@ async function ownEntryWrite(cloud, uid, chatPrivKey, pair, fields = {}) {
94104
94042
  }
94105
94043
  const entryId = ownChatEntryId(chatPrivKey, pair.chatId);
94106
94044
  const existing = fields.entry || await readOwnEntry(cloud, uid, chatPrivKey, entryId);
94107
- const peerActorPK = cleanText(fields.peerActorPK) || cleanText(existing?.actors?.[pair.peerChatPK]);
94108
- const actors = {
94109
- ...existing?.actors || {},
94110
- [pair.chatPK]: pair.actor.publicKey,
94111
- ...peerActorPK ? { [pair.peerChatPK]: peerActorPK } : {}
94045
+ const peerSigningPublicKey = cleanText(fields.peerSigningPublicKey) || cleanText(existing?.signingKeysByChatKey?.[pair.peerChatPK]);
94046
+ const signingKeysByChatKey = {
94047
+ ...existing?.signingKeysByChatKey || {},
94048
+ [pair.chatPK]: pair.signingKey.publicKey,
94049
+ ...peerSigningPublicKey ? { [pair.peerChatPK]: peerSigningPublicKey } : {}
94112
94050
  };
94113
94051
  const entry = makeOwnChatEntry(pair, {
94114
94052
  peerUid: fields.peerUid || existing?.peerUid,
94115
- peerActorPK,
94116
- actors,
94053
+ peerSigningPublicKey,
94054
+ signingKeysByChatKey,
94117
94055
  settings: fields.settings || existing?.settings,
94118
94056
  preview: fields.preview || existing?.preview,
94119
94057
  saved: existing?.saved || null,
@@ -94157,9 +94095,9 @@ async function recipientForSend(cloud, receiverChatPK, options, needed) {
94157
94095
  return null;
94158
94096
  }
94159
94097
  const uid = cleanText(options?.receiverUid);
94160
- const actorPK = cleanText(options?.peerActorPK);
94098
+ const signingPublicKey = cleanText(options?.peerSigningPublicKey);
94161
94099
  if (uid) {
94162
- return { uid, actorPK };
94100
+ return { uid, signingPublicKey };
94163
94101
  }
94164
94102
  return profileByChatPK(cloud, receiverChatPK);
94165
94103
  }
@@ -94181,7 +94119,7 @@ async function sendMsg(cloud, senderPubkey, senderPrivkey, receiverChatPK, messa
94181
94119
  const messagePayload = withMessageRetention(message, retention);
94182
94120
  const actionOp = actionOpForPayload(messagePayload);
94183
94121
  const { head, body } = await sealMsg(pair, messagePayload, { op: actionOp, ts: tsMs });
94184
- const ttlMs = actionOp === CHAT_ACTION_OPS.CREATE ? getMessageTtlMs(retention) : null;
94122
+ const ttlMs = actionOp === CHAT_ACTION_OPS.CREATE ? newStorageTtlMs() : null;
94185
94123
  const messageId = cleanText(options?.messageId) || await cloud.chat.messages.id(chatId);
94186
94124
  const msgData = {
94187
94125
  head,
@@ -94193,7 +94131,7 @@ async function sendMsg(cloud, senderPubkey, senderPrivkey, receiverChatPK, messa
94193
94131
  const preview = updatePreview ? sentMessage : null;
94194
94132
  const ownerEntry = updatePreview ? await ownEntryWrite(cloud, cleanText(options?.senderUid), senderPrivkey, pair, {
94195
94133
  peerUid: recipientProfile?.uid || cleanText(options?.receiverUid),
94196
- peerActorPK: recipientProfile?.actorPK,
94134
+ peerSigningPublicKey: recipientProfile?.signingPublicKey,
94197
94135
  entry: options?.ownEntry,
94198
94136
  settings: options?.chatSettings,
94199
94137
  preview,
@@ -94214,7 +94152,7 @@ async function sendMsg(cloud, senderPubkey, senderPrivkey, receiverChatPK, messa
94214
94152
  message: msgData,
94215
94153
  ownerEntry,
94216
94154
  inbox: ping ? { recipientUid: recipientProfile?.uid, ping } : null,
94217
- onCommitted: options?.onCommitted
94155
+ onCommitted: typeof options?.onCommitted === "function" ? (committed) => options.onCommitted({ ...committed, message: sentMessage, preview }) : undefined
94218
94156
  });
94219
94157
  return { chatId, msgId: messageId, cid: head.cid, message: sentMessage, preview, ...write?.skipped ? { skipped: true } : {} };
94220
94158
  }
@@ -94277,7 +94215,7 @@ function messagePermanentUpdateItems(messages) {
94277
94215
  function messageTemporaryUpdateItems(messages) {
94278
94216
  return messageMutationItems(messages, { include: (message) => message?.ttl == null });
94279
94217
  }
94280
- async function makeMsgTemporary(cloud, chatId, messages, ttlMs = newMessageTtlMs()) {
94218
+ async function makeMsgTemporary(cloud, chatId, messages, ttlMs = newMessageStorageTtlMs()) {
94281
94219
  const nextTtlMs = makeTtlMs(ttlMs);
94282
94220
  const items = messageTemporaryUpdateItems(messages);
94283
94221
  if (!cloud || !chatId || !nextTtlMs || !items.length) {
@@ -94286,7 +94224,7 @@ async function makeMsgTemporary(cloud, chatId, messages, ttlMs = newMessageTtlMs
94286
94224
  if (typeof cloud.chat?.messages?.ttl !== "function") {
94287
94225
  throw new Error("message ttl unavailable");
94288
94226
  }
94289
- const result = await cloud.chat.messages.ttl(chatId, items, { permanent: false, ttlMs: nextTtlMs });
94227
+ const result = await cloud.chat.messages.ttl(chatId, items, { permanent: false, ttlMs: nextTtlMs, releaseMediaHold: true });
94290
94228
  return Number.isFinite(result?.updated) ? result.updated : items.length;
94291
94229
  }
94292
94230
  async function makeMsgPermanent(cloud, chatId, messages) {
@@ -94311,7 +94249,7 @@ async function setChatRetention(cloud, chatId, senderPubkey, senderPrivkey, peer
94311
94249
  }
94312
94250
  const systemMessage = {
94313
94251
  ...makeRetentionSystemMsg(nextRetention),
94314
- cid: makeCid(),
94252
+ cid: cleanText(options?.cid) || makeCid(),
94315
94253
  s: senderPubkey
94316
94254
  };
94317
94255
  await sendMsg(cloud, senderPubkey, senderPrivkey, peerChatPK, systemMessage, {
@@ -94322,7 +94260,8 @@ async function setChatRetention(cloud, chatId, senderPubkey, senderPrivkey, peer
94322
94260
  chatExists: true,
94323
94261
  senderUid: options?.senderUid,
94324
94262
  ownEntry: options?.ownEntry,
94325
- chatSettings: { retention: nextRetention }
94263
+ chatSettings: { retention: nextRetention },
94264
+ onCommitted: options?.onCommitted
94326
94265
  });
94327
94266
  return nextRetention;
94328
94267
  }
@@ -94350,7 +94289,7 @@ async function updateMsg(cloud, chatId, msgId, senderPubkey, senderPrivkey, rece
94350
94289
  const preview = updatePreview ? ownerEditedPreview(senderPubkey, newMessage) : null;
94351
94290
  const ownerEntry = updatePreview ? await ownEntryWrite(cloud, cleanText(options?.senderUid), senderPrivkey, pair, {
94352
94291
  peerUid: cleanText(options?.receiverUid),
94353
- peerActorPK: cleanText(options?.peerActorPK),
94292
+ peerSigningPublicKey: cleanText(options?.peerSigningPublicKey),
94354
94293
  entry: options?.ownEntry,
94355
94294
  preview,
94356
94295
  ts: preview?.ts ?? tsMs
@@ -94492,7 +94431,7 @@ async function decryptMsg(msgData, userChatPK, userPrivKey, peerChatPK, options
94492
94431
  }
94493
94432
  try {
94494
94433
  const pair = await getCachedPair(userChatPK, userPrivKey, peerChatPK, { chatId: options?.chatId });
94495
- const message = await openMsg(pair, msgData, { actors: options?.actors, crypto: options?.crypto });
94434
+ const message = await openMsg(pair, msgData, { signingKeysByChatKey: options?.signingKeysByChatKey, crypto: options?.crypto });
94496
94435
  return normalizeDecryptedMsg(msgData, message);
94497
94436
  } catch {
94498
94437
  return null;
@@ -94514,7 +94453,7 @@ function normalizeChatPreview(msgData, message) {
94514
94453
  return canRenderChatPreview(normalized) ? normalized : null;
94515
94454
  }
94516
94455
  async function readExistingEntry(cloud, uid, userPrivKey, entryId) {
94517
- const entry = await cloud.user.chats.read(uid, entryId).catch(() => null);
94456
+ const entry = await cloud.user.chats.read(uid, entryId);
94518
94457
  if (!entry) {
94519
94458
  return null;
94520
94459
  }
@@ -94540,11 +94479,11 @@ function isReadPing(ping) {
94540
94479
  function isDeletePing(ping) {
94541
94480
  return pingKind(ping) === CHAT_PING_KIND_DELETE;
94542
94481
  }
94543
- function pingActors(ping, existing) {
94482
+ function pingSigningKeys(ping, existing) {
94544
94483
  return {
94545
- ...existing?.actors || {},
94546
- [ping.pair.chatPK]: ping.pair.actor.publicKey,
94547
- [ping.payload.senderChatPK]: ping.payload.actorPK
94484
+ ...existing?.signingKeysByChatKey || {},
94485
+ [ping.pair.chatPK]: ping.pair.signingKey.publicKey,
94486
+ [ping.payload.senderChatPK]: ping.payload.signingPublicKey
94548
94487
  };
94549
94488
  }
94550
94489
  function chatFromPing(ping, entryId, existing, preview, userChatPK, ms) {
@@ -94561,7 +94500,7 @@ function chatFromPing(ping, entryId, existing, preview, userChatPK, ms) {
94561
94500
  entryId,
94562
94501
  peerChatPK: ping.payload.senderChatPK,
94563
94502
  peerUid: existing?.peerUid || cleanText(ping.payload.senderUid) || null,
94564
- actors: pingActors(ping, existing),
94503
+ signingKeysByChatKey: pingSigningKeys(ping, existing),
94565
94504
  settings: existing?.settings,
94566
94505
  saved: existing?.saved || null,
94567
94506
  readMs,
@@ -94577,27 +94516,27 @@ async function resolvePingUid(cloud, payload) {
94577
94516
  return null;
94578
94517
  }
94579
94518
  if (claimedUid) {
94580
- const peer2 = await cloud.peer.read(claimedUid).catch(() => null);
94519
+ const peer2 = await cloud.peer.read(claimedUid);
94581
94520
  if (cleanText(peer2?.chatPK) !== senderChatPK) {
94582
94521
  throw new Error("ping sender uid mismatch");
94583
94522
  }
94584
94523
  return claimedUid;
94585
94524
  }
94586
- const peer = await cloud.search.peer.byChatPK(senderChatPK).catch(() => null);
94525
+ const peer = await cloud.search.peer.byChatPK(senderChatPK);
94587
94526
  return peer?.uid || null;
94588
94527
  }
94589
- async function readPingMsg(cloud, userChatPK, userPrivKey, ping, actors, options = {}) {
94528
+ async function readPingMsg(cloud, userChatPK, userPrivKey, ping, signingKeysByChatKey, options = {}) {
94590
94529
  const chatId = ping?.pair?.chatId;
94591
94530
  const messageId = cleanText(ping?.payload?.messageId);
94592
94531
  const peerChatPK = cleanText(ping?.payload?.senderChatPK);
94593
94532
  if (!cloud || !chatId || !messageId || !userChatPK || !userPrivKey || !peerChatPK) {
94594
94533
  return null;
94595
94534
  }
94596
- const data = await cloud.chat.messages.read(chatId, messageId).catch(() => null);
94535
+ const data = await cloud.chat.messages.read(chatId, messageId);
94597
94536
  if (!data) {
94598
94537
  return null;
94599
94538
  }
94600
- const message = await decryptMsg(data, userChatPK, userPrivKey, peerChatPK, { actors, chatId }).catch(() => null);
94539
+ const message = await decryptMsg(data, userChatPK, userPrivKey, peerChatPK, { signingKeysByChatKey, chatId }).catch(() => null);
94601
94540
  const normalized = message ? { ...message, id: data.id, ts: data.ts ?? message.ts, ttl: data.ttl ?? message.ttl } : null;
94602
94541
  if (options.raw === true) {
94603
94542
  return normalized;
@@ -94607,19 +94546,19 @@ async function readPingMsg(cloud, userChatPK, userPrivKey, ping, actors, options
94607
94546
  }
94608
94547
  async function savePing(cloud, uid, userChatPK, userPrivKey, ping, options = {}) {
94609
94548
  const chatId = ping?.pair?.chatId;
94610
- if (!chatId || !cleanText(ping?.payload?.actorPK) || !cleanText(ping?.payload?.senderChatPK)) {
94549
+ if (!chatId || !cleanText(ping?.payload?.signingPublicKey) || !cleanText(ping?.payload?.senderChatPK)) {
94611
94550
  return false;
94612
94551
  }
94613
94552
  const entryId = ownChatEntryId(userPrivKey, chatId);
94614
94553
  const existing = options.existing || await readExistingEntry(cloud, uid, userPrivKey, entryId);
94615
94554
  const peerUid = options.peerUid || await resolvePingUid(cloud, ping.payload);
94616
- const actors = options.actors || pingActors(ping, existing);
94555
+ const signingKeysByChatKey = options.signingKeysByChatKey || pingSigningKeys(ping, existing);
94617
94556
  const hasPreview = Object.prototype.hasOwnProperty.call(options, "preview");
94618
- const preview = hasPreview ? options.preview : await readPingMsg(cloud, userChatPK, userPrivKey, ping, actors);
94557
+ const preview = hasPreview ? options.preview : await readPingMsg(cloud, userChatPK, userPrivKey, ping, signingKeysByChatKey);
94619
94558
  const entry = makeOwnChatEntry(ping.pair, {
94620
94559
  peerUid: peerUid || existing?.peerUid,
94621
- peerActorPK: ping.payload.actorPK || existing?.actors?.[ping.payload.senderChatPK],
94622
- actors,
94560
+ peerSigningPublicKey: ping.payload.signingPublicKey || existing?.signingKeysByChatKey?.[ping.payload.senderChatPK],
94561
+ signingKeysByChatKey,
94623
94562
  settings: existing?.settings,
94624
94563
  preview: preview || existing?.preview,
94625
94564
  readMs: existing?.readMs
@@ -94662,7 +94601,7 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94662
94601
  if (!cloud || !uid || !userChatPK || !userPrivKey) {
94663
94602
  return false;
94664
94603
  }
94665
- const inboxItems = await cloud.inbox.list(uid).catch(() => null);
94604
+ const inboxItems = await cloud.inbox.list(uid);
94666
94605
  if (!inboxItems?.length) {
94667
94606
  return false;
94668
94607
  }
@@ -94717,9 +94656,9 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94717
94656
  if (group.message) {
94718
94657
  const item = group.message;
94719
94658
  const entryId = ownChatEntryId(userPrivKey, item.chatId);
94720
- const actors = pingActors(item.ping, current);
94659
+ const signingKeysByChatKey = pingSigningKeys(item.ping, current);
94721
94660
  const existingMs = timestampMs(current?.preview?.ts, 0) ?? 0;
94722
- const preview = existingMs >= item.ms ? current?.preview || null : await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, actors);
94661
+ const preview = existingMs >= item.ms ? current?.preview || null : await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, signingKeysByChatKey);
94723
94662
  const chat = chatFromPing(item.ping, entryId, current, preview, userChatPK, item.ms);
94724
94663
  if (chat) {
94725
94664
  current = chat;
@@ -94729,7 +94668,7 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94729
94668
  }
94730
94669
  wrote = await savePing(cloud, uid, userChatPK, userPrivKey, item.ping, {
94731
94670
  existing: current,
94732
- actors,
94671
+ signingKeysByChatKey,
94733
94672
  preview
94734
94673
  });
94735
94674
  }
@@ -94737,8 +94676,8 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94737
94676
  const item = group.read;
94738
94677
  const entryId = ownChatEntryId(userPrivKey, item.chatId);
94739
94678
  const existing = current || await readExistingEntry(cloud, uid, userPrivKey, entryId);
94740
- const actors = pingActors(item.ping, existing);
94741
- const receiptPreview = await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, actors);
94679
+ const signingKeysByChatKey = pingSigningKeys(item.ping, existing);
94680
+ const receiptPreview = await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, signingKeysByChatKey);
94742
94681
  const openedPreview = patchReadPingPreview(existing, receiptPreview, userChatPK);
94743
94682
  const chat = chatWithReadPreview(current, openedPreview, userChatPK);
94744
94683
  handled = true;
@@ -94751,7 +94690,7 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94751
94690
  const writeExisting = chat || existing;
94752
94691
  wrote = await savePing(cloud, uid, userChatPK, userPrivKey, item.ping, {
94753
94692
  existing: writeExisting,
94754
- actors,
94693
+ signingKeysByChatKey,
94755
94694
  preview: openedPreview,
94756
94695
  writeTs: false
94757
94696
  }) || wrote;
@@ -94761,8 +94700,8 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94761
94700
  const item = group.delete;
94762
94701
  const entryId = ownChatEntryId(userPrivKey, item.chatId);
94763
94702
  const existing = current || await readExistingEntry(cloud, uid, userPrivKey, entryId);
94764
- const actors = pingActors(item.ping, existing);
94765
- const deletePreview = await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, actors, { raw: true });
94703
+ const signingKeysByChatKey = pingSigningKeys(item.ping, existing);
94704
+ const deletePreview = await readPingMsg(cloud, userChatPK, userPrivKey, item.ping, signingKeysByChatKey, { raw: true });
94766
94705
  const deletedPreview = patchDeletePingPreview(existing, deletePreview);
94767
94706
  const chat = deletedPreview ? chatFromPing(item.ping, entryId, current || existing, deletedPreview, userChatPK, item.ms) : null;
94768
94707
  handled = true;
@@ -94775,7 +94714,7 @@ async function processInbox(cloud, uid, userChatPK, userPrivKey, options = {}) {
94775
94714
  const writeExisting = chat || existing;
94776
94715
  wrote = await savePing(cloud, uid, userChatPK, userPrivKey, item.ping, {
94777
94716
  existing: writeExisting,
94778
- actors,
94717
+ signingKeysByChatKey,
94779
94718
  preview: deletedPreview
94780
94719
  }) || wrote;
94781
94720
  }
@@ -94944,7 +94883,7 @@ async function getChat(cloud, uid, chatId, userChatPK, userPrivKey) {
94944
94883
  return null;
94945
94884
  }
94946
94885
  const entryId = ownChatEntryId(userPrivKey, chatId);
94947
- const entry = await cloud.user.chats.read(uid, entryId).catch(() => null);
94886
+ const entry = await cloud.user.chats.read(uid, entryId);
94948
94887
  if (!entry) {
94949
94888
  return null;
94950
94889
  }
@@ -94979,7 +94918,7 @@ async function decryptChatEntry(entryRecord, userChatPK, userPrivKey) {
94979
94918
  entryId: entryRecord.id,
94980
94919
  peerChatPK: entry.peerChatPK,
94981
94920
  peerUid: entry.peerUid || null,
94982
- actors: entry.actors || {},
94921
+ signingKeysByChatKey: entry.signingKeysByChatKey || {},
94983
94922
  settings: entry.settings,
94984
94923
  saved: entry.saved || null,
94985
94924
  readMs,
@@ -95237,7 +95176,7 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95237
95176
  chatId: chat.id,
95238
95177
  senderUid: active.uid,
95239
95178
  receiverUid: chat.peerUid,
95240
- peerActorPK: chat.actors?.[chat.peerChatPK],
95179
+ peerSigningPublicKey: chat.signingKeysByChatKey?.[chat.peerChatPK],
95241
95180
  ownEntry: chat.entryId ? chat : null,
95242
95181
  chatSettings: normalizeChatSettings(chat.settings)
95243
95182
  };
@@ -95258,10 +95197,7 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95258
95197
  ...chat,
95259
95198
  peerChatPK,
95260
95199
  peerUid: profile.uid || chat.peerUid || null,
95261
- actors: {
95262
- ...chat.actors || {},
95263
- ...peerChatPK && profile.actorPK ? { [peerChatPK]: profile.actorPK } : {}
95264
- }
95200
+ signingKeysByChatKey: chat.signingKeysByChatKey || {}
95265
95201
  };
95266
95202
  }
95267
95203
  async function list(options = {}) {
@@ -95285,11 +95221,11 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95285
95221
  if (chat) {
95286
95222
  return withPeerProfile(chat, profile2);
95287
95223
  }
95288
- const link = await resolvePeerChat(readCloud(), active.chatPK, active.chatPrivKey, profile2.chatPK, options).catch(() => null);
95224
+ const link = await resolvePeerChat(readCloud(), active.chatPK, active.chatPrivKey, profile2.chatPK, options);
95289
95225
  if (!link?.chatId) {
95290
95226
  return null;
95291
95227
  }
95292
- const linkedChat = await getChat(readCloud(), active.uid, link.chatId, active.chatPK, active.chatPrivKey).catch(() => null);
95228
+ const linkedChat = await getChat(readCloud(), active.uid, link.chatId, active.chatPK, active.chatPrivKey);
95293
95229
  return withPeerProfile(linkedChat, profile2);
95294
95230
  };
95295
95231
  if (CHAT_PK_RE.test(value)) {
@@ -95297,12 +95233,12 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95297
95233
  if (chat) {
95298
95234
  return chat;
95299
95235
  }
95300
- const profile2 = await peers.resolve(value).catch(() => null);
95236
+ const profile2 = await peers.resolve(value);
95301
95237
  const resolvedChat = await chatByProfile(profile2);
95302
95238
  if (resolvedChat) {
95303
95239
  return resolvedChat;
95304
95240
  }
95305
- return getChat(readCloud(), active.uid, value, active.chatPK, active.chatPrivKey).catch(() => null);
95241
+ return getChat(readCloud(), active.uid, value, active.chatPK, active.chatPrivKey);
95306
95242
  }
95307
95243
  const profile = await peers.resolve(peer);
95308
95244
  return chatByProfile(profile);
@@ -95312,7 +95248,7 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95312
95248
  const decrypted = [];
95313
95249
  for (const record of page.records || []) {
95314
95250
  const message = await decryptMsg(record, active.chatPK, active.chatPrivKey, chat.peerChatPK, {
95315
- actors: chat.actors,
95251
+ signingKeysByChatKey: chat.signingKeysByChatKey,
95316
95252
  chatId: chat.id
95317
95253
  });
95318
95254
  if (message) {
@@ -95341,7 +95277,7 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95341
95277
  senderUid: active.uid,
95342
95278
  receiverUid: chat.peerUid,
95343
95279
  linkId: chat.linkId,
95344
- peerActorPK: chat.actors?.[chat.peerChatPK],
95280
+ peerSigningPublicKey: chat.signingKeysByChatKey?.[chat.peerChatPK],
95345
95281
  ping: true
95346
95282
  }).catch(() => {});
95347
95283
  }
@@ -95370,9 +95306,9 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95370
95306
  if (message) {
95371
95307
  return { active, chat, message, target: getMessageKey(message) || target };
95372
95308
  }
95373
- const record = await readCloud().chat.messages.read(chat.id, target).catch(() => null);
95309
+ const record = await readCloud().chat.messages.read(chat.id, target);
95374
95310
  const direct = record ? await decryptMsg(record, active.chatPK, active.chatPrivKey, chat.peerChatPK, {
95375
- actors: chat.actors,
95311
+ signingKeysByChatKey: chat.signingKeysByChatKey,
95376
95312
  chatId: chat.id
95377
95313
  }) : null;
95378
95314
  if (!direct) {
@@ -95421,8 +95357,7 @@ function createChatActions({ readCloud, readSession, inbox, peers }) {
95421
95357
  linkVersion: link.version,
95422
95358
  protocol: link.protocol,
95423
95359
  senderUid: active.uid,
95424
- receiverUid: profile.uid,
95425
- peerActorPK: profile.actorPK
95360
+ receiverUid: profile.uid
95426
95361
  });
95427
95362
  return {
95428
95363
  chat: {
@@ -96793,7 +96728,7 @@ function createMoneyActions({ readCloud, readSession, resolvePeer, sendPayload }
96793
96728
  }
96794
96729
  const record = await readCloud().chat.messages.read(chat.id, messageId);
96795
96730
  const message = await decryptMsg(record, active.chatPK, active.chatPrivKey, chat.peerChatPK, {
96796
- actors: chat.actors,
96731
+ signingKeysByChatKey: chat.signingKeysByChatKey,
96797
96732
  chatId: chat.id
96798
96733
  });
96799
96734
  if (!message || message.t !== "req") {
@@ -96816,7 +96751,7 @@ function createMoneyActions({ readCloud, readSession, resolvePeer, sendPayload }
96816
96751
  senderUid: active.uid,
96817
96752
  receiverUid: chat.peerUid,
96818
96753
  linkId: chat.linkId,
96819
- peerActorPK: chat.actors?.[chat.peerChatPK]
96754
+ peerSigningPublicKey: chat.signingKeysByChatKey?.[chat.peerChatPK]
96820
96755
  });
96821
96756
  return {
96822
96757
  ...paid,
@@ -98116,7 +98051,7 @@ replaceTraps((oldTraps) => ({
98116
98051
  has: (target, prop) => !!getMethod2(target, prop) || oldTraps.has(target, prop)
98117
98052
  }));
98118
98053
 
98119
- // ../../node_modules/.bun/@firebase+app@0.15.0/node_modules/@firebase/app/dist/esm/index.esm.js
98054
+ // ../../node_modules/.bun/@firebase+app@0.15.1/node_modules/@firebase/app/dist/esm/index.esm.js
98120
98055
  class PlatformLoggerServiceImpl {
98121
98056
  constructor(container) {
98122
98057
  this.container = container;
@@ -98138,7 +98073,7 @@ function isVersionServiceProvider(provider) {
98138
98073
  return component?.type === "VERSION";
98139
98074
  }
98140
98075
  var name$q = "@firebase/app";
98141
- var version$1 = "0.15.0";
98076
+ var version$1 = "0.15.1";
98142
98077
  var logger2 = new Logger2("@firebase/app");
98143
98078
  var name$p = "@firebase/app-compat";
98144
98079
  var name$o = "@firebase/analytics-compat";
@@ -98166,7 +98101,7 @@ var name$3 = "@firebase/firestore";
98166
98101
  var name$2 = "@firebase/ai";
98167
98102
  var name$1 = "@firebase/firestore-compat";
98168
98103
  var name2 = "firebase";
98169
- var version2 = "12.15.0";
98104
+ var version2 = "12.16.0";
98170
98105
  var DEFAULT_ENTRY_NAME2 = "[DEFAULT]";
98171
98106
  var PLATFORM_LOG_STRING = {
98172
98107
  [name$q]: "fire-core",
@@ -98616,12 +98551,12 @@ function registerCoreComponents(variant) {
98616
98551
  }
98617
98552
  registerCoreComponents("");
98618
98553
 
98619
- // ../../node_modules/.bun/firebase@12.15.0+419ecb626e0dfd90/node_modules/firebase/app/dist/index.mjs
98554
+ // ../../node_modules/.bun/firebase@12.16.0+419ecb626e0dfd90/node_modules/firebase/app/dist/index.mjs
98620
98555
  var name3 = "firebase";
98621
- var version3 = "12.15.0";
98556
+ var version3 = "12.16.0";
98622
98557
  registerVersion(name3, version3, "app");
98623
98558
 
98624
- // ../../node_modules/.bun/@firebase+auth@1.13.3+92862aca8e915725/node_modules/@firebase/auth/dist/node-esm/totp-65577477.js
98559
+ // ../../node_modules/.bun/@firebase+auth@1.13.3+8807f692d12224be/node_modules/@firebase/auth/dist/node-esm/totp-65577477.js
98625
98560
  function _prodErrorMap() {
98626
98561
  return {
98627
98562
  ["dependent-sdk-initialized-before-auth"]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is " + "initialized. Please be sure to call `initializeAuth` or `getAuth` before " + "starting any other Firebase SDK."
@@ -101914,7 +101849,7 @@ var Md5;
101914
101849
  Integer = bloom_blob_es2018.Integer = t;
101915
101850
  }).apply(typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
101916
101851
 
101917
- // ../../node_modules/.bun/@firebase+firestore@4.16.0+5bd1f26d8863c124/node_modules/@firebase/firestore/dist/common-cc96d03b.node.mjs
101852
+ // ../../node_modules/.bun/@firebase+firestore@4.16.0+80db1b7a714a6e79/node_modules/@firebase/firestore/dist/common-cc96d03b.node.mjs
101918
101853
  var grpc = __toESM(require_src3(), 1);
101919
101854
  var protoLoader = __toESM(require_src2(), 1);
101920
101855
  import { TextEncoder as TextEncoder2, inspect as inspect2, TextDecoder as TextDecoder2 } from "util";
@@ -106117,7 +106052,7 @@ class RE2JS {
106117
106052
  }
106118
106053
  }
106119
106054
 
106120
- // ../../node_modules/.bun/@firebase+firestore@4.16.0+5bd1f26d8863c124/node_modules/@firebase/firestore/dist/common-cc96d03b.node.mjs
106055
+ // ../../node_modules/.bun/@firebase+firestore@4.16.0+80db1b7a714a6e79/node_modules/@firebase/firestore/dist/common-cc96d03b.node.mjs
106121
106056
  class User {
106122
106057
  constructor(uid) {
106123
106058
  this.uid = uid;
@@ -110823,6 +110758,31 @@ function toMutationDocument(serializer, key, fields) {
110823
110758
  fields: fields.value.mapValue.fields
110824
110759
  };
110825
110760
  }
110761
+ function fromFound(serializer, doc) {
110762
+ hardAssert(!!doc.found, 43571);
110763
+ assertPresent(doc.found.name);
110764
+ assertPresent(doc.found.updateTime);
110765
+ const key = fromName(serializer, doc.found.name);
110766
+ const version6 = fromVersion(doc.found.updateTime);
110767
+ const createTime = doc.found.createTime ? fromVersion(doc.found.createTime) : SnapshotVersion.min();
110768
+ const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });
110769
+ return MutableDocument.newFoundDocument(key, version6, createTime, data);
110770
+ }
110771
+ function fromMissing(serializer, result) {
110772
+ hardAssert(!!result.missing, 3894);
110773
+ hardAssert(!!result.readTime, 22933);
110774
+ const key = fromName(serializer, result.missing);
110775
+ const version6 = fromVersion(result.readTime);
110776
+ return MutableDocument.newNoDocument(key, version6);
110777
+ }
110778
+ function fromBatchGetDocumentsResponse(serializer, result) {
110779
+ if ("found" in result) {
110780
+ return fromFound(serializer, result);
110781
+ } else if ("missing" in result) {
110782
+ return fromMissing(serializer, result);
110783
+ }
110784
+ return fail(7234, { result });
110785
+ }
110826
110786
  function fromWatchChange(serializer, change) {
110827
110787
  let watchChange;
110828
110788
  if ("targetChange" in change) {
@@ -116700,6 +116660,34 @@ class DatastoreImpl extends Datastore {
116700
116660
  function newDatastore(authCredentials, appCheckCredentials, connection, serializer) {
116701
116661
  return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer);
116702
116662
  }
116663
+ async function invokeCommitRpc(datastore, mutations) {
116664
+ const datastoreImpl = debugCast(datastore);
116665
+ const request = {
116666
+ writes: mutations.map((m) => toMutation(datastoreImpl.serializer, m))
116667
+ };
116668
+ await datastoreImpl.invokeRPC("Commit", datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request);
116669
+ }
116670
+ async function invokeBatchGetDocumentsRpc(datastore, keys) {
116671
+ const datastoreImpl = debugCast(datastore);
116672
+ const request = {
116673
+ documents: keys.map((k) => toName(datastoreImpl.serializer, k))
116674
+ };
116675
+ const response = await datastoreImpl.invokeStreamingRPC("BatchGetDocuments", datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length);
116676
+ const docs = new Map;
116677
+ response.forEach((proto) => {
116678
+ const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);
116679
+ docs.set(doc.key.toString(), doc);
116680
+ });
116681
+ const result = [];
116682
+ keys.forEach((key) => {
116683
+ const doc = docs.get(key.toString());
116684
+ hardAssert(!!doc, 55234, {
116685
+ key
116686
+ });
116687
+ result.push(doc);
116688
+ });
116689
+ return result;
116690
+ }
116703
116691
  function newPersistentWriteStream(datastore, queue, listener) {
116704
116692
  const datastoreImpl = debugCast(datastore);
116705
116693
  datastoreImpl.verifyInitialized();
@@ -125372,6 +125360,172 @@ class AsyncObserver {
125372
125360
  }, 0);
125373
125361
  }
125374
125362
  }
125363
+ class Transaction2 {
125364
+ constructor(datastore) {
125365
+ this.datastore = datastore;
125366
+ this.readVersions = new Map;
125367
+ this.mutations = [];
125368
+ this.committed = false;
125369
+ this.lastTransactionError = null;
125370
+ this.writtenDocs = new Set;
125371
+ }
125372
+ async lookup(keys) {
125373
+ this.ensureCommitNotCalled();
125374
+ if (this.mutations.length > 0) {
125375
+ this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
125376
+ throw this.lastTransactionError;
125377
+ }
125378
+ const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);
125379
+ docs.forEach((doc2) => this.recordVersion(doc2));
125380
+ return docs;
125381
+ }
125382
+ set(key, data) {
125383
+ this.write(data.toMutation(key, this.precondition(key)));
125384
+ this.writtenDocs.add(key.toString());
125385
+ }
125386
+ update(key, data) {
125387
+ try {
125388
+ this.write(data.toMutation(key, this.preconditionForUpdate(key)));
125389
+ } catch (e) {
125390
+ this.lastTransactionError = e;
125391
+ }
125392
+ this.writtenDocs.add(key.toString());
125393
+ }
125394
+ delete(key) {
125395
+ this.write(new DeleteMutation(key, this.precondition(key)));
125396
+ this.writtenDocs.add(key.toString());
125397
+ }
125398
+ async commit() {
125399
+ this.ensureCommitNotCalled();
125400
+ if (this.lastTransactionError) {
125401
+ throw this.lastTransactionError;
125402
+ }
125403
+ const unwritten = this.readVersions;
125404
+ this.mutations.forEach((mutation) => {
125405
+ unwritten.delete(mutation.key.toString());
125406
+ });
125407
+ unwritten.forEach((_, path) => {
125408
+ const key = DocumentKey.fromPath(path);
125409
+ this.mutations.push(new VerifyMutation(key, this.precondition(key)));
125410
+ });
125411
+ await invokeCommitRpc(this.datastore, this.mutations);
125412
+ this.committed = true;
125413
+ }
125414
+ recordVersion(doc2) {
125415
+ let docVersion;
125416
+ if (doc2.isFoundDocument()) {
125417
+ docVersion = doc2.version;
125418
+ } else if (doc2.isNoDocument()) {
125419
+ docVersion = SnapshotVersion.min();
125420
+ } else {
125421
+ throw fail(50498, {
125422
+ documentName: doc2.constructor.name
125423
+ });
125424
+ }
125425
+ const existingVersion = this.readVersions.get(doc2.key.toString());
125426
+ if (existingVersion) {
125427
+ if (!docVersion.isEqual(existingVersion)) {
125428
+ throw new FirestoreError(Code.ABORTED, "Document version changed between two reads.");
125429
+ }
125430
+ } else {
125431
+ this.readVersions.set(doc2.key.toString(), docVersion);
125432
+ }
125433
+ }
125434
+ precondition(key) {
125435
+ const version6 = this.readVersions.get(key.toString());
125436
+ if (!this.writtenDocs.has(key.toString()) && version6) {
125437
+ if (version6.isEqual(SnapshotVersion.min())) {
125438
+ return Precondition.exists(false);
125439
+ } else {
125440
+ return Precondition.updateTime(version6);
125441
+ }
125442
+ } else {
125443
+ return Precondition.none();
125444
+ }
125445
+ }
125446
+ preconditionForUpdate(key) {
125447
+ const version6 = this.readVersions.get(key.toString());
125448
+ if (!this.writtenDocs.has(key.toString()) && version6) {
125449
+ if (version6.isEqual(SnapshotVersion.min())) {
125450
+ throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
125451
+ }
125452
+ return Precondition.updateTime(version6);
125453
+ } else {
125454
+ return Precondition.exists(true);
125455
+ }
125456
+ }
125457
+ write(mutation) {
125458
+ this.ensureCommitNotCalled();
125459
+ this.mutations.push(mutation);
125460
+ }
125461
+ ensureCommitNotCalled() {}
125462
+ }
125463
+
125464
+ class TransactionRunner {
125465
+ constructor(asyncQueue, datastore, options2, updateFunction, deferred) {
125466
+ this.asyncQueue = asyncQueue;
125467
+ this.datastore = datastore;
125468
+ this.options = options2;
125469
+ this.updateFunction = updateFunction;
125470
+ this.deferred = deferred;
125471
+ this.attemptsRemaining = options2.maxAttempts;
125472
+ this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry");
125473
+ }
125474
+ run() {
125475
+ this.attemptsRemaining -= 1;
125476
+ this.runWithBackOff();
125477
+ }
125478
+ runWithBackOff() {
125479
+ this.backoff.backoffAndRun(async () => {
125480
+ const transaction = new Transaction2(this.datastore);
125481
+ const userPromise = this.tryRunUpdateFunction(transaction);
125482
+ if (userPromise) {
125483
+ userPromise.then((result) => {
125484
+ this.asyncQueue.enqueueAndForget(() => {
125485
+ return transaction.commit().then(() => {
125486
+ this.deferred.resolve(result);
125487
+ }).catch((commitError) => {
125488
+ this.handleTransactionError(commitError);
125489
+ });
125490
+ });
125491
+ }).catch((userPromiseError) => {
125492
+ this.handleTransactionError(userPromiseError);
125493
+ });
125494
+ }
125495
+ });
125496
+ }
125497
+ tryRunUpdateFunction(transaction) {
125498
+ try {
125499
+ const userPromise = this.updateFunction(transaction);
125500
+ if (isNullOrUndefined(userPromise) || !userPromise.catch || !userPromise.then) {
125501
+ this.deferred.reject(Error("Transaction callback must return a Promise"));
125502
+ return null;
125503
+ }
125504
+ return userPromise;
125505
+ } catch (error) {
125506
+ this.deferred.reject(error);
125507
+ return null;
125508
+ }
125509
+ }
125510
+ handleTransactionError(error) {
125511
+ if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {
125512
+ this.attemptsRemaining -= 1;
125513
+ this.asyncQueue.enqueueAndForget(() => {
125514
+ this.runWithBackOff();
125515
+ return Promise.resolve();
125516
+ });
125517
+ } else {
125518
+ this.deferred.reject(error);
125519
+ }
125520
+ }
125521
+ isRetryableTransactionError(error) {
125522
+ if (error?.name === "FirebaseError") {
125523
+ const code = error.code;
125524
+ return code === "aborted" || code === "failed-precondition" || code === "already-exists" || !isPermanentError(code);
125525
+ }
125526
+ return false;
125527
+ }
125528
+ }
125375
125529
  var LOG_TAG$1 = "FirestoreClient";
125376
125530
  var MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;
125377
125531
  var DOM_EXCEPTION_INVALID_STATE = 11;
@@ -125506,6 +125660,9 @@ async function ensureOnlineComponents(client2) {
125506
125660
  function getSyncEngine(client2) {
125507
125661
  return ensureOnlineComponents(client2).then((c) => c.syncEngine);
125508
125662
  }
125663
+ function getDatastore(client2) {
125664
+ return ensureOnlineComponents(client2).then((c) => c.datastore);
125665
+ }
125509
125666
  async function getEventManager(client2) {
125510
125667
  const onlineComponentProvider = await ensureOnlineComponents(client2);
125511
125668
  const eventManager = onlineComponentProvider.eventManager;
@@ -125554,6 +125711,14 @@ function firestoreClientWrite(client2, mutations) {
125554
125711
  });
125555
125712
  return deferred.promise;
125556
125713
  }
125714
+ function firestoreClientTransaction(client2, updateFunction, options2) {
125715
+ const deferred = new Deferred2;
125716
+ client2.asyncQueue.enqueueAndForget(async () => {
125717
+ const datastore = await getDatastore(client2);
125718
+ new TransactionRunner(client2.asyncQueue, datastore, options2, updateFunction, deferred).run();
125719
+ });
125720
+ return deferred.promise;
125721
+ }
125557
125722
  function readDocumentViaSnapshotListener(eventManager, asyncQueue, key, options2, result) {
125558
125723
  const wrappedObserver = new AsyncObserver({
125559
125724
  next: (snap) => {
@@ -125908,7 +126073,7 @@ class ExpUserDataWriter extends AbstractUserDataWriter {
125908
126073
  return new DocumentReference(this.firestore, null, key);
125909
126074
  }
125910
126075
  }
125911
- // ../../node_modules/.bun/@firebase+firestore@4.16.0+5bd1f26d8863c124/node_modules/@firebase/firestore/dist/index.node.mjs
126076
+ // ../../node_modules/.bun/@firebase+firestore@4.16.0+80db1b7a714a6e79/node_modules/@firebase/firestore/dist/index.node.mjs
125912
126077
  var import_grpc_js = __toESM(require_src3(), 1);
125913
126078
  var import_proto_loader = __toESM(require_src2(), 1);
125914
126079
  var name$12 = "@firebase/firestore";
@@ -126306,6 +126471,20 @@ function applyFirestoreDataConverter(converter, value, options2) {
126306
126471
  }
126307
126472
  return convertedValue;
126308
126473
  }
126474
+
126475
+ class LiteUserDataWriter extends AbstractUserDataWriter {
126476
+ constructor(firestore) {
126477
+ super();
126478
+ this.firestore = firestore;
126479
+ }
126480
+ convertBytes(bytes) {
126481
+ return new Bytes(bytes);
126482
+ }
126483
+ convertReference(name5) {
126484
+ const key = this.convertDocumentKey(name5, this.firestore._databaseId);
126485
+ return new DocumentReference(this.firestore, null, key);
126486
+ }
126487
+ }
126309
126488
  var encoder2 = newTextEncoder();
126310
126489
  function lengthPrefixedString(o) {
126311
126490
  const str = JSON.stringify(o);
@@ -126720,6 +126899,15 @@ function resultChangeType(type) {
126720
126899
  return fail(61501, { type });
126721
126900
  }
126722
126901
  }
126902
+ var DEFAULT_TRANSACTION_OPTIONS = {
126903
+ maxAttempts: 5
126904
+ };
126905
+ function validateTransactionOptions(options2) {
126906
+ if (options2.maxAttempts < 1) {
126907
+ throw new FirestoreError(Code.INVALID_ARGUMENT, "Max attempts must be at least 1");
126908
+ }
126909
+ }
126910
+
126723
126911
  class WriteBatch {
126724
126912
  constructor(_firestore, _commitHandler) {
126725
126913
  this._firestore = _firestore;
@@ -126777,6 +126965,79 @@ function validateReference(documentRef, firestore) {
126777
126965
  return documentRef;
126778
126966
  }
126779
126967
  }
126968
+
126969
+ class Transaction$1 {
126970
+ constructor(_firestore, _transaction) {
126971
+ this._firestore = _firestore;
126972
+ this._transaction = _transaction;
126973
+ this._dataReader = newUserDataReader(_firestore);
126974
+ }
126975
+ get(documentRef) {
126976
+ const ref = validateReference(documentRef, this._firestore);
126977
+ const userDataWriter = new LiteUserDataWriter(this._firestore);
126978
+ return this._transaction.lookup([ref._key]).then((docs) => {
126979
+ if (!docs || docs.length !== 1) {
126980
+ return fail(24041);
126981
+ }
126982
+ const doc3 = docs[0];
126983
+ if (doc3.isFoundDocument()) {
126984
+ return new DocumentSnapshot$1(this._firestore, userDataWriter, doc3.key, doc3, ref.converter);
126985
+ } else if (doc3.isNoDocument()) {
126986
+ return new DocumentSnapshot$1(this._firestore, userDataWriter, ref._key, null, ref.converter);
126987
+ } else {
126988
+ throw fail(18433, {
126989
+ doc: doc3
126990
+ });
126991
+ }
126992
+ });
126993
+ }
126994
+ set(documentRef, value, options2) {
126995
+ const ref = validateReference(documentRef, this._firestore);
126996
+ const convertedValue = applyFirestoreDataConverter(ref.converter, value, options2);
126997
+ const parsed = parseSetData(this._dataReader, "Transaction.set", ref._key, convertedValue, ref.converter !== null, options2);
126998
+ this._transaction.set(ref._key, parsed);
126999
+ return this;
127000
+ }
127001
+ update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
127002
+ const ref = validateReference(documentRef, this._firestore);
127003
+ fieldOrUpdateData = getModularInstance(fieldOrUpdateData);
127004
+ let parsed;
127005
+ if (typeof fieldOrUpdateData === "string" || fieldOrUpdateData instanceof FieldPath) {
127006
+ parsed = parseUpdateVarargs(this._dataReader, "Transaction.update", ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
127007
+ } else {
127008
+ parsed = parseUpdateData(this._dataReader, "Transaction.update", ref._key, fieldOrUpdateData);
127009
+ }
127010
+ this._transaction.update(ref._key, parsed);
127011
+ return this;
127012
+ }
127013
+ delete(documentRef) {
127014
+ const ref = validateReference(documentRef, this._firestore);
127015
+ this._transaction.delete(ref._key);
127016
+ return this;
127017
+ }
127018
+ }
127019
+
127020
+ class Transaction3 extends Transaction$1 {
127021
+ constructor(_firestore, _transaction) {
127022
+ super(_firestore, _transaction);
127023
+ this._firestore = _firestore;
127024
+ }
127025
+ get(documentRef) {
127026
+ const ref = validateReference(documentRef, this._firestore);
127027
+ const userDataWriter = new ExpUserDataWriter(this._firestore);
127028
+ return super.get(documentRef).then((liteDocumentSnapshot) => new DocumentSnapshot(this._firestore, userDataWriter, ref._key, liteDocumentSnapshot._document, new SnapshotMetadata(false, false), ref.converter));
127029
+ }
127030
+ }
127031
+ function runTransaction(firestore, updateFunction, options2) {
127032
+ firestore = cast(firestore, Firestore);
127033
+ const optionsWithDefaults = {
127034
+ ...DEFAULT_TRANSACTION_OPTIONS,
127035
+ ...options2
127036
+ };
127037
+ validateTransactionOptions(optionsWithDefaults);
127038
+ const client2 = ensureFirestoreConfigured(firestore);
127039
+ return firestoreClientTransaction(client2, (internalTransaction) => updateFunction(new Transaction3(firestore, internalTransaction)), optionsWithDefaults);
127040
+ }
126780
127041
  function isPartialObserver(obj) {
126781
127042
  return implementsAnyMethods2(obj, ["next", "error", "complete"]);
126782
127043
  }
@@ -126921,7 +127182,7 @@ function writeBatch(firestore) {
126921
127182
  }
126922
127183
  var persistentCacheIndexManagerByFirestore = new WeakMap;
126923
127184
  registerFirestore("node");
126924
- // ../../node_modules/.bun/@firebase+functions@0.13.5+5bd1f26d8863c124/node_modules/@firebase/functions/dist/esm/index.esm.js
127185
+ // ../../node_modules/.bun/@firebase+functions@0.13.5+80db1b7a714a6e79/node_modules/@firebase/functions/dist/esm/index.esm.js
126925
127186
  var LONG_TYPE = "type.googleapis.com/google.protobuf.Int64Value";
126926
127187
  var UNSIGNED_LONG_TYPE = "type.googleapis.com/google.protobuf.UInt64Value";
126927
127188
  function mapValues(o, f) {
@@ -127486,7 +127747,7 @@ function httpsCallable(functionsInstance, name6, options2) {
127486
127747
  return httpsCallable$1(getModularInstance(functionsInstance), name6, options2);
127487
127748
  }
127488
127749
  registerFunctions();
127489
- // ../../node_modules/.bun/@firebase+storage@0.14.3+5bd1f26d8863c124/node_modules/@firebase/storage/dist/node-esm/index.node.esm.js
127750
+ // ../../node_modules/.bun/@firebase+storage@0.14.3+80db1b7a714a6e79/node_modules/@firebase/storage/dist/node-esm/index.node.esm.js
127490
127751
  var DEFAULT_HOST2 = "firebasestorage.googleapis.com";
127491
127752
  var CONFIG_STORAGE_BUCKET_KEY = "storageBucket";
127492
127753
  var DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;
@@ -128963,7 +129224,7 @@ function registerStorage() {
128963
129224
  registerVersion(name6, version8);
128964
129225
  }
128965
129226
  registerStorage();
128966
- // ../../node_modules/.bun/@firebase+auth@1.13.3+77f33dfe73ba26c8/node_modules/@firebase/auth/dist/node-esm/totp-65577477.js
129227
+ // ../../node_modules/.bun/@firebase+auth@1.13.3+5d31dd782a334479/node_modules/@firebase/auth/dist/node-esm/totp-65577477.js
128967
129228
  function _prodErrorMap2() {
128968
129229
  return {
128969
129230
  ["dependent-sdk-initialized-before-auth"]: "Another Firebase SDK was initialized and is trying to use Auth before Auth is " + "initialized. Please be sure to call `initializeAuth` or `getAuth` before " + "starting any other Firebase SDK."
@@ -132563,10 +132824,10 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132563
132824
  }
132564
132825
  const unlinked = targets.filter((target) => !target.linkId);
132565
132826
  const unlinkedStatuses = await Promise.all(unlinked.map(async (target) => {
132566
- const chatSnap = await getDocFromServer(doc(db, "chats", target.chatId)).catch(() => null);
132827
+ const chatSnap = await getDocFromServer(doc(db, "chats", target.chatId));
132567
132828
  return {
132568
132829
  chatId: target.chatId,
132569
- active: chatSnap?.data?.()?.deleted !== true
132830
+ active: !chatSnap.exists() || chatSnap.data()?.deleted !== true
132570
132831
  };
132571
132832
  }));
132572
132833
  for (const status of unlinkedStatuses) {
@@ -132590,6 +132851,10 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132590
132851
  await callFunction("submitReport", payload);
132591
132852
  return true;
132592
132853
  }
132854
+ async function submitBug(payload) {
132855
+ const result = await callFunction("submitBug", payload);
132856
+ return result || true;
132857
+ }
132593
132858
  async function submitFeedback(payload) {
132594
132859
  const result = await callFunction("submitFeedback", payload);
132595
132860
  return result || true;
@@ -132792,7 +133057,7 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132792
133057
  return chatMessagesPage(snap, count, { reverse: messagesQuery.reverse });
132793
133058
  }
132794
133059
  async function readChatMessage(chatId, messageId) {
132795
- const snap = await getDocFromServer(chatMessageDoc(chatId, messageId)).catch(() => null);
133060
+ const snap = await getDocFromServer(chatMessageDoc(chatId, messageId));
132796
133061
  return messageRecordFromDoc(snap);
132797
133062
  }
132798
133063
  function cleanMessageWrite(message) {
@@ -132888,11 +133153,31 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132888
133153
  throw new Error("message ttl required");
132889
133154
  }
132890
133155
  const ttl = options2?.permanent === true ? null : Timestamp2.fromMillis(ttlMs);
132891
- const updateItems = async (nextTtl = ttl, targetItems = items) => {
133156
+ const updateItems = async (nextTtl = ttl, targetItems = items, { shortenOnly = false } = {}) => {
132892
133157
  const updated2 = [];
132893
- for (const item of targetItems) {
132894
- await updateDoc(chatMessageDoc(chatId, item.id), { ttl: nextTtl });
132895
- updated2.push(item);
133158
+ for (let index = 0;index < targetItems.length; index += CHAT_TTL_WRITE_BATCH_SIZE) {
133159
+ const chunk = targetItems.slice(index, index + CHAT_TTL_WRITE_BATCH_SIZE);
133160
+ if (shortenOnly) {
133161
+ const chunkUpdated = await runTransaction(db, async (transaction) => {
133162
+ const refs = chunk.map((item) => chatMessageDoc(chatId, item.id));
133163
+ const snapshots = await Promise.all(refs.map((messageRef) => transaction.get(messageRef)));
133164
+ const eligible = [];
133165
+ snapshots.forEach((snapshot, snapshotIndex) => {
133166
+ const currentTtlMs = timestampMs(snapshot?.data?.()?.ttl, null);
133167
+ if (snapshot?.exists?.() && currentTtlMs != null && currentTtlMs > ttlMs) {
133168
+ transaction.update(refs[snapshotIndex], { ttl: nextTtl });
133169
+ eligible.push(chunk[snapshotIndex]);
133170
+ }
133171
+ });
133172
+ return eligible;
133173
+ });
133174
+ updated2.push(...chunkUpdated);
133175
+ continue;
133176
+ }
133177
+ const batch = writeBatch(db);
133178
+ chunk.forEach((item) => batch.update(chatMessageDoc(chatId, item.id), { ttl: nextTtl }));
133179
+ await batch.commit();
133180
+ updated2.push(...chunk);
132896
133181
  }
132897
133182
  return updated2;
132898
133183
  };
@@ -132910,6 +133195,10 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132910
133195
  throw error;
132911
133196
  }
132912
133197
  }
133198
+ if (options2?.releaseMediaHold !== true) {
133199
+ const updated2 = await updateItems(ttl, items, { shortenOnly: options2?.shortenOnly === true });
133200
+ return { updated: updated2.length };
133201
+ }
132913
133202
  let updated = [];
132914
133203
  try {
132915
133204
  updated = await updateItems();
@@ -132949,7 +133238,7 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
132949
133238
  requireUid(uid);
132950
133239
  if (!entryId)
132951
133240
  throw new Error("chat entry id required");
132952
- const snap = await getDocFromServer(doc(db, "users", uid, "chats", entryId)).catch(() => null);
133241
+ const snap = await getDocFromServer(doc(db, "users", uid, "chats", entryId));
132953
133242
  return userChatRecordFromDoc(snap);
132954
133243
  }
132955
133244
  async function writeUserChat(uid, entryId, { body, tsMs, touchTs = false } = {}) {
@@ -133046,6 +133335,12 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
133046
133335
  onUpdate?.(recordsFromSnapshot(snap));
133047
133336
  }, onError);
133048
133337
  }
133338
+ function watchAdminBugs(onUpdate, onError, options2 = {}) {
133339
+ const count = Math.min(positiveInt(options2?.count, 100), 250);
133340
+ return onSnapshot(query(collection(db, "bugs"), orderBy("createdAt", "desc"), limit(count)), (snap) => {
133341
+ onUpdate?.(recordsFromSnapshot(snap));
133342
+ }, onError);
133343
+ }
133049
133344
  function watchAdminBots(onUpdate, onError) {
133050
133345
  return onSnapshot(collection(db, "bots"), (snap) => {
133051
133346
  onUpdate?.(recordsFromSnapshot(snap));
@@ -133219,6 +133514,9 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
133219
133514
  push: pushInbox
133220
133515
  },
133221
133516
  admin: {
133517
+ bugs: {
133518
+ watch: watchAdminBugs
133519
+ },
133222
133520
  reports: {
133223
133521
  watchOffenders: watchAdminReportOffenders,
133224
133522
  watchUser: watchAdminUserReports,
@@ -133249,6 +133547,9 @@ function createFirebaseCloud({ db, auth: auth3, getAuth: getAuth3, functions: fu
133249
133547
  upload: uploadReportEvidence
133250
133548
  }
133251
133549
  },
133550
+ bugs: {
133551
+ submit: submitBug
133552
+ },
133252
133553
  feedback: {
133253
133554
  submit: submitFeedback
133254
133555
  },
@@ -134807,57 +135108,203 @@ class ProfileStore {
134807
135108
  // src/mcp.js
134808
135109
  import { createInterface } from "readline";
134809
135110
  import process4 from "process";
134810
- function tool(name8, description, properties = {}, required = []) {
134811
- return {
135111
+ // package.json
135112
+ var package_default = {
135113
+ name: "@glyphteck/veyl",
135114
+ version: "0.3.1",
135115
+ license: "Apache-2.0",
135116
+ type: "module",
135117
+ description: "Programmable Bun client for Veyl accounts, vaults, chat, and wallet payments.",
135118
+ exports: {
135119
+ ".": "./dist/index.js"
135120
+ },
135121
+ bin: {
135122
+ veyl: "dist/cli.js"
135123
+ },
135124
+ files: [
135125
+ "dist",
135126
+ "docs",
135127
+ "README.md",
135128
+ "package.json"
135129
+ ],
135130
+ engines: {
135131
+ bun: ">=1.3.0"
135132
+ },
135133
+ publishConfig: {
135134
+ access: "public"
135135
+ },
135136
+ scripts: {
135137
+ build: "bun build src/index.js src/cli.js --target=bun --outdir dist",
135138
+ prepack: "bun run build",
135139
+ start: "bun src/cli.js",
135140
+ lint: "eslint src --quiet"
135141
+ }
135142
+ };
135143
+
135144
+ // src/commands.js
135145
+ var stringProp = Object.freeze({ type: "string" });
135146
+ var numberProp = Object.freeze({ type: "number" });
135147
+ var booleanProp = Object.freeze({ type: "boolean" });
135148
+ var objectProp = Object.freeze({ type: "object" });
135149
+ function command({ name: name8, group, apiNames, description, properties = {}, required = [], paths = [], shortUsage = "", structuredUsage = "", cliInput, invoke, invokeCli, mcp = true }) {
135150
+ return Object.freeze({
134812
135151
  name: name8,
135152
+ group,
135153
+ apiNames: Object.freeze(apiNames || []),
134813
135154
  description,
134814
- inputSchema: {
134815
- type: "object",
134816
- properties,
134817
- ...required.length ? { required } : {}
134818
- }
134819
- };
134820
- }
134821
- var stringProp = { type: "string" };
134822
- var numberProp = { type: "number" };
134823
- var booleanProp = { type: "boolean" };
134824
- var objectProp = { type: "object" };
134825
- var TOOLS = [
134826
- tool("account_create", "Create a Veyl account headlessly.", { username: stringProp, network: stringProp }, ["username"]),
134827
- tool("account_login", "Log in with the local machine credential.", { username: stringProp }),
134828
- tool("account_me", "Show the current local account."),
134829
- tool("vault_create", "Create and upload the local encrypted vault.", { secret: stringProp, saveSecret: booleanProp }),
134830
- tool("vault_unlock", "Unlock the local encrypted vault.", { secret: stringProp }),
134831
- tool("vault_lock", "Lock the wallet and chat session."),
134832
- tool("chat_list", "List chats.", { count: numberProp }),
134833
- tool("chat_read", "Read display messages from a chat.", { peer: stringProp, count: numberProp }, ["peer"]),
134834
- tool("chat_send", "Send a text message.", { peer: stringProp, message: stringProp }, ["peer", "message"]),
134835
- tool("chat_reply", "Reply to one displayed message. Pass either a peer plus messageId or a message event from veyl listen.", { peer: stringProp, messageId: stringProp, event: objectProp, message: stringProp }, ["message"]),
134836
- tool("chat_react", "React to one displayed message.", { peer: stringProp, messageId: stringProp, emoji: stringProp }, ["peer", "messageId", "emoji"]),
134837
- tool("chat_react_to", "React to a displayed message or a message event from veyl listen.", { peer: stringProp, messageId: stringProp, event: objectProp, emoji: stringProp }, ["emoji"]),
134838
- tool("chat_unreact", "Remove your reaction from one displayed message.", { peer: stringProp, messageId: stringProp }, ["peer", "messageId"]),
134839
- tool("chat_save", "Keep one displayed message permanently.", { peer: stringProp, messageId: stringProp }, ["peer", "messageId"]),
134840
- tool("chat_unsave", "Return one displayed message to normal temporary retention.", { peer: stringProp, messageId: stringProp }, ["peer", "messageId"]),
134841
- tool("chat_delete_message", "Delete one displayed message.", { peer: stringProp, messageId: stringProp }, ["peer", "messageId"]),
134842
- tool("chat_delete", "Delete one chat.", { peer: stringProp, cleanup: booleanProp }, ["peer"]),
134843
- tool("chat_retention", "Set chat retention to seen or 24h.", { peer: stringProp, retention: stringProp }, ["peer", "retention"]),
134844
- tool("money_receive", "Get the static funding address.", {}),
134845
- tool("money_claim", "Claim static deposits and pending incoming transfers.", { count: numberProp }),
134846
- tool("money_balance", "Read wallet balance.", {}),
134847
- tool("money_send", "Send sats to a peer.", { peer: stringProp, sats: numberProp }, ["peer", "sats"]),
134848
- tool("money_request", "Request sats from a peer.", { peer: stringProp, sats: numberProp }, ["peer", "sats"]),
134849
- tool("money_pay", "Pay a chat payment request.", { requestId: stringProp }, ["requestId"]),
134850
- tool("money_invoice", "Create a Lightning invoice.", { sats: numberProp, memo: stringProp, expirySeconds: numberProp, includeSparkAddress: booleanProp, includeSparkInvoice: booleanProp }),
134851
- tool("money_pay_invoice", "Pay a Lightning or Spark invoice.", { invoice: stringProp, type: stringProp, amountSats: numberProp, maxFeeSats: numberProp, preferSpark: booleanProp }, ["invoice"]),
134852
- tool("lightning_quote", "Quote Lightning send fees.", { invoice: stringProp, amountSats: numberProp }, ["invoice"]),
134853
- tool("lightning_pay", "Pay a Lightning invoice.", { invoice: stringProp, amountSats: numberProp, amountSatsToSend: numberProp, maxFeeSats: numberProp, preferSpark: booleanProp }, ["invoice"]),
134854
- tool("lightning_receive", "Read a Lightning receive request.", { id: stringProp }, ["id"]),
134855
- tool("lightning_send", "Read a Lightning send request.", { id: stringProp }, ["id"]),
134856
- tool("withdraw_quote", "Quote an on-chain withdrawal.", { address: stringProp, sats: numberProp }, ["address", "sats"]),
134857
- tool("withdraw_prepare", "Prepare an on-chain withdrawal review.", { address: stringProp, sats: numberProp, speed: stringProp, deductFeeFromWithdrawalAmount: booleanProp }, ["address", "sats"]),
134858
- tool("withdraw_send", "Send an on-chain withdrawal.", { address: stringProp, sats: numberProp, speed: stringProp, deductFeeFromWithdrawalAmount: booleanProp }, ["address", "sats"]),
134859
- tool("transactions_list", "List wallet transactions.", { count: numberProp, offset: numberProp })
134860
- ];
135155
+ properties: Object.freeze(properties),
135156
+ required: Object.freeze(required),
135157
+ paths: Object.freeze(paths.map((path) => Object.freeze(path))),
135158
+ shortUsage,
135159
+ structuredUsage,
135160
+ cliInput,
135161
+ invoke,
135162
+ invokeCli,
135163
+ mcp
135164
+ });
135165
+ }
135166
+ var optionsOnly = (_args, context) => ({ ...context.commandOptions });
135167
+ var peerInput = (args, context) => ({ ...context.commandOptions, peer: args[0] });
135168
+ var peerMessageInput = (args, context) => ({ ...context.commandOptions, peer: args[0], message: args.slice(1).join(" ") });
135169
+ var peerMessageIdInput = (args, context) => ({ ...context.commandOptions, peer: args[0], messageId: args[1] });
135170
+ var peerMessageActionInput = (args, context) => ({ ...context.commandOptions, peer: args[0], messageId: args[1], message: args.slice(2).join(" ") });
135171
+ var peerEmojiInput = (args, context) => ({ ...context.commandOptions, peer: args[0], messageId: args[1], emoji: args.slice(2).join(" ") });
135172
+ var peerSatsInput = (args, context) => ({ ...context.commandOptions, peer: args[0], sats: args[1] });
135173
+ var invoiceInput = (args, context) => ({ ...context.commandOptions, invoice: args[0] });
135174
+ var requestInput = (args, context) => ({ ...context.commandOptions, requestId: args[0] });
135175
+ var idInput = (args, context) => ({ ...context.commandOptions, id: args[0] });
135176
+ var withdrawalInput = (args, context) => ({ ...context.commandOptions, address: args[0], sats: args[1] });
135177
+ function accountInput(args, context) {
135178
+ return {
135179
+ username: args[0],
135180
+ network: context.options.network,
135181
+ webUrl: context.options.webUrl,
135182
+ saveCredential: context.options.saveCredential,
135183
+ onPasskeyUrl: context.onPasskeyUrl
135184
+ };
135185
+ }
135186
+ function vaultInput(_args, context) {
135187
+ return {
135188
+ secret: context.options.secret,
135189
+ saveSecret: context.options.saveSecret
135190
+ };
135191
+ }
135192
+ function invoiceCreateInput(args, context) {
135193
+ return {
135194
+ ...context.commandOptions,
135195
+ sats: args[0] || 0,
135196
+ memo: context.commandOptions.memo || args.slice(1).join(" ") || undefined
135197
+ };
135198
+ }
135199
+ var HEADLESS_COMMANDS = Object.freeze([
135200
+ command({
135201
+ name: "account_create",
135202
+ group: "account",
135203
+ apiNames: ["create"],
135204
+ description: "Create a Veyl account headlessly.",
135205
+ properties: { username: stringProp, network: stringProp },
135206
+ required: ["username"],
135207
+ paths: [["create"], ["account", "create"]],
135208
+ shortUsage: "create [--passkey] @name",
135209
+ structuredUsage: "account create [--passkey] @name",
135210
+ cliInput: accountInput,
135211
+ invoke: (client2, input) => client2.account.create(input),
135212
+ invokeCli: (client2, input, context) => context.options.passkey ? client2.account.createPasskey(input) : client2.account.create({ username: input.username, network: input.network, saveCredential: input.saveCredential })
135213
+ }),
135214
+ command({
135215
+ name: "account_login",
135216
+ group: "account",
135217
+ apiNames: ["login"],
135218
+ description: "Log in with the local machine credential.",
135219
+ properties: { username: stringProp },
135220
+ paths: [["login"], ["account", "login"]],
135221
+ shortUsage: "login [--passkey] [@name]",
135222
+ structuredUsage: "account login [--passkey] [@name]",
135223
+ cliInput: accountInput,
135224
+ invoke: (client2, input) => client2.account.login(input),
135225
+ invokeCli: (client2, input, context) => context.options.passkey ? client2.account.loginPasskey(input) : client2.account.login({ username: input.username })
135226
+ }),
135227
+ command({ name: "account_me", group: "account", apiNames: ["me"], description: "Show the current local account.", paths: [["me"], ["account", "me"]], shortUsage: "me", structuredUsage: "account me", cliInput: optionsOnly, invoke: (client2) => client2.account.me() }),
135228
+ command({ name: "vault_create", group: "vault", apiNames: ["create"], description: "Create and upload the local encrypted vault.", properties: { secret: stringProp, saveSecret: booleanProp }, paths: [["vault", "create"]], structuredUsage: "vault create", cliInput: vaultInput, invoke: (client2, input) => client2.vault.create(input) }),
135229
+ command({ name: "vault_unlock", group: "vault", apiNames: ["unlock"], description: "Unlock the local vault.", properties: { secret: stringProp }, paths: [["unlock"], ["vault", "unlock"]], shortUsage: "unlock", structuredUsage: "vault unlock [--secret value]", cliInput: vaultInput, invoke: (client2, input) => client2.vault.unlock(input) }),
135230
+ command({ name: "vault_lock", group: "vault", apiNames: ["lock"], description: "Lock the wallet and chat session.", paths: [["lock"], ["vault", "lock"]], shortUsage: "lock", structuredUsage: "vault lock", cliInput: optionsOnly, invoke: (client2) => client2.vault.lock() }),
135231
+ command({ name: "chat_list", group: "chat", apiNames: ["list"], description: "List chats.", properties: { count: numberProp }, paths: [["chats"], ["chat", "list"]], shortUsage: "chats", structuredUsage: "chat list", cliInput: optionsOnly, invoke: (client2, input) => client2.chat.list(input) }),
135232
+ command({ name: "chat_read", group: "chat", apiNames: ["read"], description: "Read display messages from a chat.", properties: { peer: stringProp, count: numberProp }, required: ["peer"], paths: [["read"], ["chat", "read"]], shortUsage: "read @name", structuredUsage: "chat read @name", cliInput: peerInput, invoke: (client2, input) => client2.chat.read(input.peer, input) }),
135233
+ command({ name: "chat_send", group: "chat", apiNames: ["send"], description: "Send a text message.", properties: { peer: stringProp, message: stringProp }, required: ["peer", "message"], paths: [["say"], ["msg"], ["chat", "send"]], shortUsage: 'say @name "message"', structuredUsage: 'chat send @name "message"', cliInput: peerMessageInput, invoke: (client2, input) => client2.chat.send(input.peer, input.message, input) }),
135234
+ command({ name: "chat_reply", group: "chat", apiNames: ["reply"], description: "Reply to one displayed message or listen event.", properties: { peer: stringProp, messageId: stringProp, event: objectProp, message: stringProp }, required: ["message"], paths: [["reply"], ["chat", "reply"]], shortUsage: 'reply @name <message-id> "message"', structuredUsage: 'chat reply @name <message-id> "message"', cliInput: peerMessageActionInput, invoke: (client2, input) => client2.chat.reply(input.event || { peer: input.peer, messageId: input.messageId }, input.message, input) }),
135235
+ command({ name: "chat_react", group: "chat", apiNames: ["react"], description: "React to one displayed message.", properties: { peer: stringProp, messageId: stringProp, emoji: stringProp }, required: ["peer", "messageId", "emoji"], paths: [["react"], ["chat", "react"]], shortUsage: "react @name <message-id> <emoji>", structuredUsage: "chat react @name <message-id> <emoji>", cliInput: peerEmojiInput, invoke: (client2, input) => client2.chat.react(input.peer, input.messageId, input.emoji, input) }),
135236
+ command({ name: "chat_react_to", group: "chat", apiNames: ["react-to"], description: "React to a displayed message or listen event.", properties: { peer: stringProp, messageId: stringProp, event: objectProp, emoji: stringProp }, required: ["emoji"], paths: [["chat", "react-to"]], structuredUsage: "chat react-to @name <message-id> <emoji>", cliInput: peerEmojiInput, invoke: (client2, input) => client2.chat.reactTo(input.event || { peer: input.peer, messageId: input.messageId }, input.emoji, input) }),
135237
+ command({ name: "chat_unreact", group: "chat", apiNames: ["unreact"], description: "Remove your reaction from one displayed message.", properties: { peer: stringProp, messageId: stringProp }, required: ["peer", "messageId"], paths: [["unreact"], ["chat", "unreact"]], shortUsage: "unreact @name <message-id>", structuredUsage: "chat unreact @name <message-id>", cliInput: peerMessageIdInput, invoke: (client2, input) => client2.chat.unreact(input.peer, input.messageId, input) }),
135238
+ command({ name: "chat_save", group: "chat", apiNames: ["save"], description: "Keep one displayed message permanently.", properties: { peer: stringProp, messageId: stringProp }, required: ["peer", "messageId"], paths: [["save"], ["chat", "save"]], shortUsage: "save @name <message-id>", structuredUsage: "chat save @name <message-id>", cliInput: peerMessageIdInput, invoke: (client2, input) => client2.chat.save(input.peer, input.messageId, input) }),
135239
+ command({ name: "chat_unsave", group: "chat", apiNames: ["unsave"], description: "Return one displayed message to temporary retention.", properties: { peer: stringProp, messageId: stringProp }, required: ["peer", "messageId"], paths: [["unsave"], ["chat", "unsave"]], shortUsage: "unsave @name <message-id>", structuredUsage: "chat unsave @name <message-id>", cliInput: peerMessageIdInput, invoke: (client2, input) => client2.chat.unsave(input.peer, input.messageId, input) }),
135240
+ command({ name: "chat_delete_message", group: "chat", apiNames: ["delete"], description: "Delete one displayed message.", properties: { peer: stringProp, messageId: stringProp }, required: ["peer", "messageId"], paths: [["delete-message"], ["chat", "delete"]], shortUsage: "delete-message @name <message-id>", structuredUsage: "chat delete @name <message-id>", cliInput: peerMessageIdInput, invoke: (client2, input) => client2.chat.delete(input.peer, input.messageId, input) }),
135241
+ command({ name: "chat_delete", group: "chat", apiNames: ["delete-chat"], description: "Delete one chat.", properties: { peer: stringProp, cleanup: booleanProp }, required: ["peer"], paths: [["delete-chat"], ["chat", "delete-chat"]], shortUsage: "delete-chat @name", structuredUsage: "chat delete-chat @name", cliInput: peerInput, invoke: (client2, input) => client2.chat.deleteChat(input.peer, input) }),
135242
+ command({ name: "chat_retention", group: "chat", apiNames: ["retention"], description: "Set chat retention to seen or 24h.", properties: { peer: stringProp, retention: stringProp }, required: ["peer", "retention"], paths: [["retention"], ["chat", "retention"]], shortUsage: "retention @name seen|24h", structuredUsage: "chat retention @name seen|24h", cliInput: (args, context) => ({ ...context.commandOptions, peer: args[0], retention: args[1] }), invoke: (client2, input) => client2.chat.retention(input.peer, input.retention, input) }),
135243
+ command({ name: "money_receive", group: "money", apiNames: ["address", "receive"], description: "Get the static funding address.", paths: [["receive"], ["address"], ["money", "receive"], ["money", "address"]], shortUsage: "receive", structuredUsage: "money receive", cliInput: optionsOnly, invoke: (client2, input) => client2.money.receive(input) }),
135244
+ command({ name: "money_claim", group: "money", apiNames: ["claim"], description: "Claim static deposits and pending incoming transfers.", properties: { count: numberProp }, paths: [["claim"], ["money", "claim"]], shortUsage: "claim", structuredUsage: "money claim", cliInput: optionsOnly, invoke: (client2, input) => client2.money.claim(input) }),
135245
+ command({ name: "money_balance", group: "money", apiNames: ["balance"], description: "Read wallet balance.", paths: [["balance"], ["money", "balance"]], shortUsage: "balance", structuredUsage: "money balance", cliInput: optionsOnly, invoke: (client2, input) => client2.money.balance(input) }),
135246
+ command({ name: "money_send", group: "money", apiNames: ["send"], description: "Send sats to a peer.", properties: { peer: stringProp, sats: numberProp }, required: ["peer", "sats"], paths: [["send"], ["money", "send"]], shortUsage: "send @name 1000", structuredUsage: "money send @name 1000", cliInput: peerSatsInput, invoke: (client2, input) => client2.money.send(input.peer, input.sats, input) }),
135247
+ command({ name: "money_request", group: "money", apiNames: ["request"], description: "Request sats from a peer.", properties: { peer: stringProp, sats: numberProp }, required: ["peer", "sats"], paths: [["request"], ["money", "request"]], shortUsage: "request @name 1000", structuredUsage: "money request @name 1000", cliInput: peerSatsInput, invoke: (client2, input) => client2.money.request(input.peer, input.sats, input) }),
135248
+ command({ name: "money_pay", group: "money", apiNames: ["pay"], description: "Pay a chat payment request.", properties: { requestId: stringProp }, required: ["requestId"], paths: [["pay"], ["money", "pay"]], shortUsage: "pay <request-id>", structuredUsage: "money pay <request-id>", cliInput: requestInput, invoke: (client2, input) => client2.money.pay(input.requestId, input) }),
135249
+ command({ name: "money_invoice", group: "money", apiNames: ["invoice"], description: "Create a Lightning invoice.", properties: { sats: numberProp, memo: stringProp, expirySeconds: numberProp, includeSparkAddress: booleanProp, includeSparkInvoice: booleanProp }, paths: [["invoice"], ["money", "invoice"]], shortUsage: 'invoice 100 ["memo"]', structuredUsage: 'money invoice 100 ["memo"]', cliInput: invoiceCreateInput, invoke: (client2, input) => client2.money.invoice(input.sats || 0, input) }),
135250
+ command({ name: "money_pay_invoice", group: "money", apiNames: ["pay-invoice"], description: "Pay a Lightning or Spark invoice.", properties: { invoice: stringProp, type: stringProp, amountSats: numberProp, maxFeeSats: numberProp, preferSpark: booleanProp }, required: ["invoice"], paths: [["pay-invoice"], ["payinvoice"], ["money", "pay-invoice"]], shortUsage: "pay-invoice <invoice>", structuredUsage: "money pay-invoice <invoice>", cliInput: invoiceInput, invoke: (client2, input) => client2.money.payInvoice(input.invoice, input) }),
135251
+ command({ name: "lightning_quote", group: "money", apiNames: ["lightning-quote"], description: "Quote Lightning send fees.", properties: { invoice: stringProp, amountSats: numberProp }, required: ["invoice"], paths: [["money", "lightning-quote"]], structuredUsage: "money lightning-quote <invoice>", cliInput: invoiceInput, invoke: (client2, input) => client2.money.lightningQuote(input.invoice, input) }),
135252
+ command({ name: "lightning_pay", group: "money", apiNames: ["lightning-pay"], description: "Pay a Lightning invoice.", properties: { invoice: stringProp, amountSats: numberProp, amountSatsToSend: numberProp, maxFeeSats: numberProp, preferSpark: booleanProp }, required: ["invoice"], paths: [["money", "lightning-pay"]], structuredUsage: "money lightning-pay <invoice>", cliInput: invoiceInput, invoke: (client2, input) => client2.money.lightningPay(input.invoice, input) }),
135253
+ command({ name: "lightning_receive", group: "money", apiNames: ["lightning-receive"], description: "Read a Lightning receive request.", properties: { id: stringProp }, required: ["id"], paths: [["money", "lightning-receive"]], structuredUsage: "money lightning-receive <id>", cliInput: idInput, invoke: (client2, input) => client2.money.lightningReceive(input.id, input) }),
135254
+ command({ name: "lightning_send", group: "money", apiNames: ["lightning-send"], description: "Read a Lightning send request.", properties: { id: stringProp }, required: ["id"], paths: [["money", "lightning-send"]], structuredUsage: "money lightning-send <id>", cliInput: idInput, invoke: (client2, input) => client2.money.lightningSend(input.id, input) }),
135255
+ command({ name: "withdraw_quote", group: "money", apiNames: ["withdraw-quote"], description: "Quote an on-chain withdrawal.", properties: { address: stringProp, sats: numberProp }, required: ["address", "sats"], paths: [["withdraw-quote"], ["money", "withdraw-quote"]], shortUsage: "withdraw-quote <address> 1000", structuredUsage: "money withdraw-quote <address> 1000", cliInput: withdrawalInput, invoke: (client2, input) => client2.money.withdrawQuote(input.address, input.sats, input) }),
135256
+ command({ name: "withdraw_prepare", group: "money", apiNames: ["withdraw-prepare"], description: "Prepare an on-chain withdrawal review.", properties: { address: stringProp, sats: numberProp, speed: stringProp, deductFeeFromWithdrawalAmount: booleanProp }, required: ["address", "sats"], paths: [["withdraw-prepare"], ["money", "withdraw-prepare"]], shortUsage: "withdraw-prepare <address> 1000", structuredUsage: "money withdraw-prepare <address> 1000", cliInput: withdrawalInput, invoke: (client2, input) => client2.money.withdrawPrepare(input.address, input.sats, input) }),
135257
+ command({ name: "withdraw_send", group: "money", apiNames: ["withdraw"], description: "Send an on-chain withdrawal.", properties: { address: stringProp, sats: numberProp, speed: stringProp, deductFeeFromWithdrawalAmount: booleanProp }, required: ["address", "sats"], paths: [["withdraw"], ["money", "withdraw"]], shortUsage: "withdraw <address> 1000", structuredUsage: "money withdraw <address> 1000", cliInput: withdrawalInput, invoke: (client2, input) => client2.money.withdraw(input.address, input.sats, input) }),
135258
+ command({ name: "transactions_list", group: "transactions", apiNames: ["list"], description: "List wallet transactions.", properties: { count: numberProp, offset: numberProp }, paths: [["transactions"], ["txs"], ["money", "transactions"]], shortUsage: "transactions", structuredUsage: "money transactions", cliInput: optionsOnly, invoke: (client2, input) => client2.money.transactions(input) }),
135259
+ command({ name: "listen_start", group: "listen", apiNames: ["start"], description: "Listen for account events.", paths: [["listen"]], shortUsage: "listen", cliInput: optionsOnly, mcp: false, invokeCli: (client2, _input, context) => context.listen(client2) }),
135260
+ command({ name: "mcp_serve", group: "mcp", apiNames: ["serve"], description: "Serve MCP over stdio.", paths: [["mcp", "serve"]], structuredUsage: "mcp serve", cliInput: optionsOnly, mcp: false, invoke: (client2) => client2.mcp.serve() })
135261
+ ]);
135262
+ var commandByName = new Map(HEADLESS_COMMANDS.map((item) => [item.name, item]));
135263
+ var cliPaths = HEADLESS_COMMANDS.flatMap((item) => item.paths.map((path) => ({ command: item, path }))).sort((a, b) => b.path.length - a.path.length);
135264
+ var MCP_TOOLS = Object.freeze(HEADLESS_COMMANDS.filter((item) => item.mcp).map((item) => Object.freeze({
135265
+ name: item.name,
135266
+ description: item.description,
135267
+ inputSchema: Object.freeze({
135268
+ type: "object",
135269
+ properties: item.properties,
135270
+ ...item.required.length ? { required: item.required } : {}
135271
+ })
135272
+ })));
135273
+ var groups = ["account", "vault", "chat", "money", "mcp", "transactions", "listen"];
135274
+ var COMMANDS = Object.freeze(Object.fromEntries(groups.map((group) => [group, Object.freeze(HEADLESS_COMMANDS.filter((item) => item.group === group).flatMap((item) => item.apiNames))])));
135275
+ function invokeCommand(client2, name8, input = {}) {
135276
+ const selected = commandByName.get(name8);
135277
+ if (!selected?.invoke || !selected.mcp) {
135278
+ throw new Error(`unknown tool ${name8}`);
135279
+ }
135280
+ return selected.invoke(client2, input);
135281
+ }
135282
+ function resolveCliCommand(tokens = []) {
135283
+ for (const entry of cliPaths) {
135284
+ if (entry.path.every((part, index) => tokens[index] === part)) {
135285
+ return { command: entry.command, args: tokens.slice(entry.path.length) };
135286
+ }
135287
+ }
135288
+ return null;
135289
+ }
135290
+ function invokeCliCommand(client2, resolved, context) {
135291
+ const selected = resolved?.command;
135292
+ if (!selected) {
135293
+ throw new Error("command required");
135294
+ }
135295
+ const input = selected.cliInput?.(resolved.args, context) || {};
135296
+ const invoke = selected.invokeCli || selected.invoke;
135297
+ if (!invoke) {
135298
+ throw new Error(`CLI command unavailable: ${selected.name}`);
135299
+ }
135300
+ return invoke(client2, input, context);
135301
+ }
135302
+ function cliHelpLines(kind) {
135303
+ const field2 = kind === "structured" ? "structuredUsage" : "shortUsage";
135304
+ return HEADLESS_COMMANDS.map((item) => item[field2]).filter(Boolean);
135305
+ }
135306
+
135307
+ // src/mcp.js
134861
135308
  function result(value) {
134862
135309
  return {
134863
135310
  content: [
@@ -134868,77 +135315,6 @@ function result(value) {
134868
135315
  ]
134869
135316
  };
134870
135317
  }
134871
- async function callTool(client2, name8, args = {}) {
134872
- if (name8 === "account_create")
134873
- return client2.account.create(args);
134874
- if (name8 === "account_login")
134875
- return client2.account.login(args);
134876
- if (name8 === "account_me")
134877
- return client2.account.me();
134878
- if (name8 === "vault_create")
134879
- return client2.vault.create(args);
134880
- if (name8 === "vault_unlock")
134881
- return client2.vault.unlock(args);
134882
- if (name8 === "vault_lock")
134883
- return client2.vault.lock();
134884
- if (name8 === "chat_list")
134885
- return client2.chat.list(args);
134886
- if (name8 === "chat_read")
134887
- return client2.chat.read(args.peer, args);
134888
- if (name8 === "chat_send")
134889
- return client2.chat.send(args.peer, args.message, args);
134890
- if (name8 === "chat_reply")
134891
- return client2.chat.reply(args.event || { peer: args.peer, messageId: args.messageId }, args.message, args);
134892
- if (name8 === "chat_react")
134893
- return client2.chat.react(args.peer, args.messageId, args.emoji, args);
134894
- if (name8 === "chat_react_to")
134895
- return client2.chat.reactTo(args.event || { peer: args.peer, messageId: args.messageId }, args.emoji, args);
134896
- if (name8 === "chat_unreact")
134897
- return client2.chat.unreact(args.peer, args.messageId, args);
134898
- if (name8 === "chat_save")
134899
- return client2.chat.save(args.peer, args.messageId, args);
134900
- if (name8 === "chat_unsave")
134901
- return client2.chat.unsave(args.peer, args.messageId, args);
134902
- if (name8 === "chat_delete_message")
134903
- return client2.chat.delete(args.peer, args.messageId, args);
134904
- if (name8 === "chat_delete")
134905
- return client2.chat.deleteChat(args.peer, args);
134906
- if (name8 === "chat_retention")
134907
- return client2.chat.retention(args.peer, args.retention, args);
134908
- if (name8 === "money_receive")
134909
- return client2.money.receive(args);
134910
- if (name8 === "money_claim")
134911
- return client2.money.claim(args);
134912
- if (name8 === "money_balance")
134913
- return client2.money.balance(args);
134914
- if (name8 === "money_send")
134915
- return client2.money.send(args.peer, args.sats, args);
134916
- if (name8 === "money_request")
134917
- return client2.money.request(args.peer, args.sats, args);
134918
- if (name8 === "money_pay")
134919
- return client2.money.pay(args.requestId, args);
134920
- if (name8 === "money_invoice")
134921
- return client2.money.invoice(args.sats || 0, args);
134922
- if (name8 === "money_pay_invoice")
134923
- return client2.money.payInvoice(args.invoice, args);
134924
- if (name8 === "lightning_quote")
134925
- return client2.money.lightningQuote(args.invoice, args);
134926
- if (name8 === "lightning_pay")
134927
- return client2.money.lightningPay(args.invoice, args);
134928
- if (name8 === "lightning_receive")
134929
- return client2.money.lightningReceive(args.id, args);
134930
- if (name8 === "lightning_send")
134931
- return client2.money.lightningSend(args.id, args);
134932
- if (name8 === "withdraw_quote")
134933
- return client2.money.withdrawQuote(args.address, args.sats, args);
134934
- if (name8 === "withdraw_prepare")
134935
- return client2.money.withdrawPrepare(args.address, args.sats, args);
134936
- if (name8 === "withdraw_send")
134937
- return client2.money.withdraw(args.address, args.sats, args);
134938
- if (name8 === "transactions_list")
134939
- return client2.money.transactions(args);
134940
- throw new Error(`unknown tool ${name8}`);
134941
- }
134942
135318
  function write(message) {
134943
135319
  process4.stdout.write(`${JSON.stringify(message)}
134944
135320
  `);
@@ -134969,13 +135345,13 @@ async function serveMcp(client2) {
134969
135345
  result: {
134970
135346
  protocolVersion: "2024-11-05",
134971
135347
  capabilities: { tools: {} },
134972
- serverInfo: { name: "veyl", version: "0.1.0" }
135348
+ serverInfo: { name: "veyl", version: package_default.version }
134973
135349
  }
134974
135350
  });
134975
135351
  } else if (message.method === "tools/list") {
134976
- write({ jsonrpc: "2.0", id: message.id, result: { tools: TOOLS } });
135352
+ write({ jsonrpc: "2.0", id: message.id, result: { tools: MCP_TOOLS } });
134977
135353
  } else if (message.method === "tools/call") {
134978
- const toolResult = await callTool(client2, message.params?.name, message.params?.arguments || {});
135354
+ const toolResult = await invokeCommand(client2, message.params?.name, message.params?.arguments || {});
134979
135355
  write({ jsonrpc: "2.0", id: message.id, result: result(toolResult) });
134980
135356
  } else if (message.id != null) {
134981
135357
  write({ jsonrpc: "2.0", id: message.id, result: {} });
@@ -134988,15 +135364,6 @@ async function serveMcp(client2) {
134988
135364
 
134989
135365
  // src/client.js
134990
135366
  var API_VERSION = 1;
134991
- var COMMANDS = Object.freeze({
134992
- account: Object.freeze(["create", "login", "me"]),
134993
- vault: Object.freeze(["create", "unlock", "lock"]),
134994
- chat: Object.freeze(["list", "read", "send", "reply", "react", "react-to", "unreact", "save", "unsave", "delete", "delete-chat", "retention"]),
134995
- money: Object.freeze(["address", "balance", "claim", "invoice", "lightning-quote", "lightning-pay", "lightning-receive", "lightning-send", "pay-invoice", "receive", "request", "send", "pay", "withdraw", "withdraw-prepare", "withdraw-quote"]),
134996
- mcp: Object.freeze(["serve"]),
134997
- transactions: Object.freeze(["list"]),
134998
- listen: Object.freeze(["start"])
134999
- });
135000
135367
 
135001
135368
  class ClientNotReadyError extends Error {
135002
135369
  constructor(feature) {
@@ -135561,84 +135928,42 @@ async function open(options2 = {}) {
135561
135928
  return createClient2(options2);
135562
135929
  }
135563
135930
  // src/cli.js
135931
+ function usageLines(kind) {
135932
+ return cliHelpLines(kind).map((line) => ` veyl ${line}`).join(`
135933
+ `);
135934
+ }
135564
135935
  var HELP = `Usage:
135565
- veyl create [--passkey] @name
135566
- veyl login [--passkey] [@name]
135567
- veyl unlock
135568
- veyl send @name 1000
135569
- veyl request @name 1000
135570
- veyl receive
135571
- veyl claim
135572
- veyl invoice 100 ["memo"]
135573
- veyl pay-invoice <invoice>
135574
- veyl withdraw <address> 1000
135575
- veyl balance
135576
- veyl read @name
135577
- veyl say @name "message"
135578
- veyl reply @name <message-id> "message"
135579
- veyl react @name <message-id> <emoji>
135580
- veyl save @name <message-id>
135581
- veyl retention @name seen|24h
135582
- veyl listen
135936
+ ${usageLines("short")}
135583
135937
 
135584
135938
  Structured:
135585
- veyl [--profile name] [--network REGTEST|MAINNET] account create @name
135586
- veyl account create --passkey @name
135587
- veyl account login @name
135588
- veyl account login --passkey [@name]
135589
- veyl account me
135590
- veyl vault create
135591
- veyl vault unlock [--secret value]
135592
- veyl vault lock
135593
- veyl chats
135594
- veyl chat read @name
135595
- veyl chat send @name "message"
135596
- veyl chat reply @name <message-id> "message"
135597
- veyl chat react @name <message-id> <emoji>
135598
- veyl chat unreact @name <message-id>
135599
- veyl chat save @name <message-id>
135600
- veyl chat unsave @name <message-id>
135601
- veyl chat delete @name <message-id>
135602
- veyl chat delete-chat @name
135603
- veyl chat retention @name seen|24h
135604
- veyl money receive
135605
- veyl money balance
135606
- veyl money claim
135607
- veyl money invoice 100 ["memo"]
135608
- veyl money pay-invoice <invoice>
135609
- veyl money send @name 1000
135610
- veyl money request @name 1000
135611
- veyl money pay <request-id>
135612
- veyl money withdraw-quote <address> 1000
135613
- veyl money withdraw <address> 1000
135614
- veyl transactions
135615
- veyl mcp serve
135939
+ veyl [--profile name] [--network REGTEST|MAINNET] <command>
135940
+ ${usageLines("structured")}
135616
135941
 
135617
135942
  Listen:
135618
135943
  --interval ms poll interval, minimum 1000
135619
- --replay emit current messages and transactions on startup
135620
- --incoming emit only peer-authored messages
135621
- --compact emit smaller event payloads
135622
- --agent shorthand for --incoming --compact
135623
- --no-chats skip chat message events
135624
- --no-transactions skip transaction events
135944
+ --replay emit current messages and transactions on startup
135945
+ --incoming emit only peer-authored messages
135946
+ --compact emit smaller event payloads
135947
+ --agent shorthand for --incoming --compact
135948
+ --no-chats skip chat message events
135949
+ --no-transactions skip transaction events
135625
135950
 
135626
135951
  Common options:
135627
- --count n result count for list/read/claim/transactions
135628
- --raw include raw SDK/backend data when supported
135629
- --memo text lightning invoice memo
135630
- --expiry seconds lightning invoice expiry
135631
- --max-fee sats maximum lightning fee
135632
- --amount sats variable invoice amount
135633
- --speed value withdrawal speed, SLOW|MEDIUM|FAST
135634
- --no-deduct-fee add withdrawal fee on top of the sent amount
135952
+ --count n result count for list/read/claim/transactions
135953
+ --raw include raw SDK/backend data when supported
135954
+ --memo text lightning invoice memo
135955
+ --expiry seconds lightning invoice expiry
135956
+ --max-fee sats maximum lightning fee
135957
+ --amount sats variable invoice amount
135958
+ --speed value withdrawal speed, SLOW|MEDIUM|FAST
135959
+ --no-deduct-fee add withdrawal fee on top of the sent amount
135635
135960
 
135636
135961
  Env:
135637
- VEYL_HOME local profile directory
135638
- VEYL_PROFILE default profile
135639
- VEYL_NETWORK wallet network
135640
- VEYL_VAULT_SECRET vault secret for unlock/create
135641
- VEYL_WEB_URL passkey browser origin`;
135962
+ VEYL_HOME local profile directory
135963
+ VEYL_PROFILE default profile
135964
+ VEYL_NETWORK wallet network
135965
+ VEYL_VAULT_SECRET vault secret for unlock/create
135966
+ VEYL_WEB_URL passkey browser origin`;
135642
135967
  function print2(value) {
135643
135968
  if (value === undefined) {
135644
135969
  return;
@@ -135681,316 +136006,112 @@ function commandOptions(options2 = {}) {
135681
136006
  cleanup: options2.cleanup
135682
136007
  };
135683
136008
  }
136009
+ var VALUE_FLAGS = Object.freeze({
136010
+ "--profile": "profile",
136011
+ "--network": "network",
136012
+ "--secret": "secret",
136013
+ "--web-url": "webUrl",
136014
+ "--interval": "interval",
136015
+ "--chat-count": "chatCount",
136016
+ "--message-count": "messageCount",
136017
+ "--tx-count": "txCount",
136018
+ "--count": "count",
136019
+ "--limit": "limit",
136020
+ "--offset": "offset",
136021
+ "--memo": "memo",
136022
+ "--expiry": "expirySeconds",
136023
+ "--expiry-seconds": "expirySeconds",
136024
+ "--max-fee": "maxFeeSats",
136025
+ "--max-fee-sats": "maxFeeSats",
136026
+ "--amount": "amountSats",
136027
+ "--amount-sats": "amountSats",
136028
+ "--amount-to-send": "amountSatsToSend",
136029
+ "--amount-sats-to-send": "amountSatsToSend",
136030
+ "--speed": "speed",
136031
+ "--exit-speed": "speed",
136032
+ "--type": "type"
136033
+ });
136034
+ var BOOLEAN_FLAGS = Object.freeze({
136035
+ "--no-save-secret": ["saveSecret", false],
136036
+ "--passkey": ["passkey", true],
136037
+ "--no-save-credential": ["saveCredential", false],
136038
+ "--raw": ["raw", true],
136039
+ "--no-deduct-fee": ["deductFeeFromWithdrawalAmount", false],
136040
+ "--prefer-spark": ["preferSpark", true],
136041
+ "--no-prefer-spark": ["preferSpark", false],
136042
+ "--include-spark-address": ["includeSparkAddress", true],
136043
+ "--include-spark-invoice": ["includeSparkInvoice", true],
136044
+ "--no-cleanup": ["cleanup", false],
136045
+ "--replay": ["replay", true],
136046
+ "--incoming": ["incomingOnly", true],
136047
+ "--incoming-only": ["incomingOnly", true],
136048
+ "--all": ["incomingOnly", false],
136049
+ "--compact": ["compact", true],
136050
+ "--agent": ["agent", true],
136051
+ "--no-chats": ["chats", false],
136052
+ "--no-transactions": ["transactions", false]
136053
+ });
135684
136054
  function parseArgs(argv) {
135685
136055
  const options2 = {};
135686
136056
  const args = [];
135687
136057
  for (let index = 0;index < argv.length; index += 1) {
135688
136058
  const item = argv[index];
135689
- if (item === "--profile") {
135690
- options2.profile = argv[++index];
135691
- } else if (item === "--network") {
135692
- options2.network = argv[++index];
135693
- } else if (item === "--secret") {
135694
- options2.secret = argv[++index];
135695
- } else if (item === "--no-save-secret") {
135696
- options2.saveSecret = false;
135697
- } else if (item === "--passkey") {
135698
- options2.passkey = true;
135699
- } else if (item === "--web-url") {
135700
- options2.webUrl = argv[++index];
135701
- } else if (item === "--no-save-credential") {
135702
- options2.saveCredential = false;
135703
- } else if (item === "--interval") {
135704
- options2.interval = argv[++index];
135705
- } else if (item === "--chat-count") {
135706
- options2.chatCount = argv[++index];
135707
- } else if (item === "--message-count") {
135708
- options2.messageCount = argv[++index];
135709
- } else if (item === "--tx-count") {
135710
- options2.txCount = argv[++index];
135711
- } else if (item === "--count") {
135712
- options2.count = argv[++index];
135713
- } else if (item === "--limit") {
135714
- options2.limit = argv[++index];
135715
- } else if (item === "--offset") {
135716
- options2.offset = argv[++index];
135717
- } else if (item === "--raw") {
135718
- options2.raw = true;
135719
- } else if (item === "--memo") {
135720
- options2.memo = argv[++index];
135721
- } else if (item === "--expiry" || item === "--expiry-seconds") {
135722
- options2.expirySeconds = argv[++index];
135723
- } else if (item === "--max-fee" || item === "--max-fee-sats") {
135724
- options2.maxFeeSats = argv[++index];
135725
- } else if (item === "--amount" || item === "--amount-sats") {
135726
- options2.amountSats = argv[++index];
135727
- } else if (item === "--amount-to-send" || item === "--amount-sats-to-send") {
135728
- options2.amountSatsToSend = argv[++index];
135729
- } else if (item === "--speed" || item === "--exit-speed") {
135730
- options2.speed = argv[++index];
135731
- } else if (item === "--no-deduct-fee") {
135732
- options2.deductFeeFromWithdrawalAmount = false;
135733
- } else if (item === "--type") {
135734
- options2.type = argv[++index];
135735
- } else if (item === "--prefer-spark") {
135736
- options2.preferSpark = true;
135737
- } else if (item === "--no-prefer-spark") {
135738
- options2.preferSpark = false;
135739
- } else if (item === "--include-spark-address") {
135740
- options2.includeSparkAddress = true;
135741
- } else if (item === "--include-spark-invoice") {
135742
- options2.includeSparkInvoice = true;
135743
- } else if (item === "--no-cleanup") {
135744
- options2.cleanup = false;
135745
- } else if (item === "--replay") {
135746
- options2.replay = true;
135747
- } else if (item === "--incoming" || item === "--incoming-only") {
135748
- options2.incomingOnly = true;
135749
- } else if (item === "--all") {
135750
- options2.incomingOnly = false;
135751
- } else if (item === "--compact") {
135752
- options2.compact = true;
135753
- } else if (item === "--agent") {
135754
- options2.agent = true;
135755
- } else if (item === "--no-chats") {
135756
- options2.chats = false;
135757
- } else if (item === "--no-transactions") {
135758
- options2.transactions = false;
135759
- } else {
135760
- args.push(item);
136059
+ const valueKey = VALUE_FLAGS[item];
136060
+ if (valueKey) {
136061
+ options2[valueKey] = argv[++index];
136062
+ continue;
136063
+ }
136064
+ const booleanFlag = BOOLEAN_FLAGS[item];
136065
+ if (booleanFlag) {
136066
+ options2[booleanFlag[0]] = booleanFlag[1];
136067
+ continue;
135761
136068
  }
136069
+ args.push(item);
135762
136070
  }
135763
136071
  return { args, options: options2 };
135764
136072
  }
136073
+ async function listen2(client3, options2) {
136074
+ const controller = new AbortController;
136075
+ process.once("SIGINT", () => controller.abort());
136076
+ process.once("SIGTERM", () => controller.abort());
136077
+ await client3.listen({
136078
+ interval: options2.interval,
136079
+ chatCount: options2.chatCount,
136080
+ messageCount: options2.messageCount,
136081
+ txCount: options2.txCount,
136082
+ replay: options2.replay,
136083
+ incomingOnly: options2.incomingOnly,
136084
+ compact: options2.compact,
136085
+ agent: options2.agent,
136086
+ chats: options2.chats,
136087
+ transactions: options2.transactions,
136088
+ signal: controller.signal,
136089
+ onEvent: (event2) => console.log(JSON.stringify(event2))
136090
+ });
136091
+ }
135765
136092
  async function runCommand(argv) {
135766
136093
  const parsed = parseArgs(argv);
136094
+ const [area] = parsed.args;
136095
+ if (!area || area === "help" || area === "--help" || area === "-h") {
136096
+ return HELP;
136097
+ }
136098
+ const resolved = resolveCliCommand(parsed.args);
136099
+ if (!resolved) {
136100
+ throw usageError("unknown command");
136101
+ }
135767
136102
  if (parsed.options.secret) {
135768
136103
  process.env.VEYL_VAULT_SECRET = parsed.options.secret;
135769
136104
  }
135770
- const [area, command, ...args] = parsed.args;
135771
- const shortArgs = command === undefined ? [] : [command, ...args];
135772
- const veyl = createClient2({
136105
+ const client3 = createClient2({
135773
136106
  profile: parsed.options.profile,
135774
136107
  network: parsed.options.network
135775
136108
  });
135776
- const opts = commandOptions(parsed.options);
135777
- if (!area || area === "help" || area === "--help" || area === "-h") {
135778
- return HELP;
135779
- }
135780
- if (area === "chats") {
135781
- return veyl.chat.list(opts);
135782
- }
135783
- if (area === "transactions") {
135784
- return veyl.money.transactions(opts);
135785
- }
135786
- if (area === "create") {
135787
- return parsed.options.passkey ? veyl.account.createPasskey({
135788
- username: shortArgs[0],
135789
- network: parsed.options.network,
135790
- webUrl: parsed.options.webUrl,
135791
- saveCredential: parsed.options.saveCredential,
135792
- onPasskeyUrl: (url) => console.error(`open ${url}`)
135793
- }) : veyl.account.create({ username: shortArgs[0], network: parsed.options.network, saveCredential: parsed.options.saveCredential });
135794
- }
135795
- if (area === "login") {
135796
- return parsed.options.passkey ? veyl.account.loginPasskey({
135797
- username: shortArgs[0],
135798
- network: parsed.options.network,
135799
- webUrl: parsed.options.webUrl,
135800
- saveCredential: parsed.options.saveCredential,
135801
- onPasskeyUrl: (url) => console.error(`open ${url}`)
135802
- }) : veyl.account.login({ username: shortArgs[0] });
135803
- }
135804
- if (area === "me") {
135805
- return veyl.account.me();
135806
- }
135807
- if (area === "unlock") {
135808
- return veyl.vault.unlock({ secret: parsed.options.secret, saveSecret: parsed.options.saveSecret });
135809
- }
135810
- if (area === "lock") {
135811
- return veyl.vault.lock();
135812
- }
135813
- if (area === "balance") {
135814
- return veyl.money.balance(opts);
135815
- }
135816
- if (area === "receive" || area === "address") {
135817
- return veyl.money.receive(opts);
135818
- }
135819
- if (area === "claim") {
135820
- return veyl.money.claim(opts);
135821
- }
135822
- if (area === "invoice") {
135823
- return veyl.money.invoice(shortArgs[0] || 0, { ...opts, memo: opts.memo || shortArgs.slice(1).join(" ") || undefined });
135824
- }
135825
- if (area === "pay-invoice" || area === "payinvoice") {
135826
- return veyl.money.payInvoice(shortArgs[0], opts);
135827
- }
135828
- if (area === "withdraw-quote") {
135829
- return veyl.money.withdrawQuote(shortArgs[0], shortArgs[1], opts);
135830
- }
135831
- if (area === "withdraw-prepare") {
135832
- return veyl.money.withdrawPrepare(shortArgs[0], shortArgs[1], opts);
135833
- }
135834
- if (area === "withdraw") {
135835
- return veyl.money.withdraw(shortArgs[0], shortArgs[1], opts);
135836
- }
135837
- if (area === "send") {
135838
- return veyl.money.send(shortArgs[0], shortArgs[1], opts);
135839
- }
135840
- if (area === "request") {
135841
- return veyl.money.request(shortArgs[0], shortArgs[1], opts);
135842
- }
135843
- if (area === "pay") {
135844
- return veyl.money.pay(shortArgs[0], opts);
135845
- }
135846
- if (area === "txs") {
135847
- return veyl.money.transactions(opts);
135848
- }
135849
- if (area === "read") {
135850
- return veyl.chat.read(shortArgs[0], opts);
135851
- }
135852
- if (area === "say" || area === "msg") {
135853
- return veyl.chat.send(shortArgs[0], shortArgs.slice(1).join(" "), opts);
135854
- }
135855
- if (area === "reply") {
135856
- return veyl.chat.reply({ peer: shortArgs[0], messageId: shortArgs[1] }, shortArgs.slice(2).join(" "), opts);
135857
- }
135858
- if (area === "react") {
135859
- return veyl.chat.react(shortArgs[0], shortArgs[1], shortArgs.slice(2).join(" "), opts);
135860
- }
135861
- if (area === "unreact") {
135862
- return veyl.chat.unreact(shortArgs[0], shortArgs[1], opts);
135863
- }
135864
- if (area === "save") {
135865
- return veyl.chat.save(shortArgs[0], shortArgs[1], opts);
135866
- }
135867
- if (area === "unsave") {
135868
- return veyl.chat.unsave(shortArgs[0], shortArgs[1], opts);
135869
- }
135870
- if (area === "delete-message") {
135871
- return veyl.chat.delete(shortArgs[0], shortArgs[1], opts);
135872
- }
135873
- if (area === "delete-chat") {
135874
- return veyl.chat.deleteChat(shortArgs[0], opts);
135875
- }
135876
- if (area === "retention") {
135877
- return veyl.chat.retention(shortArgs[0], shortArgs[1], opts);
135878
- }
135879
- if (area === "listen") {
135880
- const controller = new AbortController;
135881
- process.once("SIGINT", () => controller.abort());
135882
- process.once("SIGTERM", () => controller.abort());
135883
- await veyl.listen({
135884
- interval: parsed.options.interval,
135885
- chatCount: parsed.options.chatCount,
135886
- messageCount: parsed.options.messageCount,
135887
- txCount: parsed.options.txCount,
135888
- replay: parsed.options.replay,
135889
- incomingOnly: parsed.options.incomingOnly,
135890
- compact: parsed.options.compact,
135891
- agent: parsed.options.agent,
135892
- chats: parsed.options.chats,
135893
- transactions: parsed.options.transactions,
135894
- signal: controller.signal,
135895
- onEvent: (event2) => console.log(JSON.stringify(event2))
135896
- });
135897
- return;
135898
- }
135899
- if (area === "account") {
135900
- const passkeyOptions = {
135901
- username: args[0],
135902
- network: parsed.options.network,
135903
- webUrl: parsed.options.webUrl,
135904
- saveCredential: parsed.options.saveCredential,
135905
- onPasskeyUrl: (url) => console.error(`open ${url}`)
135906
- };
135907
- if (command === "create") {
135908
- return parsed.options.passkey ? veyl.account.createPasskey(passkeyOptions) : veyl.account.create({ username: args[0], network: parsed.options.network, saveCredential: parsed.options.saveCredential });
135909
- }
135910
- if (command === "login") {
135911
- return parsed.options.passkey ? veyl.account.loginPasskey(passkeyOptions) : veyl.account.login({ username: args[0] });
135912
- }
135913
- if (command === "me")
135914
- return veyl.account.me();
135915
- throw usageError("unknown account command");
135916
- }
135917
- if (area === "vault") {
135918
- if (command === "create")
135919
- return veyl.vault.create({ secret: parsed.options.secret, saveSecret: parsed.options.saveSecret });
135920
- if (command === "unlock")
135921
- return veyl.vault.unlock({ secret: parsed.options.secret, saveSecret: parsed.options.saveSecret });
135922
- if (command === "lock")
135923
- return veyl.vault.lock();
135924
- throw usageError("unknown vault command");
135925
- }
135926
- if (area === "chat") {
135927
- if (command === "list")
135928
- return veyl.chat.list(opts);
135929
- if (command === "read")
135930
- return veyl.chat.read(args[0], opts);
135931
- if (command === "send")
135932
- return veyl.chat.send(args[0], args.slice(1).join(" "), opts);
135933
- if (command === "reply")
135934
- return veyl.chat.reply({ peer: args[0], messageId: args[1] }, args.slice(2).join(" "), opts);
135935
- if (command === "react")
135936
- return veyl.chat.react(args[0], args[1], args.slice(2).join(" "), opts);
135937
- if (command === "react-to")
135938
- return veyl.chat.reactTo({ peer: args[0], messageId: args[1] }, args.slice(2).join(" "), opts);
135939
- if (command === "unreact")
135940
- return veyl.chat.unreact(args[0], args[1], opts);
135941
- if (command === "save")
135942
- return veyl.chat.save(args[0], args[1], opts);
135943
- if (command === "unsave")
135944
- return veyl.chat.unsave(args[0], args[1], opts);
135945
- if (command === "delete")
135946
- return veyl.chat.delete(args[0], args[1], opts);
135947
- if (command === "delete-chat")
135948
- return veyl.chat.deleteChat(args[0], opts);
135949
- if (command === "retention")
135950
- return veyl.chat.retention(args[0], args[1], opts);
135951
- throw usageError("unknown chat command");
135952
- }
135953
- if (area === "money") {
135954
- if (command === "address" || command === "receive")
135955
- return veyl.money.receive(opts);
135956
- if (command === "balance")
135957
- return veyl.money.balance(opts);
135958
- if (command === "claim")
135959
- return veyl.money.claim(opts);
135960
- if (command === "invoice")
135961
- return veyl.money.invoice(args[0] || 0, { ...opts, memo: opts.memo || args.slice(1).join(" ") || undefined });
135962
- if (command === "lightning-quote")
135963
- return veyl.money.lightningQuote(args[0], opts);
135964
- if (command === "lightning-pay")
135965
- return veyl.money.lightningPay(args[0], opts);
135966
- if (command === "lightning-receive")
135967
- return veyl.money.lightningReceive(args[0], opts);
135968
- if (command === "lightning-send")
135969
- return veyl.money.lightningSend(args[0], opts);
135970
- if (command === "pay-invoice")
135971
- return veyl.money.payInvoice(args[0], opts);
135972
- if (command === "send")
135973
- return veyl.money.send(args[0], args[1], opts);
135974
- if (command === "request")
135975
- return veyl.money.request(args[0], args[1], opts);
135976
- if (command === "pay")
135977
- return veyl.money.pay(args[0], opts);
135978
- if (command === "transactions")
135979
- return veyl.money.transactions(opts);
135980
- if (command === "withdraw-quote")
135981
- return veyl.money.withdrawQuote(args[0], args[1], opts);
135982
- if (command === "withdraw-prepare")
135983
- return veyl.money.withdrawPrepare(args[0], args[1], opts);
135984
- if (command === "withdraw")
135985
- return veyl.money.withdraw(args[0], args[1], opts);
135986
- throw usageError("unknown money command");
135987
- }
135988
- if (area === "mcp") {
135989
- if (command === "serve")
135990
- return veyl.mcp.serve();
135991
- throw usageError("unknown mcp command");
135992
- }
135993
- throw usageError("unknown command");
136109
+ return invokeCliCommand(client3, resolved, {
136110
+ options: parsed.options,
136111
+ commandOptions: commandOptions(parsed.options),
136112
+ onPasskeyUrl: (url) => console.error(`open ${url}`),
136113
+ listen: (selected) => listen2(selected, parsed.options)
136114
+ });
135994
136115
  }
135995
136116
  async function main() {
135996
136117
  try {