@abraca/dabra 2.33.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.
@@ -13974,7 +13974,7 @@ const MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode("abracadabra
13974
13974
  const MNEMONIC_HKDF_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-identity-v1");
13975
13975
  /** HKDF info string for deriving the AES-GCM seed-wrapping key from PRF output. */
13976
13976
  const SEED_WRAP_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-seed-wrap-v1");
13977
- function toBase64url$1(bytes) {
13977
+ function toBase64url$2(bytes) {
13978
13978
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
13979
13979
  }
13980
13980
  /**
@@ -14016,14 +14016,14 @@ function mnemonicToEd25519Seed(mnemonic, passphrase) {
14016
14016
  async function mnemonicToKeyPair(mnemonic, passphrase) {
14017
14017
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14018
14018
  const publicKey = await _noble_ed25519.getPublicKeyAsync(seed);
14019
- const publicKeyB64 = toBase64url$1(publicKey);
14019
+ const publicKeyB64 = toBase64url$2(publicKey);
14020
14020
  const x25519PublicKey = ed25519.utils.toMontgomery(publicKey);
14021
14021
  return {
14022
14022
  seed,
14023
14023
  publicKey,
14024
14024
  publicKeyB64,
14025
14025
  x25519PublicKey,
14026
- x25519PublicKeyB64: toBase64url$1(x25519PublicKey)
14026
+ x25519PublicKeyB64: toBase64url$2(x25519PublicKey)
14027
14027
  };
14028
14028
  }
14029
14029
  /**
@@ -14134,10 +14134,10 @@ const PRF_SALT = new Uint8Array([
14134
14134
  207
14135
14135
  ]);
14136
14136
  const HKDF_INFO$1 = new TextEncoder().encode("abracadabra-identity-v1");
14137
- function toBase64url(bytes) {
14137
+ function toBase64url$1(bytes) {
14138
14138
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14139
14139
  }
14140
- function fromBase64url(b64) {
14140
+ function fromBase64url$1(b64) {
14141
14141
  const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14142
14142
  const padLen = (4 - padded.length % 4) % 4;
14143
14143
  const padded2 = padded + "=".repeat(padLen);
@@ -14255,9 +14255,9 @@ var CryptoIdentityKeystore = class {
14255
14255
  if (!credential) throw new Error("WebAuthn credential creation cancelled");
14256
14256
  const seed = deriveEd25519Seed(extractPrfOutput(credential));
14257
14257
  const publicKey = await _noble_ed25519.getPublicKeyAsync(seed);
14258
- const publicKeyB64 = toBase64url(publicKey);
14259
- const x25519PubB64 = toBase64url(ed25519.utils.toMontgomery(publicKey));
14260
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14258
+ const publicKeyB64 = toBase64url$1(publicKey);
14259
+ const x25519PubB64 = toBase64url$1(ed25519.utils.toMontgomery(publicKey));
14260
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14261
14261
  const db = await openDb$4();
14262
14262
  await dbPut(db, credentialIdB64, {
14263
14263
  username,
@@ -14283,8 +14283,8 @@ var CryptoIdentityKeystore = class {
14283
14283
  async sign(challengeB64, credentialIdHint) {
14284
14284
  const { seed } = await this._assertAndDerive(credentialIdHint);
14285
14285
  try {
14286
- const challengeBytes = fromBase64url(challengeB64);
14287
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14286
+ const challengeBytes = fromBase64url$1(challengeB64);
14287
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14288
14288
  } finally {
14289
14289
  seed.fill(0);
14290
14290
  }
@@ -14369,7 +14369,7 @@ var CryptoIdentityKeystore = class {
14369
14369
  try {
14370
14370
  const all = await dbGetAll(db);
14371
14371
  if (all.length === 0) return null;
14372
- const edPub = fromBase64url(all[0].value.publicKey);
14372
+ const edPub = fromBase64url$1(all[0].value.publicKey);
14373
14373
  return ed25519.utils.toMontgomery(edPub);
14374
14374
  } finally {
14375
14375
  db.close();
@@ -14464,7 +14464,7 @@ var CryptoIdentityKeystore = class {
14464
14464
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14465
14465
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14466
14466
  wrapKey.fill(0);
14467
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14467
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14468
14468
  const db = await openDb$4();
14469
14469
  await dbPut(db, credentialIdB64, {
14470
14470
  username,
@@ -14510,7 +14510,7 @@ var CryptoIdentityKeystore = class {
14510
14510
  name: rpName
14511
14511
  },
14512
14512
  user: {
14513
- id: fromBase64url(kp.publicKeyB64),
14513
+ id: fromBase64url$1(kp.publicKeyB64),
14514
14514
  name: kp.publicKeyB64.slice(0, 16),
14515
14515
  displayName: kp.publicKeyB64.slice(0, 16)
14516
14516
  },
@@ -14534,7 +14534,7 @@ var CryptoIdentityKeystore = class {
14534
14534
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14535
14535
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14536
14536
  wrapKey.fill(0);
14537
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14537
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14538
14538
  let username = "";
14539
14539
  try {
14540
14540
  const db = await openDb$4();
@@ -14565,8 +14565,8 @@ var CryptoIdentityKeystore = class {
14565
14565
  * The caller manages the seed lifecycle (wiping on session end).
14566
14566
  */
14567
14567
  static async signWithSeed(challengeB64, seed) {
14568
- const challengeBytes = fromBase64url(challengeB64);
14569
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14568
+ const challengeBytes = fromBase64url$1(challengeB64);
14569
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14570
14570
  }
14571
14571
  /**
14572
14572
  * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
@@ -14575,8 +14575,8 @@ var CryptoIdentityKeystore = class {
14575
14575
  static async signWithMnemonic(mnemonic, challengeB64, passphrase) {
14576
14576
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14577
14577
  try {
14578
- const challengeBytes = fromBase64url(challengeB64);
14579
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14578
+ const challengeBytes = fromBase64url$1(challengeB64);
14579
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14580
14580
  } finally {
14581
14581
  seed.fill(0);
14582
14582
  }
@@ -14588,7 +14588,7 @@ var CryptoIdentityKeystore = class {
14588
14588
  async _assertAndDerive(credentialIdHint) {
14589
14589
  const allowCredentials = [];
14590
14590
  if (credentialIdHint) allowCredentials.push({
14591
- id: fromBase64url(credentialIdHint),
14591
+ id: fromBase64url$1(credentialIdHint),
14592
14592
  type: "public-key"
14593
14593
  });
14594
14594
  else try {
@@ -14608,7 +14608,7 @@ var CryptoIdentityKeystore = class {
14608
14608
  } });
14609
14609
  if (!assertion) throw new Error("WebAuthn assertion cancelled");
14610
14610
  const prfOutput = extractPrfOutput(assertion);
14611
- const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
14611
+ const credentialIdB64 = toBase64url$1(new Uint8Array(assertion.rawId));
14612
14612
  let stored;
14613
14613
  try {
14614
14614
  const db = await openDb$4();
@@ -14621,7 +14621,7 @@ var CryptoIdentityKeystore = class {
14621
14621
  seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
14622
14622
  wrapKey.fill(0);
14623
14623
  } else seed = deriveEd25519Seed(prfOutput);
14624
- const publicKeyB64 = toBase64url(await _noble_ed25519.getPublicKeyAsync(seed));
14624
+ const publicKeyB64 = toBase64url$1(await _noble_ed25519.getPublicKeyAsync(seed));
14625
14625
  try {
14626
14626
  const db = await openDb$4();
14627
14627
  const existing = await dbGet(db, credentialIdB64);
@@ -14644,6 +14644,374 @@ var CryptoIdentityKeystore = class {
14644
14644
  }
14645
14645
  };
14646
14646
 
14647
+ //#endregion
14648
+ //#region packages/provider/src/NodeIdentity.ts
14649
+ /**
14650
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
14651
+ *
14652
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
14653
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
14654
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
14655
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
14656
+ * the same challenge → sign → verify flow exposed by
14657
+ * {@link AbracadabraClient.loginWithKey}.
14658
+ *
14659
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
14660
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
14661
+ * "login → register-on-404 → re-login" block. These helpers are the single
14662
+ * shared home for both.
14663
+ *
14664
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
14665
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
14666
+ * module stays importable from browser bundles (the fs path simply isn't
14667
+ * reachable there).
14668
+ */
14669
+ _noble_ed25519.hashes.sha512 = sha512;
14670
+ _noble_ed25519.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
14671
+ function toBase64url(bytes) {
14672
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14673
+ }
14674
+ function fromBase64url(b64) {
14675
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14676
+ const padLen = (4 - padded.length % 4) % 4;
14677
+ return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) => c.charCodeAt(0));
14678
+ }
14679
+ /**
14680
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
14681
+ * Returns a base64url signature suitable for
14682
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
14683
+ */
14684
+ function signChallengeWithSeed(challengeB64, seed) {
14685
+ return toBase64url(_noble_ed25519.sign(fromBase64url(challengeB64), seed));
14686
+ }
14687
+ /**
14688
+ * Build the async `signChallenge` callback that
14689
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
14690
+ * returned function around to re-authenticate after a JWT expires.
14691
+ */
14692
+ function makeChallengeSigner(keypair) {
14693
+ return (challenge) => Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
14694
+ }
14695
+ /**
14696
+ * Derive a deterministic keypair from a seed string: the same input always
14697
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
14698
+ * actor maps to one reproducible account across runs.
14699
+ *
14700
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
14701
+ * historical value — change only if you intend a different identity space).
14702
+ */
14703
+ function deterministicKeypair(seed, salt = "orchestrator-salt") {
14704
+ const privateKey = sha512(new TextEncoder().encode(`${seed}:${salt}`)).slice(0, 32);
14705
+ return {
14706
+ privateKey,
14707
+ publicKeyB64: toBase64url(_noble_ed25519.getPublicKey(privateKey))
14708
+ };
14709
+ }
14710
+ /**
14711
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
14712
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
14713
+ * `~/.abracadabra/<defaultFileName>`.
14714
+ *
14715
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
14716
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
14717
+ */
14718
+ async function loadOrCreateKeyFile(keyPath, opts = {}) {
14719
+ const { existsSync } = await import("node:fs");
14720
+ const { readFile, writeFile, mkdir } = await import("node:fs/promises");
14721
+ const { homedir } = await import("node:os");
14722
+ const { join, dirname } = await import("node:path");
14723
+ const path = keyPath ?? join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
14724
+ if (existsSync(path)) {
14725
+ const seed = await readFile(path);
14726
+ if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
14727
+ const privateKey = new Uint8Array(seed);
14728
+ return {
14729
+ privateKey,
14730
+ publicKeyB64: toBase64url(_noble_ed25519.getPublicKey(privateKey))
14731
+ };
14732
+ }
14733
+ const privateKey = _noble_ed25519.utils.randomSecretKey();
14734
+ const publicKeyB64 = toBase64url(_noble_ed25519.getPublicKey(privateKey));
14735
+ const dir = dirname(path);
14736
+ if (!existsSync(dir)) await mkdir(dir, {
14737
+ recursive: true,
14738
+ mode: 448
14739
+ });
14740
+ await writeFile(path, privateKey, { mode: 384 });
14741
+ opts.onCreate?.({
14742
+ path,
14743
+ publicKeyB64
14744
+ });
14745
+ return {
14746
+ privateKey,
14747
+ publicKeyB64
14748
+ };
14749
+ }
14750
+ /**
14751
+ * Authenticate `keypair` against the server, auto-registering on first run.
14752
+ *
14753
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
14754
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
14755
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
14756
+ * Any other error propagates. Returns the JWT.
14757
+ *
14758
+ * This is the one shared implementation of the "login → register-on-404 →
14759
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
14760
+ */
14761
+ async function loginOrRegisterWithKey(client, keypair, opts = {}) {
14762
+ const sign = makeChallengeSigner(keypair);
14763
+ try {
14764
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14765
+ } catch (err) {
14766
+ const e = err;
14767
+ const status = e?.status ?? e?.response?.status;
14768
+ const msg = String(e?.message ?? "").toLowerCase();
14769
+ if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
14770
+ opts.onRegister?.();
14771
+ const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
14772
+ await client.registerWithKey({
14773
+ publicKey: keypair.publicKeyB64,
14774
+ username,
14775
+ displayName: opts.displayName,
14776
+ deviceName: opts.deviceName,
14777
+ inviteCode: opts.inviteCode
14778
+ });
14779
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14780
+ }
14781
+ }
14782
+
14783
+ //#endregion
14784
+ //#region packages/provider/src/DocUtils.ts
14785
+ /**
14786
+ * Shared utilities for the DocumentManager ORM layer.
14787
+ *
14788
+ * These functions were previously duplicated across `mcp/src/utils.ts`,
14789
+ * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
14790
+ */
14791
+ /**
14792
+ * Wait for a provider's `synced` event with a timeout.
14793
+ * Resolves immediately if the provider is already synced.
14794
+ */
14795
+ function waitForSync(provider, timeoutMs = 15e3) {
14796
+ if (provider.isSynced) return Promise.resolve();
14797
+ return new Promise((resolve, reject) => {
14798
+ const timer = setTimeout(() => {
14799
+ provider.off("synced", handler);
14800
+ reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
14801
+ }, timeoutMs);
14802
+ function handler() {
14803
+ clearTimeout(timer);
14804
+ provider.off("synced", handler);
14805
+ resolve();
14806
+ }
14807
+ provider.on("synced", handler);
14808
+ });
14809
+ }
14810
+ /**
14811
+ * Wrap a promise with a timeout.
14812
+ */
14813
+ function withTimeout(promise, timeoutMs, message) {
14814
+ return new Promise((resolve, reject) => {
14815
+ const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
14816
+ promise.then((val) => {
14817
+ clearTimeout(timer);
14818
+ resolve(val);
14819
+ }, (err) => {
14820
+ clearTimeout(timer);
14821
+ reject(err);
14822
+ });
14823
+ });
14824
+ }
14825
+ /**
14826
+ * Normalize a document ID so the hub/root doc ID is treated as the tree root
14827
+ * (null). This lets callers pass the hub doc_id from list_spaces as
14828
+ * parentId/rootId and get the expected root-level results instead of an empty
14829
+ * set.
14830
+ */
14831
+ function normalizeRootId(id, rootDocId) {
14832
+ if (id == null) return null;
14833
+ return id === rootDocId ? null : id;
14834
+ }
14835
+ /**
14836
+ * Safely read a tree map value, converting Y.Map to plain object if needed.
14837
+ */
14838
+ function toPlain(val) {
14839
+ return val instanceof yjs.Map ? val.toJSON() : val;
14840
+ }
14841
+ /**
14842
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
14843
+ *
14844
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
14845
+ * is given — the space root's own self-descriptor entry (keyed by the
14846
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
14847
+ * render as a phantom first child of itself. Entry values are nested
14848
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
14849
+ * Y.Map returns undefined).
14850
+ *
14851
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
14852
+ * `@abraca/resend` previously each carried a near-identical copy.
14853
+ */
14854
+ function readEntries(treeMap, selfId) {
14855
+ const entries = [];
14856
+ treeMap.forEach((raw, id) => {
14857
+ if (selfId && id === selfId) return;
14858
+ const value = toPlain(raw);
14859
+ if (typeof value !== "object" || value === null) return;
14860
+ const v = value;
14861
+ entries.push({
14862
+ id,
14863
+ label: typeof v.label === "string" && v.label ? v.label : "Untitled",
14864
+ parentId: v.parentId ?? null,
14865
+ order: typeof v.order === "number" ? v.order : 0,
14866
+ type: typeof v.type === "string" ? v.type : void 0,
14867
+ meta: v.meta,
14868
+ createdAt: typeof v.createdAt === "number" ? v.createdAt : void 0,
14869
+ updatedAt: typeof v.updatedAt === "number" ? v.updatedAt : void 0
14870
+ });
14871
+ });
14872
+ return entries;
14873
+ }
14874
+ /**
14875
+ * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
14876
+ * re-created key (create / duplicate / restore) where no concurrent
14877
+ * writer exists, so a whole-value write is safe. `undefined` fields are
14878
+ * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
14879
+ */
14880
+ function makeEntryMap(fields) {
14881
+ const m = new yjs.Map();
14882
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
14883
+ return m;
14884
+ }
14885
+ /**
14886
+ * A label is a "placeholder" — i.e. carries no real user title — when it is
14887
+ * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
14888
+ * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
14889
+ * caught too). The whole tree-label corruption class boils down to a
14890
+ * placeholder being allowed to overwrite a real title; `patchEntry` refuses
14891
+ * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
14892
+ */
14893
+ function isPlaceholderLabel(label) {
14894
+ if (typeof label !== "string") return label == null;
14895
+ const t = label.trim();
14896
+ return t === "" || t.toLowerCase() === "untitled";
14897
+ }
14898
+ /**
14899
+ * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
14900
+ * concurrent edit to a *different* field by a peer is preserved instead
14901
+ * of being clobbered by a whole-entry write — the whole-entry-LWW fix
14902
+ * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
14903
+ *
14904
+ * - nested `Y.Map` entry → set/delete only the touched keys in place;
14905
+ * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
14906
+ * - missing entry → created from the patch (lenient; matches the prior
14907
+ * call-site behaviour of spreading `undefined`).
14908
+ *
14909
+ * A patch value of `undefined` deletes the key; `null` is written.
14910
+ * Self-transacting: it batches its writes in one `Y.Doc` transaction
14911
+ * (a safe reentrant no-op join when already inside one), so callers
14912
+ * don't need to pass or own a transaction.
14913
+ *
14914
+ * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
14915
+ * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
14916
+ * DROPPED when the entry already holds a real (non-placeholder) label —
14917
+ * regardless of which consumer (cou-sh title-sync, fs-sync rename
14918
+ * detection, MCP, table renderers, a stale snapshot) tried it. This is the
14919
+ * source-of-truth guard against the "card title silently becomes Untitled
14920
+ * / files renamed to untitled.md" corruption: a placeholder must never win
14921
+ * over a real title. Creating a brand-new entry with an empty label (e.g.
14922
+ * a fresh kanban card) is still allowed — the guard only fires when a real
14923
+ * label already exists. Pass `{ allowLabelClear: true }` to override (the
14924
+ * single legitimate "user explicitly cleared it" path).
14925
+ */
14926
+ function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
14927
+ const apply = () => {
14928
+ const raw = treeMap.get(id);
14929
+ let effectivePatch = patch;
14930
+ if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
14931
+ let existingLabel;
14932
+ if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
14933
+ else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
14934
+ else if (raw != null && typeof raw === "object") existingLabel = raw.label;
14935
+ if (!isPlaceholderLabel(existingLabel)) {
14936
+ const { label: _dropped, ...rest } = patch;
14937
+ effectivePatch = rest;
14938
+ }
14939
+ }
14940
+ if (raw instanceof yjs.Map) {
14941
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
14942
+ else raw.set(k, v);
14943
+ for (const k of removeKeys) raw.delete(k);
14944
+ return;
14945
+ }
14946
+ const merged = {
14947
+ ...raw == null ? {} : toPlain(raw),
14948
+ ...effectivePatch
14949
+ };
14950
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
14951
+ for (const k of removeKeys) delete merged[k];
14952
+ treeMap.set(id, makeEntryMap(merged));
14953
+ };
14954
+ const doc = treeMap.doc;
14955
+ if (doc) doc.transact(apply);
14956
+ else apply();
14957
+ }
14958
+
14959
+ //#endregion
14960
+ //#region packages/provider/src/NodeConnect.ts
14961
+ /**
14962
+ * Node connection helpers — shared bootstrap primitives for the Node consumers
14963
+ * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).
14964
+ *
14965
+ * Each of those packages opened a synced root/space/inbox provider with the
14966
+ * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({
14967
+ * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the
14968
+ * entry space with the same "first Kind.Space, else first top-level doc" rule.
14969
+ * Both live here now so there is one implementation.
14970
+ *
14971
+ * These are deliberately small, faithful extractions — they do NOT own auth
14972
+ * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or
14973
+ * the reconnect/heal loop. Those stay with each consumer.
14974
+ */
14975
+ /**
14976
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
14977
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
14978
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
14979
+ * them with these exact options.
14980
+ *
14981
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
14982
+ * subdocs load lazily.
14983
+ */
14984
+ async function openSyncedProvider(opts) {
14985
+ const doc = new yjs.Doc({ guid: opts.docId });
14986
+ const provider = new AbracadabraProvider({
14987
+ name: opts.docId,
14988
+ document: doc,
14989
+ client: opts.client,
14990
+ disableOfflineStore: true,
14991
+ subdocLoading: "lazy"
14992
+ });
14993
+ await waitForSync(provider, opts.syncTimeoutMs);
14994
+ return {
14995
+ doc,
14996
+ provider
14997
+ };
14998
+ }
14999
+ /**
15000
+ * Pick the entry-point document from a server root's top-level children: the
15001
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
15002
+ * Returns `null` when the server has no top-level documents.
15003
+ *
15004
+ * `spaces` is returned alongside so callers that track the space list (most do)
15005
+ * don't have to re-filter.
15006
+ */
15007
+ function pickEntrySpace(roots) {
15008
+ const spaces = roots.filter((d) => d.kind === Kind.Space);
15009
+ return {
15010
+ entry: spaces[0] ?? roots[0] ?? null,
15011
+ spaces
15012
+ };
15013
+ }
15014
+
14647
15015
  //#endregion
