@thedriveai/device-helper 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.d.ts ADDED
@@ -0,0 +1,800 @@
1
+ interface CatalogItem {
2
+ externalId: string;
3
+ /** The platform's id of the parent; null when the platform reports none (shared with me). */
4
+ parentExternalId: string | null;
5
+ name: string;
6
+ kind: "file" | "folder";
7
+ mimeType: string;
8
+ size: number | null;
9
+ mtime: string | null;
10
+ ctime: string | null;
11
+ /** Algo-prefixed (contentIdentity.contentHashKey); null when the provider reports none. */
12
+ contentHash: string | null;
13
+ ownerEmail: string | null;
14
+ webUrl: string | null;
15
+ trashed: boolean;
16
+ /** Trashed by itself rather than by a folder above it; absent = same as `trashed`. */
17
+ explicitlyTrashed?: boolean;
18
+ /**
19
+ * The bytes are not where the item is (a cloud placeholder on a device: iCloud, Dropbox, OneDrive online-only).
20
+ * Reading it downloads it; the index, the hash backfill and every background read leave it alone
21
+ * (docs/agent/DEVICE_MOUNTS.md §11). Absent = present.
22
+ */
23
+ onlineOnly?: boolean;
24
+ /**
25
+ * An image's embedded facts as the PLATFORM reports them (Google Drive's imageMediaMetadata). Present = the
26
+ * platform answered for this file (every field may still be null: a photo without EXIF); absent = not asked,
27
+ * so the catalog keeps what it had.
28
+ */
29
+ media?: CatalogMedia;
30
+ }
31
+ interface CatalogMedia {
32
+ takenAt: string | null;
33
+ gpsLat: number | null;
34
+ gpsLng: number | null;
35
+ cameraMake: string | null;
36
+ cameraModel: string | null;
37
+ width: number | null;
38
+ height: number | null;
39
+ }
40
+ interface CatalogChange {
41
+ externalId: string;
42
+ /**
43
+ * The item stood at this address before (a device's journal pairs a rename or a move into ONE entry). The
44
+ * catalogue rewrites the node's address instead of deleting one row and inserting another, so the node keeps its
45
+ * id, its text, and every dataset and grant that names it. Absent on every platform with minted ids.
46
+ */
47
+ movedFrom?: string;
48
+ /** No longer listed by the platform: deleted, trashed on a platform that does not list its trash, or out of view. */
49
+ removed: boolean;
50
+ /**
51
+ * The platform cannot say whether a removal is permanent or a trip to its recycle bin (Graph's `deleted`
52
+ * facet is the same for both): the item MAY come back. The catalog keeps a tombstone instead of dropping the
53
+ * row, so a restore finds the same node id — the one the journal, grants and datasets hold. A removal
54
+ * without it (Google's `removed`: gone for good, since Drive lists its trash) drops the row.
55
+ */
56
+ recoverable?: boolean;
57
+ /**
58
+ * The platform SAW this path appear (a device's journal knows a new file from a rewritten one; a cloud feed
59
+ * does not say). A workflow trigger takes it as the verdict; absent, created-vs-updated is decided from the
60
+ * file's creation time against the watch's currency, as for every cloud platform.
61
+ */
62
+ created?: boolean;
63
+ item: CatalogItem | null;
64
+ }
65
+ /**
66
+ * 2 (2026-10-12): a move or rename is ONE journal entry naming where the item was (CatalogChange.movedFrom); a
67
+ * version-1 helper sends a removal and an upsert, which the server still takes. Photo facts may be `'unknown'`.
68
+ */
69
+ export declare const DEVICE_PROTOCOL_VERSION = 2;
70
+ /** The socket.io namespace devices connect to. */
71
+ export declare const DEVICE_NAMESPACE = "/devices";
72
+ export type DevicePlatform = "darwin" | "linux" | "win32" | "docker";
73
+ /** A folder the helper shares, as it announces it. The id is minted by the helper and survives a path change. */
74
+ export interface DeviceRoot {
75
+ id: string;
76
+ label: string;
77
+ /** Whether a delete here goes to a trash the person can recover from (Finder, the Recycle Bin, a --trash-dir). */
78
+ trash: boolean;
79
+ /** The helper refuses every write to this root. */
80
+ readOnly: boolean;
81
+ /**
82
+ * What the index may read of it (DEVICE_MOUNTS.md §10): `names` = nothing, the agent organises by name, date and
83
+ * photo facts; `documents` = their text, as for any drive. Absent = leave the source's current choice alone.
84
+ */
85
+ content?: "names" | "documents";
86
+ /**
87
+ * Share with the whole workspace (a NAS): honoured when the root is first catalogued and the pairing person is an
88
+ * admin; a choice made later in Settings is never overridden by a hello. Absent = personal.
89
+ */
90
+ shared?: boolean;
91
+ /**
92
+ * Whether the root can be read right now (DEVICE_MOUNTS.md §11): `denied` = the OS has not allowed the helper to
93
+ * read it (macOS privacy); `missing` = the path is not there (a disk unplugged, a volume asleep). Absent = ok.
94
+ * The source is paused with the reason while the state lasts; nothing is ever catalogued as empty.
95
+ */
96
+ state?: "ok" | "denied" | "missing";
97
+ /** The cloud drive this folder is the local copy of (Dropbox, OneDrive, Google Drive, iCloud, Box), when it is one. */
98
+ syncOf?: "dropbox" | "onedrive" | "google_drive" | "icloud" | "box";
99
+ }
100
+ export interface DeviceHello {
101
+ protocol: number;
102
+ device: {
103
+ id: string;
104
+ name: string;
105
+ platform: DevicePlatform;
106
+ helperVersion: string;
107
+ };
108
+ roots: DeviceRoot[];
109
+ /**
110
+ * Roots the person STOPPED SHARING (DEVICE_MOUNTS.md §17): the server retires their sources outright, where a
111
+ * root merely absent from `roots` is only paused (a reconfiguration, a released transient). The helper repeats
112
+ * them until a hello carrying them is acknowledged.
113
+ */
114
+ retired?: string[];
115
+ }
116
+ interface DeviceHelloAck {
117
+ ok: boolean;
118
+ /** The connection id the device is known by, for its logs. */
119
+ connectionId?: string;
120
+ /**
121
+ * Roots the server will not take back (DEVICE_MOUNTS.md §17): they were retired (stopped from Settings while the
122
+ * device was away, or retired before and announced again). A root id is minted once per share and never reused, so a
123
+ * retired id is dead; the helper stops sharing these.
124
+ */
125
+ retire?: string[];
126
+ error?: string;
127
+ }
128
+ type RpcErrorCode = "NOT_FOUND" | "EXISTS" | "PERMISSION_DENIED" | "READ_ONLY" | "NO_TRASH" | "TOO_LARGE" | "BAD_PATH" | "UNSUPPORTED" | "RESET"
129
+ /** The root cannot be read right now (missing, denied): the server treats it as an offline device. */
130
+ | "UNAVAILABLE"
131
+ /** The file's bytes are not on the disk (a cloud placeholder) and the read did not allow fetching them. */
132
+ | "ONLINE_ONLY" | "INTERNAL";
133
+ interface RpcError {
134
+ code: RpcErrorCode;
135
+ message: string;
136
+ }
137
+ type RpcResult<T> = {
138
+ ok: true;
139
+ result: T;
140
+ } | {
141
+ ok: false;
142
+ error: RpcError;
143
+ };
144
+ interface RpcRequest<M extends RpcMethod = RpcMethod> {
145
+ id: string;
146
+ method: M;
147
+ params: RpcParams[M];
148
+ }
149
+ type DeviceItem = CatalogItem;
150
+ interface DeviceChanged {
151
+ root: string;
152
+ cursor: string;
153
+ }
154
+ interface RpcParams {
155
+ enumerate: {
156
+ root: string;
157
+ cursor: string | null;
158
+ limit: number;
159
+ };
160
+ changes: {
161
+ root: string;
162
+ cursor: string;
163
+ limit: number;
164
+ };
165
+ stat: {
166
+ root: string;
167
+ path: string;
168
+ };
169
+ list: {
170
+ root: string;
171
+ path: string;
172
+ cursor: string | null;
173
+ limit: number;
174
+ };
175
+ /** `allowFetch`: an online-only placeholder may be downloaded by the OS to answer (a person's own read of that file). */
176
+ /** `stream`: the id the server is already listening on for this read's chunks (older helpers pick their own and answer it). */
177
+ read: {
178
+ root: string;
179
+ path: string;
180
+ maxBytes?: number;
181
+ allowFetch?: boolean;
182
+ stream?: string;
183
+ };
184
+ write: {
185
+ root: string;
186
+ path: string;
187
+ data: Buffer;
188
+ mode: "create" | "replace";
189
+ };
190
+ /**
191
+ * A streamed write, the mirror of `read` (DEVICE_MOUNTS.md §4): the server opens it naming the stream it will
192
+ * send on, sends `write_chunk`s each acknowledged by the helper, then closes it; the file appears at `path` only
193
+ * at the close (written beside, renamed over). `size` is what the server expects to send when it knows.
194
+ */
195
+ write_open: {
196
+ root: string;
197
+ path: string;
198
+ mode: "create" | "replace";
199
+ size: number | null;
200
+ stream: string;
201
+ };
202
+ /** `bytes`: what the server sent; the helper refuses a close that does not match what it wrote. */
203
+ write_close: {
204
+ root: string;
205
+ path: string;
206
+ stream: string;
207
+ bytes?: number;
208
+ };
209
+ mkdir: {
210
+ root: string;
211
+ path: string;
212
+ };
213
+ /** `to` is the full new path: a rename changes the last segment, a move the folder, one call does either. */
214
+ move: {
215
+ root: string;
216
+ from: string;
217
+ to: string;
218
+ };
219
+ copy: {
220
+ root: string;
221
+ from: string;
222
+ to: string;
223
+ };
224
+ trash: {
225
+ root: string;
226
+ path: string;
227
+ };
228
+ /** SHA-256 of each file's bytes, computed on the device (a file over `maxBytes` is skipped). */
229
+ hash: {
230
+ root: string;
231
+ paths: string[];
232
+ maxBytes?: number;
233
+ };
234
+ /** Photo facts (EXIF: when, where, camera, pixels) read on the device for these files; nothing but the facts travels. */
235
+ media: {
236
+ root: string;
237
+ paths: string[];
238
+ };
239
+ }
240
+ interface RpcResults {
241
+ /** `unreadable`: folders on this page whose contents could not be read (unknown, not empty). */
242
+ enumerate: {
243
+ items: DeviceItem[];
244
+ cursor: string | null;
245
+ done: boolean;
246
+ unreadable?: string[];
247
+ };
248
+ changes: {
249
+ changes: CatalogChange[];
250
+ cursor: string;
251
+ done: boolean;
252
+ resetRequired?: boolean;
253
+ };
254
+ stat: DeviceItem | null;
255
+ list: {
256
+ items: DeviceItem[];
257
+ cursor: string | null;
258
+ };
259
+ /** The stream the chunks will arrive on, and what they are. */
260
+ read: {
261
+ stream: string;
262
+ size: number | null;
263
+ mimeType: string;
264
+ };
265
+ write: DeviceItem;
266
+ write_open: {
267
+ stream: string;
268
+ };
269
+ write_close: DeviceItem;
270
+ mkdir: DeviceItem;
271
+ move: DeviceItem;
272
+ copy: DeviceItem;
273
+ trash: {
274
+ ok: true;
275
+ };
276
+ /** path → hex SHA-256; null when the file is gone, unreadable or over the limit. */
277
+ hash: {
278
+ hashes: Record<string, string | null>;
279
+ };
280
+ /**
281
+ * path → facts; null when the device has none for it (not a photo, no EXIF, a format it cannot read): an answer, so
282
+ * it is never asked again; `'unknown'` when the device could not find out this time (its tool failed, the file was
283
+ * gone): no answer, the server records nothing and asks again later.
284
+ */
285
+ media: {
286
+ media: Record<string, CatalogMedia | null | "unknown">;
287
+ };
288
+ }
289
+ type RpcMethod = keyof RpcParams;
290
+ interface StreamChunk {
291
+ stream: string;
292
+ seq: number;
293
+ data: Buffer;
294
+ last: boolean;
295
+ }
296
+ interface StreamAbort {
297
+ stream: string;
298
+ reason: string;
299
+ }
300
+ declare function deviceJoin(folder: string, name: string): string;
301
+ export interface RootConfig {
302
+ id: string;
303
+ label: string;
304
+ path: string;
305
+ /**
306
+ * Where a delete goes: the OS trash, a folder of your choosing, the share's own NAS recycle bin (Synology's
307
+ * `#recycle`, QNAP's `@Recycle`: nasFolders.ts), or nowhere (the agent will not delete).
308
+ */
309
+ trash: "os" | "dir" | "share" | "none";
310
+ trashDir?: string;
311
+ readOnly: boolean;
312
+ /** What the index may read: 'names' = nothing (names, dates, photo facts only); 'documents' = their text. Default documents. */
313
+ content: "names" | "documents";
314
+ /** Share with the whole workspace (a NAS): honoured when the folder is first catalogued and the pairer is an admin. */
315
+ shared: boolean;
316
+ /** Shared for one task (the desktop's "ask about this folder"): the host stops sharing it at quit unless kept. */
317
+ transient: boolean;
318
+ }
319
+ export interface DeviceConfig {
320
+ deviceId: string;
321
+ name: string;
322
+ server: string;
323
+ connectionId: string | null;
324
+ /** The workspace the device is paired into: one per device. */
325
+ workspaceId: string | null;
326
+ token: string | null;
327
+ roots: RootConfig[];
328
+ /** Roots the person stopped sharing, told to the server on the next hello and forgotten once it is acknowledged (§17). */
329
+ retired?: string[];
330
+ }
331
+ export declare function deviceHome(): string;
332
+ export declare function stateDir(rootId: string, home?: string): string;
333
+ export declare function devicePlatform(): DevicePlatform;
334
+ export declare function defaultDeviceName(): string;
335
+ export declare function loadConfig(home?: string): DeviceConfig;
336
+ /** Written atomically (rename over), mode 0600: the file holds the device token. */
337
+ export declare function saveConfig(config: DeviceConfig, home?: string): void;
338
+ /** A root id: short, URL-safe, unique in this config; the server keys the source by it, so it never changes once made. */
339
+ export declare function newRootId(existing: RootConfig[]): string;
340
+ interface ChangesPage {
341
+ changes: CatalogChange[];
342
+ cursor: string;
343
+ done: boolean;
344
+ resetRequired?: boolean;
345
+ }
346
+ declare class Journal {
347
+ private readonly dir;
348
+ private readonly keep;
349
+ private epoch;
350
+ /** The last seq handed to an entry, on disk or not. */
351
+ private seq;
352
+ /** The last seq that is on disk: everything the journal serves stops here. */
353
+ private durable;
354
+ private entries;
355
+ private readonly file;
356
+ /** Lines recorded and not yet written. */
357
+ private unwritten;
358
+ /** The next write replaces the file with the kept tail (compaction) instead of appending. */
359
+ private rewrite;
360
+ private writing;
361
+ /** Told after entries land on disk (the host nudges the server, debounced; DEVICE_MOUNTS.md §14). */
362
+ onRecord: (() => void) | null;
363
+ constructor(dir: string, keep?: number);
364
+ /** Replay the file; a missing or unreadable one starts a new epoch. */
365
+ load(): void;
366
+ /** The last durable position: what the server may hold as a cursor. */
367
+ get position(): string;
368
+ /** How many entries the journal keeps: a change set larger than this cannot be replayed and is better re-enumerated. */
369
+ get keepCount(): number;
370
+ /**
371
+ * Start a new epoch: every cursor the server holds is of the old one and answers `resetRequired`, so it
372
+ * re-enumerates. The designed answer to a change set the journal could not carry (a restore, a mass touch).
373
+ */
374
+ reset(): void;
375
+ record(change: {
376
+ path: string;
377
+ removed: boolean;
378
+ item: DeviceItem | null;
379
+ created?: boolean;
380
+ movedFrom?: string;
381
+ recoverable?: boolean;
382
+ }): void;
383
+ /** `created`: the path was not in the snapshot before (a new file or folder, not a rewrite). `movedFrom`: it was at that path. */
384
+ upsert(item: DeviceItem, created?: boolean, movedFrom?: string): void;
385
+ /** `recoverable: false`: the path left the share by policy, not for the trash; the server drops its row. */
386
+ remove(devicePath: string, options?: {
387
+ recoverable?: boolean;
388
+ }): void;
389
+ /** Write what is pending, batch after batch, each fsync'd before its entries count. */
390
+ private drain;
391
+ /** Changes after `cursor`, at most `limit` and PAGE_MAX_BYTES of them; '' asks for the current position only. */
392
+ since(cursor: string, limit: number, maxBytes?: number): ChangesPage;
393
+ /** Wait until everything recorded so far is on disk (an op before it answers, a rescan before its snapshot, shutdown). */
394
+ flush(): Promise<void>;
395
+ /** Test seam. */
396
+ get size(): number;
397
+ }
398
+ interface RescanOptions {
399
+ /** Asked before and after the walk: false when the folder at the path is no longer the shared one. */
400
+ stillThere?: () => boolean;
401
+ /** A new file that may still be being written: not reported now, handed back in `held` for the caller to watch settle. */
402
+ hold?: (item: DeviceItem) => boolean;
403
+ /** Every folder the walk lists, as it lists it (a sweep of a crash's temp files goes folder by folder). */
404
+ onFolder?: (abs: string) => void;
405
+ }
406
+ interface RescanResult {
407
+ seen: number;
408
+ added: number;
409
+ changed: number;
410
+ removed: number;
411
+ /** Folders that could not be read: what was known under them is kept. */
412
+ unreadable: string[];
413
+ held: string[];
414
+ /** Dependency folders (a virtualenv by its marker) left out of the walk, with everything under them. */
415
+ skipped: number;
416
+ /** The removals were not reported: too many to be believed without the person's word. */
417
+ refused?: {
418
+ removing: number;
419
+ of: number;
420
+ };
421
+ /** The walk found more changes than the journal keeps: the journal started a new epoch and the server re-enumerates. */
422
+ reset?: {
423
+ changes: number;
424
+ };
425
+ }
426
+ declare class Snapshot {
427
+ private readonly file;
428
+ private readonly acceptFile;
429
+ private entries;
430
+ private loaded;
431
+ /** While a walk runs: paths ops and the watcher set, and paths (with all below) they removed. */
432
+ private touched;
433
+ private running;
434
+ constructor(dir: string);
435
+ /** Whether a snapshot exists: without one the first walk only records, it reports nothing (the server enumerates). */
436
+ load(): boolean;
437
+ get exists(): boolean;
438
+ get count(): number;
439
+ /** A rescan is walking now. */
440
+ get busy(): boolean;
441
+ private static same;
442
+ private static snapOf;
443
+ /** Keep a single change in step with the tree (the watcher and the ops call this). */
444
+ has(devicePath: string): boolean;
445
+ /** What the snapshot knows of a path: kind, size, modified time; undefined when it does not. */
446
+ entry(devicePath: string): {
447
+ kind: "file" | "folder";
448
+ size: number | null;
449
+ mtime: string | null;
450
+ } | undefined;
451
+ /** The names directly under the root, as the snapshot knows them (identity.looksLikeSharedFolder). */
452
+ topLevelNames(): string[];
453
+ /** Whether this item is what the snapshot already knows (same kind; for a file the same size, time and placement). */
454
+ knows(item: DeviceItem): boolean;
455
+ set(item: DeviceItem): void;
456
+ /** The cached hash of a file at this version; undefined when not computed or the file changed since. */
457
+ hashOf(devicePath: string, size: number | null, mtime: string | null): string | undefined;
458
+ setHash(devicePath: string, size: number | null, mtime: string | null, hash: string): void;
459
+ private dirty;
460
+ /** Persist when hashes were added since the last write (cheap to call after a batch). */
461
+ persistIfDirty(): Promise<void>;
462
+ /** Forget a path and everything under it (a folder the watcher saw go, whose children it never named). */
463
+ delete(devicePath: string): void;
464
+ /**
465
+ * Forget one path, nothing under it: for the ops that already name every descendant (a folder move or trash
466
+ * reports each child), so ten thousand children cost ten thousand deletes, not ten thousand scans of the tree.
467
+ */
468
+ deleteOne(devicePath: string): void;
469
+ /** Whether an op or the watcher changed this path (or removed a folder above it) during the current walk. */
470
+ private touchedDuringWalk;
471
+ /** One walk at a time per root: a rescan asked for while one runs gets that one's answer. */
472
+ rescan(rootPath: string, journal: Journal | null, options?: RescanOptions): Promise<RescanResult>;
473
+ /**
474
+ * Walk the tree; when a snapshot existed, journal every difference it can stand behind. Then the snapshot is
475
+ * the walk, plus what could not be read, plus what changed under it while it walked.
476
+ */
477
+ private walk;
478
+ /** The person said a large removal is real (`tdai-device root accept-removals`): honoured once. */
479
+ private takeAcceptance;
480
+ private persisting;
481
+ private persistTimer;
482
+ /**
483
+ * Persist once the changes settle (PERSIST_SOON_MS after the last one): the watcher and the ops keep the snapshot in
484
+ * memory, and a helper restarted before a rescan persisted it diffed the disk against a stale file and journaled
485
+ * every change it had already reported (seen on both a laptop and a NAS as "~2 since last run" after a restart).
486
+ */
487
+ persistSoon(delayMs?: number): void;
488
+ /** A pending persistSoon, written now (a graceful stop). */
489
+ persistNow(): Promise<void>;
490
+ /**
491
+ * Write the snapshot: one writer at a time (a hash batch and a rescan both persist; two writers on one temp file
492
+ * interleave garbage), synced to the disk BEFORE the rename (a power cut on a NAS otherwise keeps the rename and
493
+ * loses the content: an empty file where the tree was), and a disk error is an error, not a hang.
494
+ */
495
+ persist(): Promise<void>;
496
+ private writeOut;
497
+ }
498
+ declare class RootIdentityStore {
499
+ private readonly file;
500
+ private recorded;
501
+ constructor(dir: string);
502
+ private load;
503
+ private save;
504
+ /**
505
+ * `ok` when the folder at the path is the shared one (recorded on first sight, and the record follows a disk
506
+ * that was renumbered); `missing` when nothing is there; `changed` when another folder stands in its place.
507
+ */
508
+ check(rootPath: string): "ok" | "missing" | "changed";
509
+ /**
510
+ * Take the folder now at the path as the root, whatever its numbers. Asked when `check` said `changed` and the
511
+ * folder's CONTENT says otherwise (`looksLikeSharedFolder`), or by the person (`tdai-device root re-adopt`). Device
512
+ * and inode numbers are not a stable identity on every filesystem: cifs mounted `noserverino` makes them up per
513
+ * mount, a volume restored from backup has new ones, exFAT invents them at mount; a root read as `missing` for good
514
+ * for that reason was the review's finding.
515
+ */
516
+ adopt(rootPath: string): boolean;
517
+ /** Forget the record: the next probe records whatever stands at the path. */
518
+ forget(): void;
519
+ }
520
+ type RootState = "ok" | "denied" | "missing";
521
+ interface RootRuntime {
522
+ config: RootConfig;
523
+ journal: Journal;
524
+ snapshot: Snapshot;
525
+ /** Kept by the host (index.ts): every op refuses while the root is not ok. */
526
+ state?: RootState;
527
+ /** Told when an op finds the root gone, so the host can announce it. */
528
+ onStateChange?: (state: RootState) => void;
529
+ /** Which folder the root is (identity.ts); without one, being there is enough. */
530
+ identity?: RootIdentityStore;
531
+ /** Tests: how long a new file must hold still (CREATE_STABLE_MS). */
532
+ createStableMs?: number;
533
+ /** Tests: how long a vanished file waits for its moved twin (MOVE_PAIR_MS). */
534
+ movePairMs?: number;
535
+ }
536
+ export declare class RootOps {
537
+ private readonly root;
538
+ /** New files seen once, waiting to be seen again unchanged before they are reported created. */
539
+ private readonly settling;
540
+ /**
541
+ * Files the watcher saw vanish, held for MOVE_PAIR_MS: a rename or a move inside the root arrives as an unlink and
542
+ * an add, and the add of a file with the vanished one's size and time IS the vanished one, moved. Reported as such;
543
+ * otherwise the removal goes out when the wait ends.
544
+ */
545
+ private readonly departing;
546
+ constructor(root: RootRuntime);
547
+ private get rootPath();
548
+ /** The journal's position, as the nudge to the server carries it. */
549
+ get position(): string;
550
+ /** Whether the snapshot knows this path (the watcher asks before walking a folder's subtree). */
551
+ knows(devicePath: string): boolean;
552
+ /** Whether the folder at the root's path is the one that was shared (not merely a folder of that name). */
553
+ private present;
554
+ /** The root went away (a volume unmounted, another folder in its place): paused, never emptied. */
555
+ private lost;
556
+ /** Every op starts here: a root that is missing or denied answers UNAVAILABLE, never a half answer. */
557
+ private available;
558
+ /** A write answers once what it journaled is on disk. */
559
+ private landed;
560
+ private writable;
561
+ /**
562
+ * `created` when the path was not known before: the snapshot says, so a new file is told apart from a rewrite.
563
+ * `movedFrom`: the item stood there a moment ago (an op's move, a watcher's unlink+add pair, a rescan's match):
564
+ * ONE journal entry, so the server keeps the node — its id, its text, the datasets that name it — instead of
565
+ * burying one and birthing another. A move into another folder still counts as created there (a file LANDED,
566
+ * which is what a "when a file lands in Inbox" trigger means); a rename inside its folder does not.
567
+ */
568
+ private record;
569
+ private forget;
570
+ /** Descendants a folder op already walked: each forgotten on its own, deepest first (no scan of the tree per child). */
571
+ private forgetWalked;
572
+ /**
573
+ * An item as it leaves the helper: a file carries its SHA-256 when the helper has computed it for this very
574
+ * version (the snapshot's cache), as `sha256:<hex>`, the key the server stores. The server compares what the
575
+ * catalogue holds with what the helper reports to decide whether a file changed, so the two must agree.
576
+ */
577
+ private withHash;
578
+ private itemAt;
579
+ stat(params: RpcParams["stat"]): Promise<RpcResults["stat"]>;
580
+ list(params: RpcParams["list"]): Promise<RpcResults["list"]>;
581
+ enumerate(params: RpcParams["enumerate"]): Promise<RpcResults["enumerate"]>;
582
+ changes(params: RpcParams["changes"]): Promise<RpcResults["changes"]>;
583
+ mkdir(params: RpcParams["mkdir"]): Promise<RpcResults["mkdir"]>;
584
+ /** `to` is the full destination path: one call renames or moves, like Dropbox's move_v2. Descendants are reported. */
585
+ move(params: RpcParams["move"]): Promise<RpcResults["move"]>;
586
+ copy(params: RpcParams["copy"]): Promise<RpcResults["copy"]>;
587
+ trash(params: RpcParams["trash"]): Promise<RpcResults["trash"]>;
588
+ write(params: RpcParams["write"]): Promise<RpcResults["write"]>;
589
+ /** Writes in progress, by the stream the server named: a temp file beside the destination, filled chunk by chunk. */
590
+ private readonly writes;
591
+ /** Closes that completed, by stream, for a few minutes: a close re-asked after the helper's memory of the request lapsed answers from here, never from whatever sits at the path. */
592
+ private readonly closed;
593
+ /** Streams open for writing, for the host to abort when the line goes. */
594
+ get openWrites(): string[];
595
+ /** Every write still open is dropped (a graceful stop): its temp file goes with it. */
596
+ abortAllWrites(): Promise<void>;
597
+ /**
598
+ * Open a streamed write (the mirror of openRead): the same checks as `write`, then a temp file beside the
599
+ * destination that the chunks fill. Nothing appears under the name until closeWrite renames it over.
600
+ */
601
+ openWrite(params: RpcParams["write_open"]): Promise<RpcResults["write_open"]>;
602
+ /** One chunk, in order, onto the temp file; true once it is written (the server's permission to send the next). */
603
+ appendWrite(chunk: {
604
+ stream: string;
605
+ seq: number;
606
+ data: Buffer | ArrayBuffer | Uint8Array;
607
+ }): Promise<boolean>;
608
+ /** The write is complete: synced, renamed over the destination, journaled. The item as it now is. */
609
+ closeWrite(params: RpcParams["write_close"]): Promise<RpcResults["write_close"]>;
610
+ /** The server gave up (or the line went): what was written so far is dropped; the destination is untouched. */
611
+ abortWrite(stream: string): Promise<void>;
612
+ /**
613
+ * SHA-256 of each named file, computed here where the bytes are (DEVICE_MOUNTS.md §4): nothing crosses the
614
+ * network but the digests. A cached digest for the same version is answered without reading the file. A file
615
+ * that is gone, unreadable, a folder or over `maxBytes` answers null. At most HASH_BATCH paths per call.
616
+ */
617
+ hash(params: RpcParams["hash"]): Promise<RpcResults["hash"]>;
618
+ /**
619
+ * Photo facts for these files, read here (media.ts): Spotlight on a Mac, the EXIF reader elsewhere. A placeholder
620
+ * is answered without being fetched (Spotlight knows it; the reader does not open it). Every path is answered.
621
+ */
622
+ media(params: RpcParams["media"]): Promise<RpcResults["media"]>;
623
+ /** Open a file for streaming: the stream itself is driven by the client (chunks with acks). */
624
+ openRead(params: RpcParams["read"]): {
625
+ abs: string;
626
+ size: number;
627
+ name: string;
628
+ };
629
+ /**
630
+ * The watcher's report of a path that may have changed: stat it and journal the difference, if there is one.
631
+ * A new file is reported created only when a second look, CREATE_STABLE_MS later, finds the same size and time.
632
+ */
633
+ observe(devicePath: string): Promise<void>;
634
+ private unsettle;
635
+ /** A known file is gone from its path: a folder goes out at once (its children are not paired); a file waits for its twin. */
636
+ private depart;
637
+ /** The departed file this new one is (same size and modified time, and the only such), or null. */
638
+ private departedTwin;
639
+ /**
640
+ * Walk the root against its snapshot and journal what changed (snapshot.ts). The root must be the shared folder
641
+ * before and after; one walk runs at a time; a new file written moments ago settles through `observe` first.
642
+ */
643
+ rescan(): Promise<RescanResult>;
644
+ /** A rescan is walking now (the host does not start another). */
645
+ get rescanning(): boolean;
646
+ /** Stop waiting on new files (the root is closing). What had departed is reported gone: nothing is left unsaid. */
647
+ stop(): void;
648
+ /** For tests and the CLI: the parent and name a path has. */
649
+ static split(devicePath: string): {
650
+ parent: string;
651
+ name: string;
652
+ };
653
+ static join: typeof deviceJoin;
654
+ }
655
+ interface RootWatcherOptions {
656
+ /** The disk moved under the root, as soon as the OS says so: for a view on screen, never for the journal. */
657
+ onSeen?: () => void;
658
+ /** The watcher died (an error event) or gave up: the host rescans and may try again later. */
659
+ onError?: (reason: string) => void;
660
+ /** Tests: force one strategy. */
661
+ strategy?: "recursive" | "perFolder";
662
+ /** Tests: the folder budget. */
663
+ budget?: number;
664
+ }
665
+ declare class RootWatcher {
666
+ private readonly rootPath;
667
+ private readonly ops;
668
+ private readonly log;
669
+ private recursive;
670
+ /** Linux: one watcher per folder, by its device path. */
671
+ private readonly folders;
672
+ private readonly pending;
673
+ private readonly rootReal;
674
+ private queue;
675
+ private stopped;
676
+ private collapsed;
677
+ private readonly options;
678
+ constructor(rootPath: string, ops: RootOps, log: (line: string) => void, onSeenOrOptions?: (() => void) | RootWatcherOptions);
679
+ /** How this platform watches. */
680
+ get strategy(): "recursive" | "perFolder";
681
+ /** Folders under watch (per-folder strategy); 1 for a recursive watch; 0 when not watching. */
682
+ get watchCount(): number;
683
+ /**
684
+ * True when events flow; false when this filesystem gives none, or the tree is past the budget (the rescan is the
685
+ * feed then). Async because the per-folder watcher lists the tree without blocking the socket.
686
+ */
687
+ start(): Promise<boolean>;
688
+ private startRecursive;
689
+ private startPerFolder;
690
+ /** One folder's watch; false when the kernel refuses (ENOSPC: the inotify limit, EMFILE). */
691
+ private watchFolder;
692
+ private unwatchFolder;
693
+ private died;
694
+ private closeAll;
695
+ stop(): void;
696
+ private schedule;
697
+ private observe;
698
+ /** Tests: wait for queued observations. */
699
+ settle(): Promise<void>;
700
+ }
701
+ export declare const HELPER_VERSION = "0.1.4";
702
+ interface LiveRoot {
703
+ announce: DeviceRoot;
704
+ ops: RootOps;
705
+ runtime: RootRuntime & {
706
+ config: RootConfig;
707
+ journal: Journal;
708
+ snapshot: Snapshot;
709
+ };
710
+ watcher: RootWatcher | null;
711
+ /** Whether the root can be read now; the announcement carries it (DEVICE_MOUNTS.md §11). */
712
+ state: RootState;
713
+ /** Why, in the person's words; null when ok. */
714
+ reason: string | null;
715
+ /** Ask the OS again: a drive back, a permission granted. True when the state changed (the caller re-announces). */
716
+ reprobe(): Promise<boolean>;
717
+ }
718
+ /**
719
+ * Bring a root up as far as the OS allows. A root that is denied or missing comes up PAUSED: it is announced with
720
+ * its state so the server pauses its source with the reason, every op on it answers UNAVAILABLE, and `reprobe`
721
+ * finishes the job once it can be read. Nothing is ever walked as empty.
722
+ */
723
+ export declare function bringUpRoot(config: RootConfig, log: (line: string) => void, options?: {
724
+ onStateChange?: (root: LiveRoot) => void; /** The journal moved (an op, the watcher, a rescan): the host nudges the server. */
725
+ onChanged?: (root: LiveRoot) => void; /** The disk moved, as the OS reported it, before any settling: a view on screen reloads; nothing is journaled by it. */
726
+ onSeen?: (root: LiveRoot) => void;
727
+ }): Promise<LiveRoot>;
728
+ export interface ClientSocketLike {
729
+ on(event: "connect", handler: () => void): void;
730
+ on(event: "disconnect", handler: (reason: string) => void): void;
731
+ on(event: "connect_error", handler: (error: Error) => void): void;
732
+ on(event: "rpc", handler: (request: RpcRequest, ack: (reply: RpcResult<unknown>) => void) => void): void;
733
+ on(event: "stream_abort", handler: (abort: StreamAbort) => void): void;
734
+ on(event: "write_chunk", handler: (chunk: StreamChunk, ack: (ok: boolean) => void) => void): void;
735
+ on(event: "superseded", handler: (notice: {
736
+ reason: string;
737
+ }) => void): void;
738
+ emit(event: "hello", hello: DeviceHello, ack: (reply: DeviceHelloAck) => void): void;
739
+ emit(event: "changed", notice: DeviceChanged): void;
740
+ timeout(ms: number): {
741
+ emitWithAck(event: "chunk", chunk: StreamChunk): Promise<boolean>;
742
+ };
743
+ connected: boolean;
744
+ /** socket.io's connect(): used to come back after the server hung up, which socket.io does not retry on its own. */
745
+ connect?(): unknown;
746
+ }
747
+ interface DeviceClientDeps {
748
+ socket: ClientSocketLike;
749
+ device: DeviceHello["device"];
750
+ roots: () => Array<{
751
+ announce: DeviceRoot;
752
+ ops: RootOps;
753
+ }>;
754
+ /** Roots the person stopped sharing, until the server has heard it (§17). */
755
+ retired?: () => string[];
756
+ /** The server acknowledged a hello that carried these: forget them. */
757
+ retiredAcked?: (ids: string[]) => void;
758
+ /** The server will not take these roots back (retired while this device was away): stop sharing them here. */
759
+ retireRequested?: (ids: string[]) => void;
760
+ log: (line: string) => void;
761
+ chunkBytes?: number;
762
+ /** How long to wait before dialling again after the server hung up. */
763
+ reconnectAfterMs?: number;
764
+ /** How long a burst of changes on one root is let settle before the server is nudged. */
765
+ changeDebounceMs?: number;
766
+ }
767
+ export declare class DeviceClient {
768
+ private readonly deps;
769
+ private readonly replies;
770
+ private readonly aborted;
771
+ private readonly open;
772
+ /** Write streams the server has open, by stream, with the root they write into. */
773
+ private readonly writing;
774
+ private readonly pendingNudges;
775
+ /** Another copy of this device connected with the same token: this one stays down rather than fight it. */
776
+ private superseded;
777
+ /** Hellos the server refused in a row (an unsupported protocol, a token of another device): each wait doubles. */
778
+ private refusals;
779
+ constructor(deps: DeviceClientDeps);
780
+ /**
781
+ * A root's journal moved: nudge the server once the burst settles (a save writes a file three times; a
782
+ * download lands a thousand). The nudge carries only the position; the server reads from its own cursor, so
783
+ * one lost while offline costs nothing: the server's catch-up and the next nudge both read the same feed.
784
+ */
785
+ notifyChanged(rootId: string): void;
786
+ start(): void;
787
+ announce(): void;
788
+ private rootOps;
789
+ /**
790
+ * One RPC. A write the server sends again under the same request id (its ack timed out; the first may have
791
+ * finished, or still be running) gets the first one's answer, never a second run on a half-finished op.
792
+ */
793
+ handle(request: RpcRequest): Promise<RpcResult<unknown>>;
794
+ private dispatch;
795
+ private pump;
796
+ private send;
797
+ }
798
+ export declare function rootHasTrash(root: RootConfig): boolean;
799
+
800
+ export {};