@dreamlake/dreamlake-cli 0.89.0 → 0.91.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.
@@ -1,65 +1,107 @@
1
- import { seg } from "./client.js";
1
+ /** Note attachments. JSON receipts match `notes files … --json`; bytes remain streams. */
2
+ import { ApiError, seg } from './client.js';
3
+ export function noteFileOperationId(value) {
4
+ return typeof value === 'string' && /^[a-f0-9]{24}$/i.test(value) ? value : undefined;
5
+ }
6
+ export function validateNoteFileKey(key) {
7
+ if (key !== undefined && (!/^[\x20-\x7e]{1,256}$/.test(key) || key.trim() !== key))
8
+ throw new Error('--idempotency-key must be 1–256 printable ASCII bytes without surrounding spaces');
9
+ }
2
10
  export function noteFilesApi(t, base) {
3
11
  const file = (id) => `${base}/files/${seg(id)}`;
12
+ const list = (query = {}) => {
13
+ const { prefix, trash, ...rest } = query;
14
+ // Compatibility aliases previously sent unsupported server fields.
15
+ const glob = rest.glob ?? (prefix === undefined ? undefined : prefix.replace(/[?*\[\]{}()!+@]/g, '\\$&') + '*');
16
+ return t.request('GET', base + '/files', { query: { ...rest, glob, trashed: rest.trashed ?? trash } });
17
+ };
18
+ const get = (id) => t.request('GET', file(id));
19
+ /** Paths are exact names; scan every page instead of treating page one as the whole directory. */
20
+ const resolve = async (ref, includeTrashed = false) => {
21
+ if (/^[a-f0-9]{24}$/i.test(ref))
22
+ return get(ref);
23
+ for (const trashed of includeTrashed ? [false, true] : [false]) {
24
+ let offset = 0;
25
+ for (;;) {
26
+ const page = await list({ trashed, limit: 100, offset });
27
+ if (!Array.isArray(page.files) || !Number.isSafeInteger(page.total) || page.total < 0)
28
+ throw new Error('Attachment listing is unreadable');
29
+ const hit = page.files.find(row => row.path === ref);
30
+ if (hit)
31
+ return hit;
32
+ offset += page.files.length;
33
+ if (offset >= page.total)
34
+ break;
35
+ if (!page.files.length)
36
+ throw new Error('Attachment listing did not advance');
37
+ }
38
+ }
39
+ throw new ApiError(404, 'note_file_not_found', { path: ref });
40
+ };
41
+ const resolveId = async (ref, includeTrashed = false) => /^[a-f0-9]{24}$/i.test(ref) ? ref : (await resolve(ref, includeTrashed)).id;
42
+ const publish = async (path, json, options) => {
43
+ validateNoteFileKey(options.idempotencyKey);
44
+ let operationId;
45
+ try {
46
+ const result = await t.request('POST', path, { json,
47
+ headers: { ...(options.ifMatch ? { 'If-Match': options.ifMatch } : {}), ...(options.idempotencyKey !== undefined ? { 'Idempotency-Key': options.idempotencyKey } : {}) },
48
+ redirect: 'manual', onHeaders: headers => { operationId = noteFileOperationId(headers.get('Note-File-Operation-Id')); } });
49
+ if (!result || typeof result.id !== 'string' || typeof result.path !== 'string')
50
+ throw new ApiError(503, 'note_file_publication_unconfirmed', { operationId });
51
+ return { ...result, ...(operationId ? { operationId } : {}) };
52
+ }
53
+ catch (error) {
54
+ const body = error instanceof ApiError ? error.body : undefined;
55
+ operationId ??= noteFileOperationId(body?.operationId);
56
+ // Keep the original error type/status/code and the operation identity, including lost-response failures.
57
+ if (error instanceof Error && operationId)
58
+ Object.assign(error, { operationId });
59
+ throw error;
60
+ }
61
+ };
62
+ const operation = async (operationId, action = 'status') => {
63
+ if (!noteFileOperationId(operationId))
64
+ throw new Error('operation must be a 24-character hexadecimal ID');
65
+ const result = await t.request(action === 'status' ? 'GET' : 'POST', base + '/file-publications/' + seg(operationId) + (action === 'status' ? '' : action === 'cancel' ? '/abort' : '/reconcile'), { redirect: 'manual' });
66
+ if (!result || noteFileOperationId(result.operationId)?.toLowerCase() !== operationId.toLowerCase() ||
67
+ !['admitted', 'write-started', 'published', 'aborted-before-write'].includes(result.state) || typeof result.historicalResult !== 'boolean')
68
+ throw new ApiError(503, 'note_file_operation_unconfirmed', { operationId });
69
+ return result;
70
+ };
71
+ const text = async (ref) => {
72
+ const row = await resolve(ref);
73
+ if (!row.text)
74
+ throw new ApiError(400, 'note_file_not_text', { id: row.id, contentType: row.contentType });
75
+ return t.request('GET', file(row.id) + '/text');
76
+ };
4
77
  return {
5
- download: (id, signal) => {
78
+ list, get, resolve, text, cat: text,
79
+ download: async (ref, signal) => {
6
80
  if (!t.raw)
7
- throw new Error("transport_does_not_support_streaming");
8
- return t.raw("GET", file(id) + "/content", {
9
- signal,
10
- query: { redirect: false },
11
- });
81
+ throw new Error('transport_does_not_support_streaming');
82
+ return t.raw('GET', file(await resolveId(ref)) + '/content', { signal, query: { redirect: false } });
83
+ },
84
+ upload: (path, body, options = {}) => {
85
+ if (options.contentLength !== undefined && (!Number.isSafeInteger(options.contentLength) || options.contentLength < 0))
86
+ throw new Error('contentLength must be a nonnegative safe integer');
87
+ return t.request('PUT', base + '/files/content', { body: body, signal: options.signal,
88
+ query: { path, contentType: options.contentType, overwrite: options.overwrite },
89
+ headers: { 'Content-Type': options.contentType ?? 'application/octet-stream', ...(options.ifMatch ? { 'If-Match': options.ifMatch } : {}),
90
+ ...(options.contentLength === undefined ? {} : { 'Content-Length': String(options.contentLength) }) } });
91
+ },
92
+ write: (input, options = {}) => publish(base + '/files', { ...input, overwrite: input.overwrite ?? false }, options),
93
+ move: async (ref, path, options = {}) => t.request('PATCH', file(await resolveId(ref)), { json: { path, overwrite: options.overwrite ?? false }, headers: options.ifMatch ? { 'If-Match': options.ifMatch } : {} }),
94
+ copy: async (ref, path, options = {}) => {
95
+ validateNoteFileKey(options.idempotencyKey);
96
+ return publish(file(await resolveId(ref)) + '/copy', { path, overwrite: options.overwrite ?? false }, options);
12
97
  },
13
- list: (query = {}) => t.request("GET", base + "/files", {
14
- query,
15
- }),
16
- get: (id) => t.request("GET", file(id)),
17
- text: (id) => t.request("GET", file(id) + "/text"),
18
- upload: (path, body, options = {}) => t.request("PUT", base + "/files/content", {
19
- body,
20
- query: {
21
- path,
22
- contentType: options.contentType,
23
- overwrite: options.overwrite,
24
- },
25
- headers: {
26
- "Content-Type": options.contentType ?? "application/octet-stream",
27
- ...(options.ifMatch ? { "If-Match": options.ifMatch } : {}),
28
- },
29
- }),
30
- write: (input, options = {}) => t.request("POST", base + "/files", {
31
- json: input,
32
- headers: {
33
- ...(options.ifMatch ? { "If-Match": options.ifMatch } : {}),
34
- ...(options.idempotencyKey
35
- ? { "Idempotency-Key": options.idempotencyKey }
36
- : {}),
37
- },
38
- redirect: "manual",
39
- }),
40
- move: (id, path, options = {}) => t.request("PATCH", file(id), {
41
- json: { path, overwrite: options.overwrite ?? false },
42
- headers: options.ifMatch ? { "If-Match": options.ifMatch } : {},
43
- }),
44
- copy: (id, path, options = {}) => t.request("POST", file(id) + "/copy", {
45
- json: { path, overwrite: options.overwrite ?? false },
46
- headers: options.idempotencyKey
47
- ? { "Idempotency-Key": options.idempotencyKey }
48
- : {},
49
- redirect: "manual",
50
- }),
51
- operation: (operationId, action = "status") => t.request(action === "status" ? "GET" : "POST", base +
52
- "/file-publications/" +
53
- seg(operationId) +
54
- (action === "status" ? "" : "/" + action)),
55
- delete: (id, options = {}) => t.request("DELETE", file(id), {
56
- query: { purge: options.purge ?? false },
57
- headers: options.ifMatch ? { "If-Match": options.ifMatch } : {},
58
- }),
59
- restore: (id, path) => t.request("POST", file(id) + "/restore", {
60
- json: path ? { path } : {},
61
- }),
62
- preview: (id, share = false) => t.request("GET", file(id) + "/preview", { query: share ? { share: true } : {} }),
63
- revokePreview: (id) => t.request("DELETE", file(id) + "/preview"),
98
+ operation,
99
+ status: (id) => operation(id),
100
+ reconcile: (id) => operation(id, 'reconcile'),
101
+ cancel: (id) => operation(id, 'cancel'),
102
+ delete: async (ref, options = {}) => t.request('DELETE', file(await resolveId(ref, true)), { query: { purge: options.purge ?? false }, headers: options.ifMatch ? { 'If-Match': options.ifMatch } : {} }),
103
+ restore: async (ref, path) => t.request('POST', file(await resolveId(ref, true)) + '/restore', { json: path ? { path } : {} }),
104
+ preview: async (ref, share = false) => t.request('GET', file(await resolveId(ref)) + '/preview', { query: share ? { share: true } : {} }),
105
+ revokePreview: async (ref) => t.request('DELETE', file(await resolveId(ref)) + '/preview'),
64
106
  };
65
107
  }
@@ -0,0 +1,83 @@
1
+ import type { Transport } from './client.js';
2
+ import { readNoteEvents, type Participant } from './note-events.js';
3
+ export interface NoteLingerOptions {
4
+ signal: AbortSignal;
5
+ format?: 'diff' | 'inline-dff';
6
+ debounce?: string;
7
+ throttle?: string;
8
+ ifMatch?: string;
9
+ intent?: string;
10
+ }
11
+ export type NoteLingerEvent = ({
12
+ type: 'snapshot';
13
+ observedAt: number;
14
+ selectionHash: string;
15
+ participants: Participant[];
16
+ } & LingerRead) | {
17
+ type: 'update';
18
+ observedAt: number;
19
+ content?: LingerRead;
20
+ joined: Participant[];
21
+ left: Participant[];
22
+ activities: Activity[];
23
+ selections: (Participant & {
24
+ hash: string;
25
+ })[];
26
+ };
27
+ export declare const LINGER_BATCH_MS = 2000;
28
+ /** Durations are bounded to avoid accidental busy loops or effectively silent sessions. */
29
+ export declare function lingerDuration(value: string | undefined, option: string): number;
30
+ export interface Activity {
31
+ id: string;
32
+ agent: {
33
+ id: string;
34
+ name: string;
35
+ owner: string;
36
+ };
37
+ kind: "read" | "insert";
38
+ scope: string;
39
+ hash: string;
40
+ ranges: {
41
+ start: number;
42
+ end: number;
43
+ }[];
44
+ at: number;
45
+ expiresAt: number;
46
+ }
47
+ export interface LingerRead {
48
+ note: string;
49
+ hash: string;
50
+ revision: string;
51
+ content?: string;
52
+ base?: string;
53
+ patch?: string;
54
+ format?: string;
55
+ }
56
+ interface Observation {
57
+ body: LingerRead;
58
+ participants: Participant[];
59
+ activities: Activity[];
60
+ }
61
+ export interface LingerRuntime {
62
+ signal?: AbortSignal;
63
+ events?: typeof readNoteEvents;
64
+ now(): number;
65
+ wait(ms: number, signal: AbortSignal): Promise<void>;
66
+ }
67
+ /** Stable activity fingerprints suppress renewed read/typing observations each poll. */
68
+ export declare class LingerBatch {
69
+ private readonly self;
70
+ private participants;
71
+ private activity;
72
+ private selections;
73
+ constructor(initial: Observation, self: string);
74
+ others(rows: Participant[]): Participant[];
75
+ diff(next: Observation): {
76
+ joined: Participant[];
77
+ left: Participant[];
78
+ activities: Activity[];
79
+ selections: Participant[];
80
+ };
81
+ }
82
+ export declare function watchNote(t: Transport, path: string, id: string, opts: NoteLingerOptions, receive: (event: NoteLingerEvent) => void | Promise<void>, clock?: LingerRuntime): Promise<void>;
83
+ export {};
@@ -0,0 +1,270 @@
1
+ /** Shared event-driven Note collaboration engine. Owns a bounded presence lease; never writes Note content. */
2
+ import { createHash } from 'node:crypto';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { readNoteEvents } from './note-events.js';
5
+ import { notePresenceIntent as presenceIntent } from './note-presence.js';
6
+ export const LINGER_BATCH_MS = 2000;
7
+ /** Durations are bounded to avoid accidental busy loops or effectively silent sessions. */
8
+ export function lingerDuration(value, option) {
9
+ if (value === undefined)
10
+ return LINGER_BATCH_MS;
11
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(value);
12
+ const ms = match ? Number(match[1]) * ({ ms: 1, s: 1000, m: 60000 }[match[2]] ?? 0) : NaN;
13
+ if (!Number.isFinite(ms) || ms < 250 || ms > 300000)
14
+ throw new Error(`${option} requires a duration from 250ms to 5m (for example 500ms or 2s)`);
15
+ return ms;
16
+ }
17
+ const HEARTBEAT_MS = 20_000;
18
+ const runtime = {
19
+ now: Date.now,
20
+ wait: async (ms, signal) => { await delay(ms, undefined, { signal }); },
21
+ };
22
+ /** Stable activity fingerprints suppress renewed read/typing observations each poll. */
23
+ export class LingerBatch {
24
+ self;
25
+ participants = new Map();
26
+ activity = new Map();
27
+ selections = new Map();
28
+ constructor(initial, self) {
29
+ this.self = self;
30
+ this.diff(initial);
31
+ }
32
+ others(rows) { return rows.filter(p => p.user.id !== this.self); }
33
+ diff(next) {
34
+ const current = new Map(this.others(next.participants).map(p => [p.client, p]));
35
+ const joined = [...current].filter(([id]) => !this.participants.has(id)).map(([, p]) => p);
36
+ const left = [...this.participants].filter(([id]) => !current.has(id)).map(([, p]) => p);
37
+ const selections = [...current.values()].flatMap(p => {
38
+ const fingerprint = JSON.stringify(p.selection ?? null);
39
+ const changed = this.selections.get(p.client) !== fingerprint;
40
+ this.selections.set(p.client, fingerprint);
41
+ return changed && (p.selection || this.participants.has(p.client)) ? [p] : [];
42
+ });
43
+ for (const p of left) {
44
+ this.selections.delete(p.client);
45
+ selections.push({ ...p, selection: null });
46
+ }
47
+ this.participants = current;
48
+ const seen = new Map();
49
+ const activities = next.activities.filter(a => {
50
+ if (`agent:${a.agent.owner}:${a.agent.id}` === this.self)
51
+ return false;
52
+ const key = `${a.agent.owner}:${a.agent.id}:${a.kind}`;
53
+ const fingerprint = JSON.stringify([a.hash, a.scope, a.ranges]);
54
+ seen.set(key, fingerprint);
55
+ return this.activity.get(key) !== fingerprint;
56
+ });
57
+ this.activity = seen;
58
+ return { joined, left, activities, selections };
59
+ }
60
+ }
61
+ export async function watchNote(t, path, id, opts, receive, clock = { ...runtime, signal: opts.signal }) {
62
+ const format = opts.format ?? 'diff';
63
+ if (!['diff', 'inline-dff'].includes(format))
64
+ throw new Error('--format must be diff or inline-dff');
65
+ if (opts.ifMatch !== undefined && (!opts.ifMatch.trim() || opts.ifMatch === '*' || /[\r\n]/.test(opts.ifMatch)))
66
+ throw new Error('--if-match requires an exact saved revision');
67
+ let debounce, throttle, intent;
68
+ try {
69
+ debounce = lingerDuration(opts.debounce, '--debounce');
70
+ throttle = lingerDuration(opts.throttle, '--throttle');
71
+ intent = presenceIntent(opts.intent);
72
+ }
73
+ catch (error) {
74
+ throw error;
75
+ }
76
+ const abort = new AbortController();
77
+ const stop = () => abort.abort();
78
+ clock.signal?.addEventListener('abort', stop, { once: true });
79
+ if (clock.signal?.aborted)
80
+ stop();
81
+ let leave;
82
+ let streaming;
83
+ let failure;
84
+ try {
85
+ if (abort.signal.aborted)
86
+ return;
87
+ const request = (suffix, extra = {}) => {
88
+ const { method, ...options } = extra;
89
+ return t.request(method ?? 'GET', path + suffix, {
90
+ signal: abort.signal, timeoutMs: 30000, redirect: 'error', ...options,
91
+ });
92
+ };
93
+ // Install cleanup before join: a lost join response may still have created a lease.
94
+ leave = () => t.request('POST', path + '/presence', {
95
+ json: { action: 'leave' }, timeoutMs: 5000, redirect: 'error',
96
+ });
97
+ // Intent rides the join only; heartbeats omit the field, which preserves it.
98
+ const joined = await request('/presence', { method: 'POST', json: { action: 'join', ...(intent ? { intent } : {}) } });
99
+ if (typeof joined?.state?.user?.id !== 'string')
100
+ throw new Error('server did not return an agent presence session');
101
+ const self = joined.state.user.id;
102
+ let heartbeat = clock.now();
103
+ let latest, sequence = 0, handled = -1, streamError;
104
+ let wake = new AbortController();
105
+ const wait = async (ms) => {
106
+ wake = new AbortController();
107
+ try {
108
+ await clock.wait(ms, AbortSignal.any([abort.signal, wake.signal]));
109
+ }
110
+ catch (error) {
111
+ if (!wake.signal.aborted && !abort.signal.aborted)
112
+ throw error;
113
+ }
114
+ };
115
+ streaming = (clock.events ?? readNoteEvents)(path + '/events', '', id, abort.signal, event => {
116
+ latest = event;
117
+ sequence++;
118
+ wake.abort();
119
+ }, async (_url, options) => {
120
+ if (!t.raw)
121
+ throw new Error('transport_does_not_support_streaming');
122
+ return t.raw('GET', path + '/events', { headers: options?.headers, signal: options?.signal, timeoutMs: null, redirect: 'error' });
123
+ }).then(() => {
124
+ if (!abort.signal.aborted)
125
+ streamError = new Error('Notes event stream disconnected');
126
+ wake.abort();
127
+ }, error => { streamError = error; wake.abort(); });
128
+ while (!latest && !streamError && !abort.signal.aborted)
129
+ await wait(45000);
130
+ if (abort.signal.aborted)
131
+ return;
132
+ if (streamError)
133
+ throw streamError;
134
+ const readBody = async (previous) => {
135
+ const query = new URLSearchParams({ contract: 'v2' });
136
+ if (previous) {
137
+ query.set('since', previous.hash);
138
+ query.set('format', format);
139
+ }
140
+ const body = await request('/body?' + query, { headers: !previous && opts.ifMatch ? { 'If-Match': opts.ifMatch } : {} });
141
+ if (body.note !== id || !/^sha256:[a-f0-9]{64}$/.test(body.hash ?? '') || typeof body.revision !== 'string' || !body.revision || /[\r\n]/.test(body.revision))
142
+ throw new Error('invalid Notes v2 snapshot');
143
+ if (!previous) {
144
+ if (typeof body.content !== 'string' || 'sha256:' + createHash('sha256').update(body.content).digest('hex') !== body.hash)
145
+ throw new Error('source does not match the returned hash');
146
+ if (opts.ifMatch && body.revision !== opts.ifMatch)
147
+ throw new Error('note changed since the acknowledged revision');
148
+ }
149
+ else if (body.base !== previous.hash || body.format !== format || typeof body.patch !== 'string') {
150
+ throw new Error('invalid incremental Notes v2 response');
151
+ }
152
+ return body;
153
+ };
154
+ const readActivities = async () => {
155
+ const feed = await request('/agent-activity');
156
+ if (!Array.isArray(feed?.activities))
157
+ throw new Error('server does not support activity reads');
158
+ return feed.activities;
159
+ };
160
+ const initialEvent = latest;
161
+ handled = sequence;
162
+ let initial = { body: await readBody(), participants: initialEvent.participants, activities: await readActivities() };
163
+ if (abort.signal.aborted)
164
+ return;
165
+ if (streamError)
166
+ throw streamError;
167
+ let previous = initial.body;
168
+ let observedActivities = initial.activities;
169
+ const batches = new LingerBatch(initial, self);
170
+ await receive({ type: 'snapshot', observedAt: clock.now(), ...initial.body, selectionHash: initialEvent.hash, participants: batches.others(initial.participants) });
171
+ // Release the full initial source rather than holding it through the entire session.
172
+ previous = { note: previous.note, hash: previous.hash, revision: previous.revision };
173
+ initial = undefined;
174
+ let observedHash = initialEvent.hash;
175
+ let activityVersion = initialEvent.activityVersion;
176
+ let lastEditAt = clock.now(), lastOutputAt = clock.now();
177
+ let dirtyContent = initialEvent.hash !== previous.hash;
178
+ const arrivals = new Map(), departures = new Map();
179
+ const activity = new Map();
180
+ const selections = new Map();
181
+ while (!abort.signal.aborted) {
182
+ if (streamError)
183
+ throw streamError;
184
+ if (sequence !== handled) {
185
+ handled = sequence;
186
+ const event = latest;
187
+ if (event.hash !== observedHash) {
188
+ observedHash = event.hash;
189
+ lastEditAt = clock.now();
190
+ dirtyContent = true;
191
+ }
192
+ if (event.activityVersion !== activityVersion)
193
+ observedActivities = await readActivities();
194
+ const delta = batches.diff({ body: previous, participants: event.participants, activities: observedActivities });
195
+ activityVersion = event.activityVersion;
196
+ for (const p of delta.joined) {
197
+ if (!departures.delete(p.client))
198
+ arrivals.set(p.client, p);
199
+ }
200
+ for (const p of delta.left) {
201
+ if (!arrivals.delete(p.client))
202
+ departures.set(p.client, p);
203
+ }
204
+ for (const p of delta.selections)
205
+ selections.set(p.client, p);
206
+ for (const a of delta.activities)
207
+ activity.set(`${a.agent.owner}:${a.agent.id}:${a.kind}`, a);
208
+ }
209
+ if (clock.now() - heartbeat >= HEARTBEAT_MS) {
210
+ await request('/presence', { method: 'POST', json: { action: 'heartbeat' } });
211
+ heartbeat = clock.now();
212
+ }
213
+ const now = clock.now();
214
+ const deliverContent = dirtyContent && now - lastEditAt >= debounce;
215
+ if (now - lastOutputAt >= throttle && (deliverContent || arrivals.size || departures.size || activity.size || selections.size)) {
216
+ const nextBody = deliverContent ? await readBody(previous) : undefined;
217
+ if (abort.signal.aborted)
218
+ break;
219
+ if (streamError)
220
+ throw streamError;
221
+ // A source event arriving during the read needs its own quiet period.
222
+ if (sequence !== handled && latest.hash !== observedHash)
223
+ continue;
224
+ const events = { joined: [...arrivals.values()], left: [...departures.values()], activities: [...activity.values()],
225
+ selections: [...selections.values()].map(p => ({ ...p, hash: observedHash })) };
226
+ await receive({ type: 'update', observedAt: clock.now(), ...(nextBody ? { content: nextBody } : {}), ...events });
227
+ lastOutputAt = clock.now();
228
+ arrivals.clear();
229
+ departures.clear();
230
+ activity.clear();
231
+ selections.clear();
232
+ if (nextBody) {
233
+ previous = { note: nextBody.note, hash: nextBody.hash, revision: nextBody.revision };
234
+ dirtyContent = false;
235
+ }
236
+ }
237
+ if (sequence !== handled)
238
+ continue;
239
+ const deadlines = [heartbeat + HEARTBEAT_MS];
240
+ if (arrivals.size || departures.size || activity.size || selections.size)
241
+ deadlines.push(lastOutputAt + throttle);
242
+ if (dirtyContent)
243
+ deadlines.push(Math.max(lastEditAt + debounce, lastOutputAt + throttle));
244
+ await wait(Math.max(1, Math.min(...deadlines) - clock.now()));
245
+ }
246
+ }
247
+ catch (error) {
248
+ if (!abort.signal.aborted) {
249
+ failure = error;
250
+ throw error;
251
+ }
252
+ }
253
+ finally {
254
+ abort.abort();
255
+ await streaming;
256
+ try {
257
+ if (leave)
258
+ await leave();
259
+ }
260
+ catch (error) {
261
+ if (failure instanceof Error)
262
+ Object.assign(failure, { cleanupError: error });
263
+ else
264
+ throw error;
265
+ }
266
+ finally {
267
+ clock.signal?.removeEventListener('abort', stop);
268
+ }
269
+ }
270
+ }
@@ -0,0 +1,82 @@
1
+ /** The CLI's Note roster, visit and hash-bound selection contracts. No implicit login or process state. */
2
+ import { type Transport, type RequestOptions } from './client.js';
3
+ import { type NoteEvent, type Participant } from './note-events.js';
4
+ export interface NoteRange {
5
+ start: number;
6
+ end: number;
7
+ }
8
+ export interface NotePresenceRoster {
9
+ participants: Participant[];
10
+ observedAt: number;
11
+ }
12
+ export interface NotePresenceReceipt {
13
+ state?: {
14
+ user?: Participant['user'];
15
+ expiresAt: number;
16
+ activity?: {
17
+ kind: string;
18
+ hash: string;
19
+ ranges: NoteRange[];
20
+ expiresAt: number;
21
+ };
22
+ };
23
+ [key: string]: unknown;
24
+ }
25
+ export interface NoteActivity {
26
+ id: string;
27
+ agent: {
28
+ id: string;
29
+ name: string;
30
+ owner: string;
31
+ };
32
+ kind: 'read' | 'insert';
33
+ scope: string;
34
+ hash: string;
35
+ ranges: NoteRange[];
36
+ at: number;
37
+ expiresAt: number;
38
+ }
39
+ export interface NoteSelectionOptions {
40
+ text: string;
41
+ section?: string;
42
+ occurrence?: number;
43
+ hash?: string;
44
+ }
45
+ export interface NoteSelectionReceipt {
46
+ note: string;
47
+ hash: string;
48
+ text: string;
49
+ scope: {
50
+ kind: 'note';
51
+ } | {
52
+ kind: 'section';
53
+ anchor: string;
54
+ };
55
+ range: NoteRange;
56
+ occurrence: number;
57
+ matches: number;
58
+ published: true;
59
+ selectionExpiresAt: number;
60
+ presenceExpiresAt: number;
61
+ }
62
+ export declare function notePresenceIntent(value: string | undefined): {
63
+ summary: string;
64
+ } | undefined;
65
+ export declare function notePresenceApi(t: Transport, base: string): {
66
+ /** No join or heartbeat. The optional input retains the former POST API for compatibility. */
67
+ presence: {
68
+ (id: string): Promise<NotePresenceRoster>;
69
+ /** @deprecated Use visit or updatePresence for explicit mutations. */
70
+ (id: string, input: Record<string, unknown>): Promise<NotePresenceReceipt>;
71
+ };
72
+ presenceText: (id: string) => Promise<string>;
73
+ updatePresence: (id: string, input: Record<string, unknown>, options?: RequestOptions) => Promise<NotePresenceReceipt>;
74
+ visit: (id: string, options?: {
75
+ intent?: string;
76
+ }) => Promise<NotePresenceReceipt>;
77
+ activity: (id: string, options?: RequestOptions) => Promise<{
78
+ activities: NoteActivity[];
79
+ }>;
80
+ events: (id: string, signal: AbortSignal, receive: (event: NoteEvent) => void) => Promise<void>;
81
+ selectText: (id: string, options: NoteSelectionOptions) => Promise<NoteSelectionReceipt>;
82
+ };