14648
15016
  //#region packages/provider/src/DocumentCache.ts
14649
15017
  const DB_VERSION$3 = 1;
@@ -15827,148 +16195,6 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15827
16195
  }
15828
16196
  };
15829
16197
 
15830
- //#endregion
15831
- //#region packages/provider/src/DocUtils.ts
15832
- /**
15833
- * Shared utilities for the DocumentManager ORM layer.
15834
- *
15835
- * These functions were previously duplicated across `mcp/src/utils.ts`,
15836
- * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
15837
- */
15838
- /**
15839
- * Wait for a provider's `synced` event with a timeout.
15840
- * Resolves immediately if the provider is already synced.
15841
- */
15842
- function waitForSync(provider, timeoutMs = 15e3) {
15843
- if (provider.isSynced) return Promise.resolve();
15844
- return new Promise((resolve, reject) => {
15845
- const timer = setTimeout(() => {
15846
- provider.off("synced", handler);
15847
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
15848
- }, timeoutMs);
15849
- function handler() {
15850
- clearTimeout(timer);
15851
- resolve();
15852
- }
15853
- provider.on("synced", handler);
15854
- });
15855
- }
15856
- /**
15857
- * Wrap a promise with a timeout.
15858
- */
15859
- function withTimeout(promise, timeoutMs, message) {
15860
- return new Promise((resolve, reject) => {
15861
- const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
15862
- promise.then((val) => {
15863
- clearTimeout(timer);
15864
- resolve(val);
15865
- }, (err) => {
15866
- clearTimeout(timer);
15867
- reject(err);
15868
- });
15869
- });
15870
- }
15871
- /**
15872
- * Normalize a document ID so the hub/root doc ID is treated as the tree root
15873
- * (null). This lets callers pass the hub doc_id from list_spaces as
15874
- * parentId/rootId and get the expected root-level results instead of an empty
15875
- * set.
15876
- */
15877
- function normalizeRootId(id, rootDocId) {
15878
- if (id == null) return null;
15879
- return id === rootDocId ? null : id;
15880
- }
15881
- /**
15882
- * Safely read a tree map value, converting Y.Map to plain object if needed.
15883
- */
15884
- function toPlain(val) {
15885
- return val instanceof yjs.Map ? val.toJSON() : val;
15886
- }
15887
- /**
15888
- * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
15889
- * re-created key (create / duplicate / restore) where no concurrent
15890
- * writer exists, so a whole-value write is safe. `undefined` fields are
15891
- * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
15892
- */
15893
- function makeEntryMap(fields) {
15894
- const m = new yjs.Map();
15895
- for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
15896
- return m;
15897
- }
15898
- /**
15899
- * A label is a "placeholder" — i.e. carries no real user title — when it is
15900
- * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
15901
- * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
15902
- * caught too). The whole tree-label corruption class boils down to a
15903
- * placeholder being allowed to overwrite a real title; `patchEntry` refuses
15904
- * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
15905
- */
15906
- function isPlaceholderLabel(label) {
15907
- if (typeof label !== "string") return label == null;
15908
- const t = label.trim();
15909
- return t === "" || t.toLowerCase() === "untitled";
15910
- }
15911
- /**
15912
- * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
15913
- * concurrent edit to a *different* field by a peer is preserved instead
15914
- * of being clobbered by a whole-entry write — the whole-entry-LWW fix
15915
- * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
15916
- *
15917
- * - nested `Y.Map` entry → set/delete only the touched keys in place;
15918
- * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
15919
- * - missing entry → created from the patch (lenient; matches the prior
15920
- * call-site behaviour of spreading `undefined`).
15921
- *
15922
- * A patch value of `undefined` deletes the key; `null` is written.
15923
- * Self-transacting: it batches its writes in one `Y.Doc` transaction
15924
- * (a safe reentrant no-op join when already inside one), so callers
15925
- * don't need to pass or own a transaction.
15926
- *
15927
- * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
15928
- * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
15929
- * DROPPED when the entry already holds a real (non-placeholder) label —
15930
- * regardless of which consumer (cou-sh title-sync, fs-sync rename
15931
- * detection, MCP, table renderers, a stale snapshot) tried it. This is the
15932
- * source-of-truth guard against the "card title silently becomes Untitled
15933
- * / files renamed to untitled.md" corruption: a placeholder must never win
15934
- * over a real title. Creating a brand-new entry with an empty label (e.g.
15935
- * a fresh kanban card) is still allowed — the guard only fires when a real
15936
- * label already exists. Pass `{ allowLabelClear: true }` to override (the
15937
- * single legitimate "user explicitly cleared it" path).
15938
- */
15939
- function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
15940
- const apply = () => {
15941
- const raw = treeMap.get(id);
15942
- let effectivePatch = patch;
15943
- if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
15944
- let existingLabel;
15945
- if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
15946
- else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
15947
- else if (raw != null && typeof raw === "object") existingLabel = raw.label;
15948
- if (!isPlaceholderLabel(existingLabel)) {
15949
- const { label: _dropped, ...rest } = patch;
15950
- effectivePatch = rest;
15951
- }
15952
- }
15953
- if (raw instanceof yjs.Map) {
15954
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
15955
- else raw.set(k, v);
15956
- for (const k of removeKeys) raw.delete(k);
15957
- return;
15958
- }
15959
- const merged = {
15960
- ...raw == null ? {} : toPlain(raw),
15961
- ...effectivePatch
15962
- };
15963
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
15964
- for (const k of removeKeys) delete merged[k];
15965
- treeMap.set(id, makeEntryMap(merged));
15966
- };
15967
- const doc = treeMap.doc;
15968
- if (doc) doc.transact(apply);
15969
- else apply();
15970
- }
15971
-
15972
16198
  //#endregion
