@abraca/dabra 2.34.0 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13944,7 +13944,7 @@ const MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode("abracadabra
13944
13944
  const MNEMONIC_HKDF_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-identity-v1");
13945
13945
  /** HKDF info string for deriving the AES-GCM seed-wrapping key from PRF output. */
13946
13946
  const SEED_WRAP_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-seed-wrap-v1");
13947
- function toBase64url$1(bytes) {
13947
+ function toBase64url$2(bytes) {
13948
13948
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
13949
13949
  }
13950
13950
  /**
@@ -13986,14 +13986,14 @@ function mnemonicToEd25519Seed(mnemonic, passphrase) {
13986
13986
  async function mnemonicToKeyPair(mnemonic, passphrase) {
13987
13987
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
13988
13988
  const publicKey = await ed.getPublicKeyAsync(seed);
13989
- const publicKeyB64 = toBase64url$1(publicKey);
13989
+ const publicKeyB64 = toBase64url$2(publicKey);
13990
13990
  const x25519PublicKey = ed25519.utils.toMontgomery(publicKey);
13991
13991
  return {
13992
13992
  seed,
13993
13993
  publicKey,
13994
13994
  publicKeyB64,
13995
13995
  x25519PublicKey,
13996
- x25519PublicKeyB64: toBase64url$1(x25519PublicKey)
13996
+ x25519PublicKeyB64: toBase64url$2(x25519PublicKey)
13997
13997
  };
13998
13998
  }
13999
13999
  /**
@@ -14104,10 +14104,10 @@ const PRF_SALT = new Uint8Array([
14104
14104
  207
14105
14105
  ]);
14106
14106
  const HKDF_INFO$1 = new TextEncoder().encode("abracadabra-identity-v1");
14107
- function toBase64url(bytes) {
14107
+ function toBase64url$1(bytes) {
14108
14108
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14109
14109
  }
14110
- function fromBase64url(b64) {
14110
+ function fromBase64url$1(b64) {
14111
14111
  const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14112
14112
  const padLen = (4 - padded.length % 4) % 4;
14113
14113
  const padded2 = padded + "=".repeat(padLen);
@@ -14225,9 +14225,9 @@ var CryptoIdentityKeystore = class {
14225
14225
  if (!credential) throw new Error("WebAuthn credential creation cancelled");
14226
14226
  const seed = deriveEd25519Seed(extractPrfOutput(credential));
14227
14227
  const publicKey = await ed.getPublicKeyAsync(seed);
14228
- const publicKeyB64 = toBase64url(publicKey);
14229
- const x25519PubB64 = toBase64url(ed25519.utils.toMontgomery(publicKey));
14230
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14228
+ const publicKeyB64 = toBase64url$1(publicKey);
14229
+ const x25519PubB64 = toBase64url$1(ed25519.utils.toMontgomery(publicKey));
14230
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14231
14231
  const db = await openDb$4();
14232
14232
  await dbPut(db, credentialIdB64, {
14233
14233
  username,
@@ -14253,8 +14253,8 @@ var CryptoIdentityKeystore = class {
14253
14253
  async sign(challengeB64, credentialIdHint) {
14254
14254
  const { seed } = await this._assertAndDerive(credentialIdHint);
14255
14255
  try {
14256
- const challengeBytes = fromBase64url(challengeB64);
14257
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14256
+ const challengeBytes = fromBase64url$1(challengeB64);
14257
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14258
14258
  } finally {
14259
14259
  seed.fill(0);
14260
14260
  }
@@ -14339,7 +14339,7 @@ var CryptoIdentityKeystore = class {
14339
14339
  try {
14340
14340
  const all = await dbGetAll(db);
14341
14341
  if (all.length === 0) return null;
14342
- const edPub = fromBase64url(all[0].value.publicKey);
14342
+ const edPub = fromBase64url$1(all[0].value.publicKey);
14343
14343
  return ed25519.utils.toMontgomery(edPub);
14344
14344
  } finally {
14345
14345
  db.close();
@@ -14434,7 +14434,7 @@ var CryptoIdentityKeystore = class {
14434
14434
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14435
14435
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14436
14436
  wrapKey.fill(0);
14437
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14437
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14438
14438
  const db = await openDb$4();
14439
14439
  await dbPut(db, credentialIdB64, {
14440
14440
  username,
@@ -14480,7 +14480,7 @@ var CryptoIdentityKeystore = class {
14480
14480
  name: rpName
14481
14481
  },
14482
14482
  user: {
14483
- id: fromBase64url(kp.publicKeyB64),
14483
+ id: fromBase64url$1(kp.publicKeyB64),
14484
14484
  name: kp.publicKeyB64.slice(0, 16),
14485
14485
  displayName: kp.publicKeyB64.slice(0, 16)
14486
14486
  },
@@ -14504,7 +14504,7 @@ var CryptoIdentityKeystore = class {
14504
14504
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14505
14505
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14506
14506
  wrapKey.fill(0);
14507
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14507
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14508
14508
  let username = "";
14509
14509
  try {
14510
14510
  const db = await openDb$4();
@@ -14535,8 +14535,8 @@ var CryptoIdentityKeystore = class {
14535
14535
  * The caller manages the seed lifecycle (wiping on session end).
14536
14536
  */
14537
14537
  static async signWithSeed(challengeB64, seed) {
14538
- const challengeBytes = fromBase64url(challengeB64);
14539
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14538
+ const challengeBytes = fromBase64url$1(challengeB64);
14539
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14540
14540
  }
14541
14541
  /**
14542
14542
  * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
@@ -14545,8 +14545,8 @@ var CryptoIdentityKeystore = class {
14545
14545
  static async signWithMnemonic(mnemonic, challengeB64, passphrase) {
14546
14546
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14547
14547
  try {
14548
- const challengeBytes = fromBase64url(challengeB64);
14549
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14548
+ const challengeBytes = fromBase64url$1(challengeB64);
14549
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14550
14550
  } finally {
14551
14551
  seed.fill(0);
14552
14552
  }
@@ -14558,7 +14558,7 @@ var CryptoIdentityKeystore = class {
14558
14558
  async _assertAndDerive(credentialIdHint) {
14559
14559
  const allowCredentials = [];
14560
14560
  if (credentialIdHint) allowCredentials.push({
14561
- id: fromBase64url(credentialIdHint),
14561
+ id: fromBase64url$1(credentialIdHint),
14562
14562
  type: "public-key"
14563
14563
  });
14564
14564
  else try {
@@ -14578,7 +14578,7 @@ var CryptoIdentityKeystore = class {
14578
14578
  } });
14579
14579
  if (!assertion) throw new Error("WebAuthn assertion cancelled");
14580
14580
  const prfOutput = extractPrfOutput(assertion);
14581
- const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
14581
+ const credentialIdB64 = toBase64url$1(new Uint8Array(assertion.rawId));
14582
14582
  let stored;
14583
14583
  try {
14584
14584
  const db = await openDb$4();
@@ -14591,7 +14591,7 @@ var CryptoIdentityKeystore = class {
14591
14591
  seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
14592
14592
  wrapKey.fill(0);
14593
14593
  } else seed = deriveEd25519Seed(prfOutput);
14594
- const publicKeyB64 = toBase64url(await ed.getPublicKeyAsync(seed));
14594
+ const publicKeyB64 = toBase64url$1(await ed.getPublicKeyAsync(seed));
14595
14595
  try {
14596
14596
  const db = await openDb$4();
14597
14597
  const existing = await dbGet(db, credentialIdB64);
@@ -14614,6 +14614,374 @@ var CryptoIdentityKeystore = class {
14614
14614
  }
14615
14615
  };
14616
14616
 
14617
+ //#endregion
14618
+ //#region packages/provider/src/NodeIdentity.ts
14619
+ /**
14620
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
14621
+ *
14622
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
14623
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
14624
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
14625
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
14626
+ * the same challenge → sign → verify flow exposed by
14627
+ * {@link AbracadabraClient.loginWithKey}.
14628
+ *
14629
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
14630
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
14631
+ * "login → register-on-404 → re-login" block. These helpers are the single
14632
+ * shared home for both.
14633
+ *
14634
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
14635
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
14636
+ * module stays importable from browser bundles (the fs path simply isn't
14637
+ * reachable there).
14638
+ */
14639
+ ed.hashes.sha512 = sha512;
14640
+ ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
14641
+ function toBase64url(bytes) {
14642
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14643
+ }
14644
+ function fromBase64url(b64) {
14645
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14646
+ const padLen = (4 - padded.length % 4) % 4;
14647
+ return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) => c.charCodeAt(0));
14648
+ }
14649
+ /**
14650
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
14651
+ * Returns a base64url signature suitable for
14652
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
14653
+ */
14654
+ function signChallengeWithSeed(challengeB64, seed) {
14655
+ return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
14656
+ }
14657
+ /**
14658
+ * Build the async `signChallenge` callback that
14659
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
14660
+ * returned function around to re-authenticate after a JWT expires.
14661
+ */
14662
+ function makeChallengeSigner(keypair) {
14663
+ return (challenge) => Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
14664
+ }
14665
+ /**
14666
+ * Derive a deterministic keypair from a seed string: the same input always
14667
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
14668
+ * actor maps to one reproducible account across runs.
14669
+ *
14670
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
14671
+ * historical value — change only if you intend a different identity space).
14672
+ */
14673
+ function deterministicKeypair(seed, salt = "orchestrator-salt") {
14674
+ const privateKey = sha512(new TextEncoder().encode(`${seed}:${salt}`)).slice(0, 32);
14675
+ return {
14676
+ privateKey,
14677
+ publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
14678
+ };
14679
+ }
14680
+ /**
14681
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
14682
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
14683
+ * `~/.abracadabra/<defaultFileName>`.
14684
+ *
14685
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
14686
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
14687
+ */
14688
+ async function loadOrCreateKeyFile(keyPath, opts = {}) {
14689
+ const { existsSync } = await import("node:fs");
14690
+ const { readFile, writeFile, mkdir } = await import("node:fs/promises");
14691
+ const { homedir } = await import("node:os");
14692
+ const { join, dirname } = await import("node:path");
14693
+ const path = keyPath ?? join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
14694
+ if (existsSync(path)) {
14695
+ const seed = await readFile(path);
14696
+ if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
14697
+ const privateKey = new Uint8Array(seed);
14698
+ return {
14699
+ privateKey,
14700
+ publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
14701
+ };
14702
+ }
14703
+ const privateKey = ed.utils.randomSecretKey();
14704
+ const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
14705
+ const dir = dirname(path);
14706
+ if (!existsSync(dir)) await mkdir(dir, {
14707
+ recursive: true,
14708
+ mode: 448
14709
+ });
14710
+ await writeFile(path, privateKey, { mode: 384 });
14711
+ opts.onCreate?.({
14712
+ path,
14713
+ publicKeyB64
14714
+ });
14715
+ return {
14716
+ privateKey,
14717
+ publicKeyB64
14718
+ };
14719
+ }
14720
+ /**
14721
+ * Authenticate `keypair` against the server, auto-registering on first run.
14722
+ *
14723
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
14724
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
14725
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
14726
+ * Any other error propagates. Returns the JWT.
14727
+ *
14728
+ * This is the one shared implementation of the "login → register-on-404 →
14729
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
14730
+ */
14731
+ async function loginOrRegisterWithKey(client, keypair, opts = {}) {
14732
+ const sign = makeChallengeSigner(keypair);
14733
+ try {
14734
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14735
+ } catch (err) {
14736
+ const e = err;
14737
+ const status = e?.status ?? e?.response?.status;
14738
+ const msg = String(e?.message ?? "").toLowerCase();
14739
+ if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
14740
+ opts.onRegister?.();
14741
+ const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
14742
+ await client.registerWithKey({
14743
+ publicKey: keypair.publicKeyB64,
14744
+ username,
14745
+ displayName: opts.displayName,
14746
+ deviceName: opts.deviceName,
14747
+ inviteCode: opts.inviteCode
14748
+ });
14749
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14750
+ }
14751
+ }
14752
+
14753
+ //#endregion
14754
+ //#region packages/provider/src/DocUtils.ts
14755
+ /**
14756
+ * Shared utilities for the DocumentManager ORM layer.
14757
+ *
14758
+ * These functions were previously duplicated across `mcp/src/utils.ts`,
14759
+ * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
14760
+ */
14761
+ /**
14762
+ * Wait for a provider's `synced` event with a timeout.
14763
+ * Resolves immediately if the provider is already synced.
14764
+ */
14765
+ function waitForSync(provider, timeoutMs = 15e3) {
14766
+ if (provider.isSynced) return Promise.resolve();
14767
+ return new Promise((resolve, reject) => {
14768
+ const timer = setTimeout(() => {
14769
+ provider.off("synced", handler);
14770
+ reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
14771
+ }, timeoutMs);
14772
+ function handler() {
14773
+ clearTimeout(timer);
14774
+ provider.off("synced", handler);
14775
+ resolve();
14776
+ }
14777
+ provider.on("synced", handler);
14778
+ });
14779
+ }
14780
+ /**
14781
+ * Wrap a promise with a timeout.
14782
+ */
14783
+ function withTimeout(promise, timeoutMs, message) {
14784
+ return new Promise((resolve, reject) => {
14785
+ const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
14786
+ promise.then((val) => {
14787
+ clearTimeout(timer);
14788
+ resolve(val);
14789
+ }, (err) => {
14790
+ clearTimeout(timer);
14791
+ reject(err);
14792
+ });
14793
+ });
14794
+ }
14795
+ /**
14796
+ * Normalize a document ID so the hub/root doc ID is treated as the tree root
14797
+ * (null). This lets callers pass the hub doc_id from list_spaces as
14798
+ * parentId/rootId and get the expected root-level results instead of an empty
14799
+ * set.
14800
+ */
14801
+ function normalizeRootId(id, rootDocId) {
14802
+ if (id == null) return null;
14803
+ return id === rootDocId ? null : id;
14804
+ }
14805
+ /**
14806
+ * Safely read a tree map value, converting Y.Map to plain object if needed.
14807
+ */
14808
+ function toPlain(val) {
14809
+ return val instanceof Y.Map ? val.toJSON() : val;
14810
+ }
14811
+ /**
14812
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
14813
+ *
14814
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
14815
+ * is given — the space root's own self-descriptor entry (keyed by the
14816
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
14817
+ * render as a phantom first child of itself. Entry values are nested
14818
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
14819
+ * Y.Map returns undefined).
14820
+ *
14821
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
14822
+ * `@abraca/resend` previously each carried a near-identical copy.
14823
+ */
14824
+ function readEntries(treeMap, selfId) {
14825
+ const entries = [];
14826
+ treeMap.forEach((raw, id) => {
14827
+ if (selfId && id === selfId) return;
14828
+ const value = toPlain(raw);
14829
+ if (typeof value !== "object" || value === null) return;
14830
+ const v = value;
14831
+ entries.push({
14832
+ id,
14833
+ label: typeof v.label === "string" && v.label ? v.label : "Untitled",
14834
+ parentId: v.parentId ?? null,
14835
+ order: typeof v.order === "number" ? v.order : 0,
14836
+ type: typeof v.type === "string" ? v.type : void 0,
14837
+ meta: v.meta,
14838
+ createdAt: typeof v.createdAt === "number" ? v.createdAt : void 0,
14839
+ updatedAt: typeof v.updatedAt === "number" ? v.updatedAt : void 0
14840
+ });
14841
+ });
14842
+ return entries;
14843
+ }
14844
+ /**
14845
+ * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
14846
+ * re-created key (create / duplicate / restore) where no concurrent
14847
+ * writer exists, so a whole-value write is safe. `undefined` fields are
14848
+ * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
14849
+ */
14850
+ function makeEntryMap(fields) {
14851
+ const m = new Y.Map();
14852
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
14853
+ return m;
14854
+ }
14855
+ /**
14856
+ * A label is a "placeholder" — i.e. carries no real user title — when it is
14857
+ * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
14858
+ * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
14859
+ * caught too). The whole tree-label corruption class boils down to a
14860
+ * placeholder being allowed to overwrite a real title; `patchEntry` refuses
14861
+ * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
14862
+ */
14863
+ function isPlaceholderLabel(label) {
14864
+ if (typeof label !== "string") return label == null;
14865
+ const t = label.trim();
14866
+ return t === "" || t.toLowerCase() === "untitled";
14867
+ }
14868
+ /**
14869
+ * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
14870
+ * concurrent edit to a *different* field by a peer is preserved instead
14871
+ * of being clobbered by a whole-entry write — the whole-entry-LWW fix
14872
+ * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
14873
+ *
14874
+ * - nested `Y.Map` entry → set/delete only the touched keys in place;
14875
+ * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
14876
+ * - missing entry → created from the patch (lenient; matches the prior
14877
+ * call-site behaviour of spreading `undefined`).
14878
+ *
14879
+ * A patch value of `undefined` deletes the key; `null` is written.
14880
+ * Self-transacting: it batches its writes in one `Y.Doc` transaction
14881
+ * (a safe reentrant no-op join when already inside one), so callers
14882
+ * don't need to pass or own a transaction.
14883
+ *
14884
+ * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
14885
+ * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
14886
+ * DROPPED when the entry already holds a real (non-placeholder) label —
14887
+ * regardless of which consumer (cou-sh title-sync, fs-sync rename
14888
+ * detection, MCP, table renderers, a stale snapshot) tried it. This is the
14889
+ * source-of-truth guard against the "card title silently becomes Untitled
14890
+ * / files renamed to untitled.md" corruption: a placeholder must never win
14891
+ * over a real title. Creating a brand-new entry with an empty label (e.g.
14892
+ * a fresh kanban card) is still allowed — the guard only fires when a real
14893
+ * label already exists. Pass `{ allowLabelClear: true }` to override (the
14894
+ * single legitimate "user explicitly cleared it" path).
14895
+ */
14896
+ function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
14897
+ const apply = () => {
14898
+ const raw = treeMap.get(id);
14899
+ let effectivePatch = patch;
14900
+ if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
14901
+ let existingLabel;
14902
+ if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
14903
+ else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
14904
+ else if (raw != null && typeof raw === "object") existingLabel = raw.label;
14905
+ if (!isPlaceholderLabel(existingLabel)) {
14906
+ const { label: _dropped, ...rest } = patch;
14907
+ effectivePatch = rest;
14908
+ }
14909
+ }
14910
+ if (raw instanceof Y.Map) {
14911
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
14912
+ else raw.set(k, v);
14913
+ for (const k of removeKeys) raw.delete(k);
14914
+ return;
14915
+ }
14916
+ const merged = {
14917
+ ...raw == null ? {} : toPlain(raw),
14918
+ ...effectivePatch
14919
+ };
14920
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
14921
+ for (const k of removeKeys) delete merged[k];
14922
+ treeMap.set(id, makeEntryMap(merged));
14923
+ };
14924
+ const doc = treeMap.doc;
14925
+ if (doc) doc.transact(apply);
14926
+ else apply();
14927
+ }
14928
+
14929
+ //#endregion
14930
+ //#region packages/provider/src/NodeConnect.ts
14931
+ /**
14932
+ * Node connection helpers — shared bootstrap primitives for the Node consumers
14933
+ * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).
14934
+ *
14935
+ * Each of those packages opened a synced root/space/inbox provider with the
14936
+ * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({
14937
+ * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the
14938
+ * entry space with the same "first Kind.Space, else first top-level doc" rule.
14939
+ * Both live here now so there is one implementation.
14940
+ *
14941
+ * These are deliberately small, faithful extractions — they do NOT own auth
14942
+ * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or
14943
+ * the reconnect/heal loop. Those stay with each consumer.
14944
+ */
14945
+ /**
14946
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
14947
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
14948
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
14949
+ * them with these exact options.
14950
+ *
14951
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
14952
+ * subdocs load lazily.
14953
+ */
14954
+ async function openSyncedProvider(opts) {
14955
+ const doc = new Y.Doc({ guid: opts.docId });
14956
+ const provider = new AbracadabraProvider({
14957
+ name: opts.docId,
14958
+ document: doc,
14959
+ client: opts.client,
14960
+ disableOfflineStore: true,
14961
+ subdocLoading: "lazy"
14962
+ });
14963
+ await waitForSync(provider, opts.syncTimeoutMs);
14964
+ return {
14965
+ doc,
14966
+ provider
14967
+ };
14968
+ }
14969
+ /**
14970
+ * Pick the entry-point document from a server root's top-level children: the
14971
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
14972
+ * Returns `null` when the server has no top-level documents.
14973
+ *
14974
+ * `spaces` is returned alongside so callers that track the space list (most do)
14975
+ * don't have to re-filter.
14976
+ */
14977
+ function pickEntrySpace(roots) {
14978
+ const spaces = roots.filter((d) => d.kind === Kind.Space);
14979
+ return {
14980
+ entry: spaces[0] ?? roots[0] ?? null,
14981
+ spaces
14982
+ };
14983
+ }
14984
+
14617
14985
  //#endregion
