@dreamlake/dreamlake-cli 0.104.8 → 0.105.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.
- package/dist/api/index.d.ts +27 -17
- package/dist/api/index.js +25 -16
- package/dist/api/memo-character-plan.d.ts +2 -0
- package/dist/api/memo-character-plan.js +2 -0
- package/dist/api/memo-editing.d.ts +2 -0
- package/dist/api/memo-editing.js +2 -0
- package/dist/api/memo-edits.d.ts +63 -0
- package/dist/api/memo-edits.js +206 -0
- package/dist/api/memo-events.d.ts +44 -0
- package/dist/api/memo-events.js +65 -0
- package/dist/api/memo-facade.d.ts +294 -0
- package/dist/api/memo-facade.js +382 -0
- package/dist/api/memo-files.d.ts +111 -0
- package/dist/api/memo-files.js +110 -0
- package/dist/api/memo-html-read.d.ts +2 -0
- package/dist/api/memo-html-read.js +2 -0
- package/dist/api/memo-html.d.ts +2 -0
- package/dist/api/memo-html.js +2 -0
- package/dist/api/memo-linger.d.ts +85 -0
- package/dist/api/memo-linger.js +271 -0
- package/dist/api/memo-presence.d.ts +109 -0
- package/dist/api/memo-presence.js +75 -0
- package/dist/api/memo-reading.d.ts +55 -0
- package/dist/api/memo-reading.js +43 -0
- package/dist/api/memo-toc.d.ts +2 -0
- package/dist/api/memo-toc.js +2 -0
- package/dist/api/memo-write.d.ts +119 -0
- package/dist/api/memo-write.js +221 -0
- package/dist/api/memos.d.ts +344 -0
- package/dist/api/memos.js +231 -0
- package/dist/api/note-character-plan.d.ts +2 -2
- package/dist/api/note-character-plan.js +2 -2
- package/dist/api/note-editing.d.ts +2 -2
- package/dist/api/note-editing.js +2 -2
- package/dist/api/note-edits.d.ts +2 -59
- package/dist/api/note-edits.js +2 -205
- package/dist/api/note-events.d.ts +2 -41
- package/dist/api/note-events.js +2 -64
- package/dist/api/note-facade.d.ts +2 -268
- package/dist/api/note-facade.js +2 -376
- package/dist/api/note-files.d.ts +2 -102
- package/dist/api/note-files.js +2 -107
- package/dist/api/note-html-read.d.ts +2 -2
- package/dist/api/note-html-read.js +2 -2
- package/dist/api/note-html.d.ts +2 -2
- package/dist/api/note-html.js +2 -2
- package/dist/api/note-linger.d.ts +2 -83
- package/dist/api/note-linger.js +2 -270
- package/dist/api/note-presence.d.ts +2 -100
- package/dist/api/note-presence.js +2 -73
- package/dist/api/note-reading.d.ts +2 -51
- package/dist/api/note-reading.js +2 -42
- package/dist/api/note-toc.d.ts +2 -2
- package/dist/api/note-toc.js +2 -2
- package/dist/api/note-write.d.ts +2 -110
- package/dist/api/note-write.js +2 -217
- package/dist/api/notes.d.ts +2 -335
- package/dist/api/notes.js +2 -230
- package/dist/api/open-resources.js +3 -3
- package/dist/cli/folders/index.d.ts +1 -1
- package/dist/cli/folders/index.js +4 -4
- package/dist/cli/index.js +2 -2
- package/dist/cli/{notes → memos}/api-transport.d.ts +1 -1
- package/dist/cli/{notes → memos}/api-transport.js +1 -1
- package/dist/cli/{notes → memos}/archive-command.d.ts +1 -1
- package/dist/cli/{notes → memos}/archive-command.js +5 -5
- package/dist/cli/{notes → memos}/character-plan.d.ts +3 -1
- package/dist/cli/{notes → memos}/character-plan.js +7 -5
- package/dist/cli/{notes → memos}/document.d.ts +9 -9
- package/dist/cli/{notes → memos}/document.js +12 -12
- package/dist/cli/{notes → memos}/edit-commands.d.ts +8 -8
- package/dist/cli/{notes → memos}/edit-commands.js +14 -14
- package/dist/cli/{notes → memos}/events.d.ts +3 -3
- package/dist/cli/{notes → memos}/events.js +2 -2
- package/dist/cli/{notes → memos}/files-commands.d.ts +2 -2
- package/dist/cli/{notes → memos}/files-commands.js +5 -5
- package/dist/cli/{notes → memos}/index.d.ts +16 -16
- package/dist/cli/{notes → memos}/index.js +53 -53
- package/dist/cli/{notes → memos}/linger.d.ts +3 -3
- package/dist/cli/{notes → memos}/linger.js +5 -5
- package/dist/cli/{notes → memos}/move-command.d.ts +5 -5
- package/dist/cli/{notes → memos}/move-command.js +6 -6
- package/dist/cli/{notes → memos}/rm-command.d.ts +2 -2
- package/dist/cli/{notes → memos}/rm-command.js +2 -2
- package/dist/cli/{notes → memos}/select-command.d.ts +1 -1
- package/dist/cli/{notes → memos}/select-command.js +4 -4
- package/dist/cli/{notes → memos}/suggest-diff.d.ts +1 -1
- package/dist/cli/{notes → memos}/suggest-diff.js +2 -2
- package/dist/cli/{notes → memos}/transfer-command.d.ts +2 -2
- package/dist/cli/{notes → memos}/transfer-command.js +2 -2
- package/dist/cli/share.d.ts +1 -1
- package/dist/cli/share.js +1 -1
- package/dist/cli/update/index.js +3 -3
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
- /package/dist/cli/{notes → memos}/editing.d.ts +0 -0
- /package/dist/cli/{notes → memos}/editing.js +0 -0
- /package/dist/cli/{notes → memos}/html-read.d.ts +0 -0
- /package/dist/cli/{notes → memos}/html-read.js +0 -0
- /package/dist/cli/{notes → memos}/html.d.ts +0 -0
- /package/dist/cli/{notes → memos}/html.js +0 -0
- /package/dist/cli/{notes → memos}/media-commands.d.ts +0 -0
- /package/dist/cli/{notes → memos}/media-commands.js +0 -0
- /package/dist/cli/{notes → memos}/toc.d.ts +0 -0
- /package/dist/cli/{notes → memos}/toc.js +0 -0
- /package/dist/cli/{notes → memos}/version-commands.d.ts +0 -0
- /package/dist/cli/{notes → memos}/version-commands.js +0 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Note attachments. JSON receipts match `notes files … --json`; bytes remain streams. */
|
|
2
|
+
import { type Transport, type RequestOptions } from './client.js';
|
|
3
|
+
import type { Readable } from 'node:stream';
|
|
4
|
+
export interface MemoFile {
|
|
5
|
+
id: string;
|
|
6
|
+
path: string;
|
|
7
|
+
contentType: string;
|
|
8
|
+
sizeBytes: number;
|
|
9
|
+
etag: string;
|
|
10
|
+
createdBy: string;
|
|
11
|
+
createdAt: string;
|
|
12
|
+
updatedAt: string;
|
|
13
|
+
trashed: boolean;
|
|
14
|
+
previewKind: string | null;
|
|
15
|
+
text: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface MemoFilePage {
|
|
18
|
+
files: MemoFile[];
|
|
19
|
+
total: number;
|
|
20
|
+
}
|
|
21
|
+
export interface MemoFileListOptions {
|
|
22
|
+
glob?: string;
|
|
23
|
+
trashed?: boolean;
|
|
24
|
+
contentType?: string;
|
|
25
|
+
limit?: number;
|
|
26
|
+
offset?: number;
|
|
27
|
+
/** @deprecated Use glob. This is interpreted as a literal path prefix. */
|
|
28
|
+
prefix?: string;
|
|
29
|
+
/** @deprecated Use trashed. */
|
|
30
|
+
trash?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export type MemoFileWriteReceipt = MemoFile & {
|
|
33
|
+
operationId?: string;
|
|
34
|
+
};
|
|
35
|
+
export interface MemoFileOperationReceipt {
|
|
36
|
+
operationId: string;
|
|
37
|
+
state: 'admitted' | 'write-started' | 'published' | 'aborted-before-write';
|
|
38
|
+
historicalResult: boolean;
|
|
39
|
+
file?: MemoFile;
|
|
40
|
+
}
|
|
41
|
+
export interface MemoFilePreview {
|
|
42
|
+
url: string;
|
|
43
|
+
kind: 'session' | 'shared';
|
|
44
|
+
previewKind: string | null;
|
|
45
|
+
}
|
|
46
|
+
export declare function memoFileOperationId(value: unknown): string | undefined;
|
|
47
|
+
export declare function validateMemoFileKey(key?: string): void;
|
|
48
|
+
export declare function memoFilesApi(t: Transport, base: string): {
|
|
49
|
+
list: (query?: MemoFileListOptions) => Promise<MemoFilePage>;
|
|
50
|
+
get: (id: string) => Promise<MemoFile>;
|
|
51
|
+
resolve: (ref: string, includeTrashed?: boolean) => Promise<MemoFile>;
|
|
52
|
+
text: (ref: string) => Promise<{
|
|
53
|
+
text: string;
|
|
54
|
+
etag: string;
|
|
55
|
+
}>;
|
|
56
|
+
cat: (ref: string) => Promise<{
|
|
57
|
+
text: string;
|
|
58
|
+
etag: string;
|
|
59
|
+
}>;
|
|
60
|
+
download: (ref: string, signal?: AbortSignal) => Promise<Response>;
|
|
61
|
+
upload: (path: string, body: NonNullable<RequestOptions["body"]> | Readable, options?: {
|
|
62
|
+
contentType?: string;
|
|
63
|
+
overwrite?: boolean;
|
|
64
|
+
ifMatch?: string;
|
|
65
|
+
contentLength?: number;
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}) => Promise<MemoFile>;
|
|
68
|
+
write: (input: {
|
|
69
|
+
path: string;
|
|
70
|
+
text: string;
|
|
71
|
+
overwrite?: boolean;
|
|
72
|
+
contentType?: string;
|
|
73
|
+
}, options?: {
|
|
74
|
+
ifMatch?: string;
|
|
75
|
+
idempotencyKey?: string;
|
|
76
|
+
}) => Promise<MemoFileWriteReceipt>;
|
|
77
|
+
move: (ref: string, path: string, options?: {
|
|
78
|
+
overwrite?: boolean;
|
|
79
|
+
ifMatch?: string;
|
|
80
|
+
}) => Promise<MemoFile>;
|
|
81
|
+
copy: (ref: string, path: string, options?: {
|
|
82
|
+
overwrite?: boolean;
|
|
83
|
+
idempotencyKey?: string;
|
|
84
|
+
}) => Promise<MemoFileWriteReceipt>;
|
|
85
|
+
operation: (operationId: string, action?: "status" | "reconcile" | "cancel") => Promise<MemoFileOperationReceipt>;
|
|
86
|
+
status: (id: string) => Promise<MemoFileOperationReceipt>;
|
|
87
|
+
reconcile: (id: string) => Promise<MemoFileOperationReceipt>;
|
|
88
|
+
cancel: (id: string) => Promise<MemoFileOperationReceipt>;
|
|
89
|
+
delete: (ref: string, options?: {
|
|
90
|
+
purge?: boolean;
|
|
91
|
+
ifMatch?: string;
|
|
92
|
+
}) => Promise<{
|
|
93
|
+
id: string;
|
|
94
|
+
purged: boolean;
|
|
95
|
+
}>;
|
|
96
|
+
restore: (ref: string, path?: string) => Promise<MemoFile>;
|
|
97
|
+
preview: (ref: string, share?: boolean) => Promise<MemoFilePreview>;
|
|
98
|
+
revokePreview: (ref: string) => Promise<{
|
|
99
|
+
id: string;
|
|
100
|
+
shared: boolean;
|
|
101
|
+
}>;
|
|
102
|
+
};
|
|
103
|
+
export type { MemoFile as NoteFile };
|
|
104
|
+
export type { MemoFilePage as NoteFilePage };
|
|
105
|
+
export type { MemoFileListOptions as NoteFileListOptions };
|
|
106
|
+
export type { MemoFileWriteReceipt as NoteFileWriteReceipt };
|
|
107
|
+
export type { MemoFileOperationReceipt as NoteFileOperationReceipt };
|
|
108
|
+
export type { MemoFilePreview as NoteFilePreview };
|
|
109
|
+
export { memoFileOperationId as noteFileOperationId };
|
|
110
|
+
export { validateMemoFileKey as validateNoteFileKey };
|
|
111
|
+
export { memoFilesApi as noteFilesApi };
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** Note attachments. JSON receipts match `notes files … --json`; bytes remain streams. */
|
|
2
|
+
import { ApiError, seg } from './client.js';
|
|
3
|
+
export function memoFileOperationId(value) {
|
|
4
|
+
return typeof value === 'string' && /^[a-f0-9]{24}$/i.test(value) ? value : undefined;
|
|
5
|
+
}
|
|
6
|
+
export function validateMemoFileKey(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
|
+
}
|
|
10
|
+
export function memoFilesApi(t, base) {
|
|
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
|
+
validateMemoFileKey(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 = memoFileOperationId(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 ??= memoFileOperationId(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 (!memoFileOperationId(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 || memoFileOperationId(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
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
list, get, resolve, text, cat: text,
|
|
79
|
+
download: async (ref, signal) => {
|
|
80
|
+
if (!t.raw)
|
|
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
|
+
validateMemoFileKey(options.idempotencyKey);
|
|
96
|
+
return publish(file(await resolveId(ref)) + '/copy', { path, overwrite: options.overwrite ?? false }, options);
|
|
97
|
+
},
|
|
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'),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export { memoFileOperationId as noteFileOperationId };
|
|
109
|
+
export { validateMemoFileKey as validateNoteFileKey };
|
|
110
|
+
export { memoFilesApi as noteFilesApi };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Transport } from './client.js';
|
|
2
|
+
import { readMemoEvents, type Participant } from './memo-events.js';
|
|
3
|
+
export interface MemoLingerOptions {
|
|
4
|
+
signal: AbortSignal;
|
|
5
|
+
format?: 'diff' | 'inline-dff';
|
|
6
|
+
debounce?: string;
|
|
7
|
+
throttle?: string;
|
|
8
|
+
ifMatch?: string;
|
|
9
|
+
intent?: string;
|
|
10
|
+
}
|
|
11
|
+
export type MemoLingerEvent = ({
|
|
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 readMemoEvents;
|
|
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 watchMemo(t: Transport, path: string, id: string, opts: MemoLingerOptions, receive: (event: MemoLingerEvent) => void | Promise<void>, clock?: LingerRuntime): Promise<void>;
|
|
83
|
+
export type { MemoLingerOptions as NoteLingerOptions };
|
|
84
|
+
export type { MemoLingerEvent as NoteLingerEvent };
|
|
85
|
+
export { watchMemo as watchNote };
|
|
@@ -0,0 +1,271 @@
|
|
|
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 { readMemoEvents } from './memo-events.js';
|
|
5
|
+
import { memoPresenceIntent as presenceIntent } from './memo-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 watchMemo(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 ?? readMemoEvents)(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('Memos 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 Memos 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('memo 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 Memos 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
|
+
}
|
|
271
|
+
export { watchMemo as watchNote };
|