15973
16199
  //#region packages/provider/src/TreeTimestamps.ts
15974
16200
  /**
@@ -21337,6 +21563,7 @@ exports.decryptChatContent = decryptChatContent;
21337
21563
  exports.decryptField = decryptField;
21338
21564
  exports.deriveIdentityDocId = deriveIdentityDocId;
21339
21565
  exports.deriveSeedWrappingKey = deriveSeedWrappingKey;
21566
+ exports.deterministicKeypair = deterministicKeypair;
21340
21567
  exports.encryptChatContent = encryptChatContent;
21341
21568
  exports.encryptField = encryptField;
21342
21569
  exports.filenameToLabel = filenameToLabel;
@@ -21344,20 +21571,27 @@ exports.foldRecords = foldRecords;
21344
21571
  exports.generateMnemonic = generateMnemonic;
21345
21572
  exports.isEncryptedContent = isEncryptedContent;
21346
21573
  exports.isPlaceholderLabel = isPlaceholderLabel;
21574
+ exports.loadOrCreateKeyFile = loadOrCreateKeyFile;
21575
+ exports.loginOrRegisterWithKey = loginOrRegisterWithKey;
21576
+ exports.makeChallengeSigner = makeChallengeSigner;
21347
21577
  exports.makeEncryptedYMap = makeEncryptedYMap;
21348
21578
  exports.makeEncryptedYText = makeEncryptedYText;
21349
21579
  exports.makeEntryMap = makeEntryMap;
21350
21580
  exports.mnemonicToEd25519Seed = mnemonicToEd25519Seed;
21351
21581
  exports.mnemonicToKeyPair = mnemonicToKeyPair;
21352
21582
  exports.normalizeRootId = normalizeRootId;
21583
+ exports.openSyncedProvider = openSyncedProvider;
21353
21584
  exports.parseFrontmatter = parseFrontmatter;
21354
21585
  exports.patchEntry = patchEntry;
21586
+ exports.pickEntrySpace = pickEntrySpace;
21355
21587
  exports.populateYDocFromMarkdown = populateYDocFromMarkdown;
21356
21588
  exports.readAuthMessage = readAuthMessage;
21357
21589
  exports.readBlocksFromFragment = readBlocksFromFragment;
21590
+ exports.readEntries = readEntries;
21358
21591
  exports.reconcileDocCover = reconcileDocCover;
21359
21592
  exports.recordFromYAny = recordFromYAny;
21360
21593
  exports.resolvePageType = resolvePageType;
21594
+ exports.signChallengeWithSeed = signChallengeWithSeed;
21361
21595
  exports.toPlain = toPlain;
21362
21596
  exports.unwrapSeed = unwrapSeed;
21363
21597
  exports.validateMnemonic = validateMnemonic;