14618
14986
  //#region packages/provider/src/DocumentCache.ts
14619
14987
  const DB_VERSION$3 = 1;
@@ -15788,148 +16156,6 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15788
16156
  }
15789
16157
  };
15790
16158
 
15791
- //#endregion
15792
- //#region packages/provider/src/DocUtils.ts
15793
- /**
15794
- * Shared utilities for the DocumentManager ORM layer.
15795
- *
15796
- * These functions were previously duplicated across `mcp/src/utils.ts`,
15797
- * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
15798
- */
15799
- /**
15800
- * Wait for a provider's `synced` event with a timeout.
15801
- * Resolves immediately if the provider is already synced.
15802
- */
15803
- function waitForSync(provider, timeoutMs = 15e3) {
15804
- if (provider.isSynced) return Promise.resolve();
15805
- return new Promise((resolve, reject) => {
15806
- const timer = setTimeout(() => {
15807
- provider.off("synced", handler);
15808
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
15809
- }, timeoutMs);
15810
- function handler() {
15811
- clearTimeout(timer);
15812
- resolve();
15813
- }
15814
- provider.on("synced", handler);
15815
- });
15816
- }
15817
- /**
15818
- * Wrap a promise with a timeout.
15819
- */
15820
- function withTimeout(promise, timeoutMs, message) {
15821
- return new Promise((resolve, reject) => {
15822
- const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
15823
- promise.then((val) => {
15824
- clearTimeout(timer);
15825
- resolve(val);
15826
- }, (err) => {
15827
- clearTimeout(timer);
15828
- reject(err);
15829
- });
15830
- });
15831
- }
15832
- /**
15833
- * Normalize a document ID so the hub/root doc ID is treated as the tree root
15834
- * (null). This lets callers pass the hub doc_id from list_spaces as
15835
- * parentId/rootId and get the expected root-level results instead of an empty
15836
- * set.
15837
- */
15838
- function normalizeRootId(id, rootDocId) {
15839
- if (id == null) return null;
15840
- return id === rootDocId ? null : id;
15841
- }
15842
- /**
15843
- * Safely read a tree map value, converting Y.Map to plain object if needed.
15844
- */
15845
- function toPlain(val) {
15846
- return val instanceof Y.Map ? val.toJSON() : val;
15847
- }
15848
- /**
15849
- * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
15850
- * re-created key (create / duplicate / restore) where no concurrent
15851
- * writer exists, so a whole-value write is safe. `undefined` fields are
15852
- * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
15853
- */
15854
- function makeEntryMap(fields) {
15855
- const m = new Y.Map();
15856
- for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
15857
- return m;
15858
- }
15859
- /**
15860
- * A label is a "placeholder" — i.e. carries no real user title — when it is
15861
- * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
15862
- * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
15863
- * caught too). The whole tree-label corruption class boils down to a
15864
- * placeholder being allowed to overwrite a real title; `patchEntry` refuses
15865
- * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
15866
- */
15867
- function isPlaceholderLabel(label) {
15868
- if (typeof label !== "string") return label == null;
15869
- const t = label.trim();
15870
- return t === "" || t.toLowerCase() === "untitled";
15871
- }
15872
- /**
15873
- * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
15874
- * concurrent edit to a *different* field by a peer is preserved instead
15875
- * of being clobbered by a whole-entry write — the whole-entry-LWW fix
15876
- * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
15877
- *
15878
- * - nested `Y.Map` entry → set/delete only the touched keys in place;
15879
- * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
15880
- * - missing entry → created from the patch (lenient; matches the prior
15881
- * call-site behaviour of spreading `undefined`).
15882
- *
15883
- * A patch value of `undefined` deletes the key; `null` is written.
15884
- * Self-transacting: it batches its writes in one `Y.Doc` transaction
15885
- * (a safe reentrant no-op join when already inside one), so callers
15886
- * don't need to pass or own a transaction.
15887
- *
15888
- * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
15889
- * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
15890
- * DROPPED when the entry already holds a real (non-placeholder) label —
15891
- * regardless of which consumer (cou-sh title-sync, fs-sync rename
15892
- * detection, MCP, table renderers, a stale snapshot) tried it. This is the
15893
- * source-of-truth guard against the "card title silently becomes Untitled
15894
- * / files renamed to untitled.md" corruption: a placeholder must never win
15895
- * over a real title. Creating a brand-new entry with an empty label (e.g.
15896
- * a fresh kanban card) is still allowed — the guard only fires when a real
15897
- * label already exists. Pass `{ allowLabelClear: true }` to override (the
15898
- * single legitimate "user explicitly cleared it" path).
15899
- */
15900
- function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
15901
- const apply = () => {
15902
- const raw = treeMap.get(id);
15903
- let effectivePatch = patch;
15904
- if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
15905
- let existingLabel;
15906
- if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
15907
- else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
15908
- else if (raw != null && typeof raw === "object") existingLabel = raw.label;
15909
- if (!isPlaceholderLabel(existingLabel)) {
15910
- const { label: _dropped, ...rest } = patch;
15911
- effectivePatch = rest;
15912
- }
15913
- }
15914
- if (raw instanceof Y.Map) {
15915
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
15916
- else raw.set(k, v);
15917
- for (const k of removeKeys) raw.delete(k);
15918
- return;
15919
- }
15920
- const merged = {
15921
- ...raw == null ? {} : toPlain(raw),
15922
- ...effectivePatch
15923
- };
15924
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
15925
- for (const k of removeKeys) delete merged[k];
15926
- treeMap.set(id, makeEntryMap(merged));
15927
- };
15928
- const doc = treeMap.doc;
15929
- if (doc) doc.transact(apply);
15930
- else apply();
15931
- }
15932
-
15933
16159
  //#endregion
15934
16160
  //#region packages/provider/src/TreeTimestamps.ts
15935
16161
  /**
@@ -21186,5 +21412,5 @@ var DocumentManager = class {
21186
21412
  };
21187
21413
 
21188
21414
  //#endregion
21189
- export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, WsReadyStates, YjsDataChannel, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, deriveIdentityDocId, deriveSeedWrappingKey, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, parseFrontmatter, patchEntry, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, reconcileDocCover, recordFromYAny, resolvePageType, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
21415
+ export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, WsReadyStates, YjsDataChannel, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loginOrRegisterWithKey, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, resolvePageType, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
21190
21416
  //# sourceMappingURL=abracadabra-provider.esm.js.map