@abraca/dabra 2.90.0 → 2.92.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.
Files changed (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,179 +0,0 @@
1
- /**
2
- * Phase 2 Day 1 — typed projection types for the provider.
3
- *
4
- * The provider package never imports `@abraca/schema` directly (Rule 1 —
5
- * core stays schema-free). Instead, it declares a structural witness that
6
- * any registry — including `@abraca/schema`'s `SchemaRegistry<TMap>` — can
7
- * satisfy.
8
- *
9
- * Consumers parameterise typed accessors with the registry value:
10
- *
11
- * const board = dm.tree.getTyped(kanbanSchema, "kanban", id);
12
- * // board.meta.kanbanColumnWidth is typed as the kanban enum | undefined
13
- *
14
- * The phantom `__metaMap` carries the per-doc-type meta map so the
15
- * generics below can extract it without a runtime dependency.
16
- */
17
- import type { PageMeta, TreeEntry } from "./DocTypes.ts";
18
-
19
- /**
20
- * Structural shape of a typed schema registry. The `TMap` parameter is the
21
- * meta-type map keyed by doc-type name (e.g. `{ "kanban": KanbanMeta, ... }`).
22
- * `@abraca/schema`'s `SchemaRegistry<TMap>` satisfies this shape.
23
- */
24
- export interface SchemaRegistryLike<
25
- TMap extends Record<string, unknown> = Record<string, unknown>,
26
- > {
27
- readonly types: ReadonlyMap<string, unknown>;
28
- readonly __metaMap?: TMap;
29
- }
30
-
31
- /** Extract the doc-type names from a registry. */
32
- export type SchemaDocTypeName<S> =
33
- S extends SchemaRegistryLike<infer M> ? keyof M & string : never;
34
-
35
- /** Extract the meta type for a given doc-type name from a registry. */
36
- export type SchemaMetaOf<S, N extends string> =
37
- S extends SchemaRegistryLike<infer M>
38
- ? N extends keyof M
39
- ? M[N]
40
- : never
41
- : never;
42
-
43
- /**
44
- * A tree entry projected against a typed registry. The `meta` field is
45
- * narrowed to `TMap[N] | undefined` so consumers get full type inference
46
- * without an explicit cast.
47
- *
48
- * Note: `meta` is optional even when the registry mandates fields — the
49
- * tree may contain entries written before the schema was authored, and
50
- * Rule 4 means we don't reject them at read time.
51
- */
52
- export interface TypedTreeEntry<
53
- TMap extends Record<string, unknown>,
54
- N extends keyof TMap & string,
55
- > {
56
- readonly id: string;
57
- readonly type: N;
58
- readonly label: string;
59
- readonly parentId: string | null;
60
- readonly order: number;
61
- readonly meta: TMap[N] | undefined;
62
- readonly createdAt: number | undefined;
63
- readonly updatedAt: number | undefined;
64
- }
65
-
66
- /**
67
- * A typed surface bound to a schema. Returned by
68
- * `DocumentManager.docs(schema)` so the schema doesn't have to be repeated
69
- * at every call site.
70
- *
71
- * Read methods (`get`, `getEntry`, `narrow`) project the existing
72
- * untyped tree without performing schema validation. Write methods
73
- * (`update`, `set`, `clear`) delegate to `MetaManager` and are subject
74
- * to whatever validator was attached via `MetaManager.setSchema` —
75
- * they do NOT auto-attach the registry passed to `dm.docs()`.
76
- */
77
- export interface TypedDocsClient<TMap extends Record<string, unknown>> {
78
- /**
79
- * Fetch a tree entry projected as the requested doc-type. Returns
80
- * `null` when the entry doesn't exist OR when its `type` field doesn't
81
- * match `expectedType`.
82
- */
83
- get<N extends keyof TMap & string>(
84
- expectedType: N,
85
- id: string,
86
- ): TypedTreeEntry<TMap, N> | null;
87
- /**
88
- * Fetch the raw, untyped entry (no type-narrowing applied). Useful when
89
- * the caller wants the underlying record without the projection.
90
- */
91
- getEntry(id: string): TreeEntry | null;
92
- /**
93
- * Discriminator helper: narrows an arbitrary `TreeEntry` to the
94
- * requested doc-type, returning a typed projection or `null` on mismatch.
95
- * No runtime read — pure type-guard helper.
96
- */
97
- narrow<N extends keyof TMap & string>(
98
- expectedType: N,
99
- entry: TreeEntry | null | undefined,
100
- ): TypedTreeEntry<TMap, N> | null;
101
- /**
102
- * Merge typed meta into a document's metadata. Throws
103
- * `TypedDocTypeMismatchError` when the stored entry's `type` doesn't
104
- * match `expectedType`; throws `MetaValidationError` when a validator
105
- * is attached and the merged meta fails validation.
106
- */
107
- update<N extends keyof TMap & string>(
108
- expectedType: N,
109
- id: string,
110
- meta: Partial<TMap[N]>,
111
- ): void;
112
- /**
113
- * Replace all metadata on a document with a fully-typed payload.
114
- * Same throw semantics as `update`.
115
- */
116
- set<N extends keyof TMap & string>(
117
- expectedType: N,
118
- id: string,
119
- meta: TMap[N],
120
- ): void;
121
- /**
122
- * Delete specific metadata keys. Constrained to the typed key-set of
123
- * `TMap[N]` so typos surface at compile time.
124
- */
125
- clear<N extends keyof TMap & string>(
126
- expectedType: N,
127
- id: string,
128
- keys: ReadonlyArray<keyof TMap[N] & string>,
129
- ): void;
130
- }
131
-
132
- /**
133
- * Thrown by typed write methods on `TypedDocsClient` when the stored
134
- * entry's `type` doesn't match the caller's `expectedType`. Distinct from
135
- * `MetaValidationError` (which signals schema-content mismatches).
136
- */
137
- export class TypedDocTypeMismatchError extends Error {
138
- readonly docId: string;
139
- readonly expectedType: string;
140
- readonly actualType: string | undefined;
141
- constructor(docId: string, expectedType: string, actualType: string | undefined) {
142
- super(
143
- `Typed write on document ${docId} expected type "${expectedType}" but stored type is ${
144
- actualType === undefined ? "(none)" : `"${actualType}"`
145
- }`,
146
- );
147
- this.name = "TypedDocTypeMismatchError";
148
- this.docId = docId;
149
- this.expectedType = expectedType;
150
- this.actualType = actualType;
151
- }
152
- }
153
-
154
- // ── Internal: shared projection helper ──────────────────────────────────────
155
-
156
- /**
157
- * Project a raw `TreeEntry` to a `TypedTreeEntry<TMap, N>` if its `type`
158
- * matches; otherwise return `null`. Used by both `TreeManager.getTyped`
159
- * and `TypedDocsClient.{get,narrow}` to keep semantics consistent.
160
- */
161
- export function projectTreeEntry<
162
- TMap extends Record<string, unknown>,
163
- N extends keyof TMap & string,
164
- >(entry: TreeEntry | null | undefined, expectedType: N):
165
- TypedTreeEntry<TMap, N> | null
166
- {
167
- if (!entry) return null;
168
- if (entry.type !== expectedType) return null;
169
- return {
170
- id: entry.id,
171
- type: expectedType,
172
- label: entry.label,
173
- parentId: entry.parentId,
174
- order: entry.order,
175
- meta: entry.meta as (TMap[N] & PageMeta) | undefined,
176
- createdAt: entry.createdAt,
177
- updatedAt: entry.updatedAt,
178
- };
179
- }
@@ -1,250 +0,0 @@
1
- /**
2
- * IndexedDB-backed trigram full-text search index.
3
- *
4
- * Generic: caller passes (docId, texts[]) — works for Y.Doc text content,
5
- * file names, document titles, or any other text. No Y.js coupling.
6
- *
7
- * Algorithm: trigram inverted index.
8
- * - Each document is decomposed into overlapping 3-character windows.
9
- * - The "postings" store maps trigram → [docId, ...].
10
- * - The "doc_trigrams" store maps docId → [trigram, ...] for efficient removal.
11
- * - search() scores by number of query trigrams that match.
12
- *
13
- * IDB transactions that touch multiple stores use the callback-only pattern
14
- * (not async/await inside a transaction) to avoid the transaction auto-commit
15
- * issue across microtask boundaries.
16
- */
17
-
18
- import type { SearchResult } from "./types.ts";
19
-
20
- const DB_VERSION = 1;
21
-
22
- function idbAvailable(): boolean {
23
- return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
24
- }
25
-
26
- function openDb(origin: string): Promise<IDBDatabase> {
27
- return new Promise((resolve, reject) => {
28
- const req = globalThis.indexedDB.open(`abracadabra:search:${origin}`, DB_VERSION);
29
-
30
- req.onupgradeneeded = (event) => {
31
- const db = (event.target as IDBOpenDBRequest).result;
32
- if (!db.objectStoreNames.contains("postings")) {
33
- db.createObjectStore("postings");
34
- }
35
- if (!db.objectStoreNames.contains("doc_trigrams")) {
36
- db.createObjectStore("doc_trigrams");
37
- }
38
- };
39
-
40
- req.onsuccess = () => resolve(req.result);
41
- req.onerror = () => reject(req.error);
42
- });
43
- }
44
-
45
- /** Extract the set of trigrams for a piece of text. */
46
- function extractTrigrams(text: string): Set<string> {
47
- const trigrams = new Set<string>();
48
- const padded = ` ${text.toLowerCase()} `;
49
- for (let i = 0; i <= padded.length - 3; i++) {
50
- trigrams.add(padded.slice(i, i + 3));
51
- }
52
- return trigrams;
53
- }
54
-
55
- /** Merge trigrams from multiple texts into a single set. */
56
- function extractAllTrigrams(texts: string[]): Set<string> {
57
- const result = new Set<string>();
58
- for (const t of texts) {
59
- for (const trigram of extractTrigrams(t)) {
60
- result.add(trigram);
61
- }
62
- }
63
- return result;
64
- }
65
-
66
- export class SearchIndex {
67
- private readonly origin: string;
68
- private dbPromise: Promise<IDBDatabase | null> | null = null;
69
- private db: IDBDatabase | null = null;
70
-
71
- constructor(serverOrigin: string) {
72
- this.origin = serverOrigin;
73
- }
74
-
75
- private getDb(): Promise<IDBDatabase | null> {
76
- if (!idbAvailable()) return Promise.resolve(null);
77
- if (!this.dbPromise) {
78
- this.dbPromise = openDb(this.origin)
79
- .catch(() => null)
80
- .then((db) => {
81
- this.db = db;
82
- return db;
83
- });
84
- }
85
- return this.dbPromise;
86
- }
87
-
88
- /**
89
- * Replace the index for docId with the given texts.
90
- * Old trigram associations are removed before new ones are added.
91
- */
92
- async index(docId: string, texts: string[]): Promise<void> {
93
- const db = await this.getDb();
94
- if (!db) return;
95
-
96
- const newTrigrams = extractAllTrigrams(texts);
97
-
98
- return new Promise<void>((resolve, reject) => {
99
- const tx = db.transaction(["postings", "doc_trigrams"], "readwrite");
100
- tx.oncomplete = () => resolve();
101
- tx.onerror = () => reject(tx.error);
102
-
103
- const postings = tx.objectStore("postings");
104
- const docTrigramsStore = tx.objectStore("doc_trigrams");
105
-
106
- // Step 1: read old trigrams for this doc
107
- const oldReq = docTrigramsStore.get(docId);
108
- oldReq.onsuccess = () => {
109
- const oldTrigrams: string[] = oldReq.result ?? [];
110
- let pending = oldTrigrams.length + newTrigrams.size + 1; // +1 for doc_trigrams write
111
-
112
- function done() {
113
- pending--;
114
- // tx.oncomplete fires naturally once all requests settle
115
- }
116
-
117
- // Step 2: remove docId from each old trigram's posting list
118
- for (const trigram of oldTrigrams) {
119
- const req = postings.get(trigram);
120
- req.onsuccess = () => {
121
- const list: string[] = req.result ?? [];
122
- const updated = list.filter((id) => id !== docId);
123
- if (updated.length === 0) {
124
- postings.delete(trigram);
125
- } else {
126
- postings.put(updated, trigram);
127
- }
128
- done();
129
- };
130
- req.onerror = done;
131
- }
132
-
133
- // Step 3: add docId to each new trigram's posting list
134
- for (const trigram of newTrigrams) {
135
- const req = postings.get(trigram);
136
- req.onsuccess = () => {
137
- const list: string[] = req.result ?? [];
138
- if (!list.includes(docId)) {
139
- list.push(docId);
140
- }
141
- postings.put(list, trigram);
142
- done();
143
- };
144
- req.onerror = done;
145
- }
146
-
147
- // Step 4: save new trigram set for this doc
148
- const writeReq = docTrigramsStore.put([...newTrigrams], docId);
149
- writeReq.onsuccess = done;
150
- writeReq.onerror = done;
151
- };
152
- oldReq.onerror = () => reject(oldReq.error);
153
- });
154
- }
155
-
156
- /** Remove all indexed content for a document. */
157
- async remove(docId: string): Promise<void> {
158
- const db = await this.getDb();
159
- if (!db) return;
160
-
161
- return new Promise<void>((resolve, reject) => {
162
- const tx = db.transaction(["postings", "doc_trigrams"], "readwrite");
163
- tx.oncomplete = () => resolve();
164
- tx.onerror = () => reject(tx.error);
165
-
166
- const postings = tx.objectStore("postings");
167
- const docTrigramsStore = tx.objectStore("doc_trigrams");
168
-
169
- const oldReq = docTrigramsStore.get(docId);
170
- oldReq.onsuccess = () => {
171
- const oldTrigrams: string[] = oldReq.result ?? [];
172
-
173
- for (const trigram of oldTrigrams) {
174
- const req = postings.get(trigram);
175
- req.onsuccess = () => {
176
- const list: string[] = req.result ?? [];
177
- const updated = list.filter((id) => id !== docId);
178
- if (updated.length === 0) {
179
- postings.delete(trigram);
180
- } else {
181
- postings.put(updated, trigram);
182
- }
183
- };
184
- }
185
-
186
- docTrigramsStore.delete(docId);
187
- };
188
- oldReq.onerror = () => reject(oldReq.error);
189
- });
190
- }
191
-
192
- /**
193
- * Search for documents matching the query.
194
- * Returns results sorted by score (matching trigram count) descending.
195
- */
196
- async search(query: string, limit = 20): Promise<SearchResult[]> {
197
- const db = await this.getDb();
198
- if (!db) return [];
199
-
200
- const queryTrigrams = [...extractTrigrams(query)];
201
- if (queryTrigrams.length === 0) return [];
202
-
203
- const maxScoreEntries = limit * 10;
204
-
205
- return new Promise<SearchResult[]>((resolve, reject) => {
206
- const tx = db.transaction("postings", "readonly");
207
- const postings = tx.objectStore("postings");
208
- const scores = new Map<string, number>();
209
- let remaining = queryTrigrams.length;
210
-
211
- for (const trigram of queryTrigrams) {
212
- const req = postings.get(trigram);
213
- req.onsuccess = () => {
214
- const docIds: string[] = req.result ?? [];
215
- for (const docId of docIds) {
216
- scores.set(docId, (scores.get(docId) ?? 0) + 1);
217
- if (scores.size >= maxScoreEntries) break;
218
- }
219
- remaining--;
220
- if (remaining === 0) {
221
- const results: SearchResult[] = [...scores.entries()]
222
- .map(([docId, score]) => ({ docId, score }))
223
- .sort((a, b) => b.score - a.score)
224
- .slice(0, limit);
225
- resolve(results);
226
- }
227
- };
228
- req.onerror = () => {
229
- remaining--;
230
- if (remaining === 0) {
231
- const results: SearchResult[] = [...scores.entries()]
232
- .map(([docId, score]) => ({ docId, score }))
233
- .sort((a, b) => b.score - a.score)
234
- .slice(0, limit);
235
- resolve(results);
236
- }
237
- };
238
- }
239
-
240
- tx.onerror = () => reject(tx.error);
241
- });
242
- }
243
-
244
- // ── Lifecycle ─────────────────────────────────────────────────────────────
245
-
246
- destroy(): void {
247
- this.db?.close();
248
- this.db = null;
249
- }
250
- }
@@ -1,220 +0,0 @@
1
- /**
2
- * ServerRegistry — a tiny on-disk registry of Abracadabra servers shared by the
3
- * Node-side consumers (`@abraca/mcp`, `@abraca/cli`).
4
- *
5
- * Historically each daemon read a single `ABRA_URL` and a single key file, so it
6
- * could only ever talk to one server. The registry lets a user remember several
7
- * servers by alias, keep a per-server identity (key file), and switch between
8
- * them — both from the CLI (`server add/use/login`) and from a running MCP agent
9
- * (`connect_server`/`switch_server`).
10
- *
11
- * Format: JSON at `~/.abracadabra/servers.json` (override with `ABRA_SERVERS_FILE`):
12
- *
13
- * {
14
- * "defaultAlias": "coop",
15
- * "servers": {
16
- * "coop": { "alias": "coop", "url": "https://coop.cou.sh",
17
- * "keyFile": "/home/me/.abracadabra/keys/coop.key" }
18
- * }
19
- * }
20
- *
21
- * Node-only: filesystem access is via dynamic `import("node:…")`, so importing
22
- * this module from a browser bundle is safe — only *calling* the load/save
23
- * helpers requires Node.
24
- */
25
-
26
- // ── Types ──────────────────────────────────────────────────────────────────
27
-
28
- /** A single remembered server. */
29
- export interface ServerProfile {
30
- /** Short, unique handle used on the CLI / in MCP tools. */
31
- alias: string;
32
- /** Base URL, e.g. `https://coop.cou.sh`. */
33
- url: string;
34
- /** Path to this server's Ed25519 key file (per-server identity). */
35
- keyFile: string;
36
- /** Display name presented to the server (presence / registration). */
37
- displayName?: string;
38
- /** Presence color (HSL string). */
39
- color?: string;
40
- /** Invite/registration token, when the server is invite-only. */
41
- inviteCode?: string;
42
- }
43
-
44
- /** The whole registry: a map of profiles plus which alias is the default. */
45
- export interface ServerRegistry {
46
- /** Alias used when no `--server` / `connect_server` target is given. */
47
- defaultAlias?: string;
48
- servers: Record<string, ServerProfile>;
49
- }
50
-
51
- // ── Paths ──────────────────────────────────────────────────────────────────
52
-
53
- /** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */
54
- export async function serverRegistryPath(override?: string): Promise<string> {
55
- const { homedir } = await import("node:os");
56
- const { join } = await import("node:path");
57
- return (
58
- override ??
59
- process.env.ABRA_SERVERS_FILE ??
60
- join(homedir(), ".abracadabra", "servers.json")
61
- );
62
- }
63
-
64
- /** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */
65
- export async function defaultKeyFileFor(alias: string): Promise<string> {
66
- const { homedir } = await import("node:os");
67
- const { join } = await import("node:path");
68
- const safe = alias.replace(/[^a-zA-Z0-9._-]/g, "_");
69
- return join(homedir(), ".abracadabra", "keys", `${safe}.key`);
70
- }
71
-
72
- // ── Load / save ────────────────────────────────────────────────────────────
73
-
74
- /**
75
- * Load the registry from disk. A missing file yields an empty registry (never
76
- * throws on absence). A malformed file throws so the caller can surface it.
77
- */
78
- export async function loadServerRegistry(
79
- path?: string,
80
- ): Promise<ServerRegistry> {
81
- const { existsSync } = await import("node:fs");
82
- const { readFile } = await import("node:fs/promises");
83
- const file = await serverRegistryPath(path);
84
-
85
- if (!existsSync(file)) return { servers: {} };
86
-
87
- const raw = await readFile(file, "utf8");
88
- if (!raw.trim()) return { servers: {} };
89
- let parsed: unknown;
90
- try {
91
- parsed = JSON.parse(raw);
92
- } catch (err) {
93
- throw new Error(
94
- `Malformed server registry at ${file}: ${(err as Error).message}`,
95
- );
96
- }
97
- const reg = parsed as Partial<ServerRegistry>;
98
- return {
99
- defaultAlias: reg.defaultAlias,
100
- servers: reg.servers ?? {},
101
- };
102
- }
103
-
104
- /** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */
105
- export async function saveServerRegistry(
106
- reg: ServerRegistry,
107
- path?: string,
108
- ): Promise<void> {
109
- const { existsSync } = await import("node:fs");
110
- const { writeFile, mkdir } = await import("node:fs/promises");
111
- const { dirname } = await import("node:path");
112
- const file = await serverRegistryPath(path);
113
- const dir = dirname(file);
114
- if (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });
115
- await writeFile(file, `${JSON.stringify(reg, null, 2)}\n`, { mode: 0o600 });
116
- }
117
-
118
- // ── Resolution ─────────────────────────────────────────────────────────────
119
-
120
- /**
121
- * Resolve `aliasOrUrl` against the registry.
122
- *
123
- * - A known alias → its stored profile.
124
- * - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with
125
- * a derived alias (the URL host) and a default per-host key file. This is NOT
126
- * persisted; the caller decides whether to `addServer` it.
127
- * - Anything else → `null` (unknown alias).
128
- */
129
- export async function resolveServer(
130
- reg: ServerRegistry,
131
- aliasOrUrl: string,
132
- ): Promise<ServerProfile | null> {
133
- const direct = reg.servers[aliasOrUrl];
134
- if (direct) return direct;
135
-
136
- if (/^https?:\/\//i.test(aliasOrUrl)) {
137
- let alias = aliasOrUrl;
138
- try {
139
- alias = new URL(aliasOrUrl).host || aliasOrUrl;
140
- } catch {
141
- /* keep the raw string as the alias */
142
- }
143
- return {
144
- alias,
145
- url: aliasOrUrl.replace(/\/+$/, ""),
146
- keyFile: await defaultKeyFileFor(alias),
147
- };
148
- }
149
-
150
- return null;
151
- }
152
-
153
- // ── Mutators (return a new registry; caller persists) ────────────────────────
154
-
155
- /** Add or replace a profile. The first server added becomes the default. */
156
- export function addServer(
157
- reg: ServerRegistry,
158
- profile: ServerProfile,
159
- ): ServerRegistry {
160
- const servers = { ...reg.servers, [profile.alias]: profile };
161
- const defaultAlias =
162
- reg.defaultAlias && reg.servers[reg.defaultAlias]
163
- ? reg.defaultAlias
164
- : profile.alias;
165
- return { defaultAlias, servers };
166
- }
167
-
168
- /** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */
169
- export function removeServer(
170
- reg: ServerRegistry,
171
- alias: string,
172
- ): ServerRegistry {
173
- if (!reg.servers[alias]) return reg;
174
- const servers = { ...reg.servers };
175
- delete servers[alias];
176
- let defaultAlias = reg.defaultAlias;
177
- if (defaultAlias === alias) {
178
- defaultAlias = Object.keys(servers)[0];
179
- }
180
- return { defaultAlias, servers };
181
- }
182
-
183
- /** Mark `alias` as the default. Throws if the alias is unknown. */
184
- export function setDefault(reg: ServerRegistry, alias: string): ServerRegistry {
185
- if (!reg.servers[alias]) {
186
- throw new Error(`Unknown server alias: ${alias}`);
187
- }
188
- return { ...reg, defaultAlias: alias };
189
- }
190
-
191
- // ── Migration ────────────────────────────────────────────────────────────────
192
-
193
- /**
194
- * Seed a `default` profile from a legacy single-key setup when the registry is
195
- * empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an
196
- * `ABRA_URL`; without this they'd lose their identity the first time the
197
- * registry takes over. Returns the (possibly unchanged) registry; the caller
198
- * persists if `migrated` is true.
199
- *
200
- * @param url the legacy `ABRA_URL` (no migration without it).
201
- * @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).
202
- */
203
- export async function migrateLegacyDefault(
204
- reg: ServerRegistry,
205
- url: string | undefined,
206
- legacyKeyFile: string,
207
- ): Promise<{ registry: ServerRegistry; migrated: boolean }> {
208
- if (!url || Object.keys(reg.servers).length > 0) {
209
- return { registry: reg, migrated: false };
210
- }
211
- const { existsSync } = await import("node:fs");
212
- if (!existsSync(legacyKeyFile)) return { registry: reg, migrated: false };
213
-
214
- const profile: ServerProfile = {
215
- alias: "default",
216
- url: url.replace(/\/+$/, ""),
217
- keyFile: legacyKeyFile,
218
- };
219
- return { registry: addServer(reg, profile), migrated: true };
220
- }