@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.
@@ -0,0 +1,72 @@
1
+ /** The CLI's Note roster, visit and hash-bound selection contracts. No implicit login or process state. */
2
+ import { ApiError, seg } from './client.js';
3
+ import { find } from './note-editing.js';
4
+ import { readNoteEvents } from './note-events.js';
5
+ export function notePresenceIntent(value) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ const summary = value.trim();
9
+ if (!summary || Array.from(summary).length > 280)
10
+ throw new Error('--intent requires 1–280 characters of plain text (one short sentence of purpose)');
11
+ return { summary };
12
+ }
13
+ export function notePresenceApi(t, base) {
14
+ const path = (id) => `${base}/${seg(id)}`;
15
+ const updatePresence = (id, input, options = {}) => t.request('POST', path(id) + '/presence', { ...options, json: input });
16
+ const presence = (id, input) => input === undefined
17
+ ? t.request('GET', path(id) + '/presence', { query: { format: 'json' } })
18
+ : updatePresence(id, input);
19
+ return {
20
+ /** No join or heartbeat. The optional input retains the former POST API for compatibility. */
21
+ presence: presence,
22
+ presenceText: async (id) => {
23
+ if (!t.raw)
24
+ throw new Error('transport_does_not_support_streaming');
25
+ return (await t.raw('GET', path(id) + '/presence', { query: { format: 'text' }, redirect: 'error' })).text();
26
+ },
27
+ updatePresence,
28
+ visit: (id, options = {}) => {
29
+ const intent = notePresenceIntent(options.intent);
30
+ return updatePresence(id, { action: 'join', ...(intent ? { intent } : {}) });
31
+ },
32
+ activity: (id, options = {}) => t.request('GET', path(id) + '/agent-activity', options),
33
+ events: (id, signal, receive) => {
34
+ if (!t.raw)
35
+ throw new Error('transport_does_not_support_streaming');
36
+ return readNoteEvents(path(id) + '/events', '', id, signal, receive, async (_url, options) => t.raw('GET', path(id) + '/events', { headers: options?.headers, signal: options?.signal, timeoutMs: null, redirect: 'error' }));
37
+ },
38
+ selectText: async (id, options) => {
39
+ if (!options.text || options.section === '')
40
+ throw new Error('give nonempty text and an optional nonempty section anchor');
41
+ if (options.occurrence !== undefined && (!Number.isSafeInteger(options.occurrence) || options.occurrence === 0))
42
+ throw new Error('--occurrence (-o) must be a nonzero integer: 1 is first, -1 is last');
43
+ if (options.hash !== undefined && !/^sha256:[a-f0-9]{64}$/.test(options.hash))
44
+ throw new Error('--hash must be sha256: followed by 64 lowercase hex digits');
45
+ const snapshot = await t.request('GET', options.section !== undefined ? path(id) + '/sections/' + seg(options.section) : path(id) + '/body', { query: options.section === undefined ? { contract: 'v2' } : undefined, headers: { 'X-DreamLake-Agent-Id': '' } });
46
+ const source = options.section !== undefined ? snapshot.text : snapshot.content;
47
+ const offset = options.section !== undefined ? snapshot.range?.start : 0;
48
+ if (typeof source !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(snapshot.hash ?? '') || !Number.isSafeInteger(offset) || offset < 0 ||
49
+ (options.section !== undefined && snapshot.range?.end !== offset + Array.from(source).length))
50
+ throw new Error('server did not provide canonical source/hash and code-point range; section selection requires the updated Notes server');
51
+ if (options.hash !== undefined && options.hash !== snapshot.hash)
52
+ throw new ApiError(409, 'stale_range', { note: id });
53
+ const matches = find(source, options.text), requested = options.occurrence ?? 1;
54
+ const nth = requested < 0 ? matches.length + requested + 1 : requested;
55
+ if (!matches.length || nth < 1 || nth > matches.length)
56
+ throw new ApiError(422, 'note_selection_no_match', { matches: matches.length, occurrence: requested });
57
+ if (matches.length > 1 && options.occurrence === undefined)
58
+ throw new ApiError(422, 'note_selection_ambiguous', { matches: matches.length });
59
+ const match = matches[nth - 1], range = { start: offset + match.ind[0], end: offset + match.ind[1] };
60
+ const result = await updatePresence(id, { action: 'seek', hash: snapshot.hash, ranges: [range] });
61
+ const activity = result.state?.activity;
62
+ if (activity?.kind !== 'seeking' || activity.hash !== snapshot.hash || activity.ranges?.length !== 1 ||
63
+ activity.ranges[0].start !== range.start || activity.ranges[0].end !== range.end ||
64
+ !Number.isFinite(activity.expiresAt) || !Number.isFinite(result.state?.expiresAt))
65
+ throw new ApiError(503, 'note_selection_unconfirmed', { note: id, hash: snapshot.hash, range });
66
+ return { note: id, hash: snapshot.hash, text: match.text,
67
+ scope: options.section === undefined ? { kind: 'note' } : { kind: 'section', anchor: options.section },
68
+ range, occurrence: nth, matches: matches.length, published: true,
69
+ selectionExpiresAt: activity.expiresAt, presenceExpiresAt: result.state.expiresAt };
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,24 @@
1
+ import { type Transport } from './client.js';
2
+ export interface NoteReadingOptions {
3
+ at?: string;
4
+ start?: number;
5
+ limit?: number;
6
+ section?: string;
7
+ tag?: string;
8
+ toc?: boolean;
9
+ }
10
+ export interface NoteReadingPage {
11
+ note: string;
12
+ hash: string;
13
+ revision: string;
14
+ text: string;
15
+ scope: string;
16
+ sourceType: 'markdown' | 'html';
17
+ start: number;
18
+ end: number;
19
+ total: number;
20
+ complete: boolean;
21
+ next: number | null;
22
+ }
23
+ /** Same addressed, revision-pinned reading contract as the built-in agent. */
24
+ export declare function readNoteView(t: Transport, namespace: string, note: string, options?: NoteReadingOptions): Promise<NoteReadingPage>;
@@ -0,0 +1,15 @@
1
+ import { isObjectId, seg } from './client.js';
2
+ /** Same addressed, revision-pinned reading contract as the built-in agent. */
3
+ export async function readNoteView(t, namespace, note, options = {}) {
4
+ if (!isObjectId(note))
5
+ throw new Error('expected a 24-hex note id');
6
+ if ((options.start ?? 0) > 0 && !options.at)
7
+ throw new Error('reading continuation requires the original revision');
8
+ const page = await t.request('GET', `/namespaces/${seg(namespace)}/notes/${note}/body`, { query: { contract: 'v2', view: 'reading', ...options } });
9
+ if (page.note !== note || typeof page.revision !== 'string' || !page.revision || /[\r\n]/.test(page.revision) || options.at && page.revision !== options.at ||
10
+ !/^sha256:[a-f0-9]{64}$/.test(page.hash) || typeof page.text !== 'string' || !['markdown', 'html'].includes(page.sourceType) || typeof page.scope !== 'string' ||
11
+ ![page.start, page.end, page.total].every(n => Number.isSafeInteger(n) && n >= 0) || page.start !== (options.start ?? 0) || page.end < page.start || page.end > page.total ||
12
+ Array.from(page.text).length !== page.end - page.start || page.complete !== (page.end === page.total) || page.next !== (page.complete ? null : page.end) || !page.complete && page.end === page.start)
13
+ throw new Error('invalid Note reading page');
14
+ return page;
15
+ }
@@ -1,5 +1,7 @@
1
+ import { type NoteReadingOptions } from "./note-reading.js";
1
2
  import * as editing from "./note-editing.js";
2
- import type { JsonObject, Query } from "./common.js";
3
+ import { type NoteLingerOptions, type NoteLingerEvent } from "./note-linger.js";
4
+ import type { Query } from "./common.js";
3
5
  import { type NoteSource, type NoteEdit, type NotePatch } from "./note-edits.js";
4
6
  export { noteEdits, type NoteSource, type NoteEdit, type NotePatch, } from "./note-edits.js";
5
7
  import { type Transport } from "./client.js";
@@ -74,8 +76,25 @@ export interface WriteReceipt {
74
76
  sizeBytes: number;
75
77
  sections?: Section[];
76
78
  }
79
+ export interface NoteMediaReceipt {
80
+ url: string;
81
+ contentType: string;
82
+ sizeBytes: number;
83
+ }
77
84
  export declare function notesApi(t: Transport, namespace: string): {
85
+ linger: (noteId: string, options: NoteLingerOptions, receive: (event: NoteLingerEvent) => void | Promise<void>) => Promise<void>;
78
86
  namespace: string;
87
+ /** Resolve the same ID, exact slug or exact title accepted by the CLI in this namespace. */
88
+ resolve: (ref: string) => Promise<string>;
89
+ /** CSS inspection is read-only; selectText publishes a separate agent selection. */
90
+ selectElement: (noteId: string, css: string) => Promise<{
91
+ etag: string;
92
+ tag: string;
93
+ attrs: Record<string, string | null>;
94
+ outer: [number, number];
95
+ inner: [number, number];
96
+ text: string;
97
+ }>;
79
98
  source: (noteId: string, at?: string) => Promise<NoteSource>;
80
99
  patch: (noteId: string, input: NotePatch) => Promise<{
81
100
  note: string;
@@ -151,25 +170,24 @@ export declare function notesApi(t: Transport, namespace: string): {
151
170
  remove: (userId: string) => Promise<unknown>;
152
171
  };
153
172
  files: (noteId: string) => {
154
- download: (id: string, signal?: AbortSignal) => Promise<Response>;
155
- list: (query?: {
156
- prefix?: string;
157
- trash?: boolean;
158
- limit?: number;
159
- offset?: number;
160
- }) => Promise<{
161
- files: import("./note-files.js").NoteFile[];
162
- total: number;
163
- }>;
173
+ list: (query?: import("./note-files.js").NoteFileListOptions) => Promise<import("./note-files.js").NoteFilePage>;
164
174
  get: (id: string) => Promise<import("./note-files.js").NoteFile>;
165
- text: (id: string) => Promise<{
175
+ resolve: (ref: string, includeTrashed?: boolean) => Promise<import("./note-files.js").NoteFile>;
176
+ text: (ref: string) => Promise<{
166
177
  text: string;
167
178
  etag: string;
168
179
  }>;
169
- upload: (path: string, body: NonNullable<import("./client.js").RequestOptions["body"]>, options?: {
180
+ cat: (ref: string) => Promise<{
181
+ text: string;
182
+ etag: string;
183
+ }>;
184
+ download: (ref: string, signal?: AbortSignal) => Promise<Response>;
185
+ upload: (path: string, body: NonNullable<import("./client.js").RequestOptions["body"]> | import("stream").Readable, options?: {
170
186
  contentType?: string;
171
187
  overwrite?: boolean;
172
188
  ifMatch?: string;
189
+ contentLength?: number;
190
+ signal?: AbortSignal;
173
191
  }) => Promise<import("./note-files.js").NoteFile>;
174
192
  write: (input: {
175
193
  path: string;
@@ -179,40 +197,36 @@ export declare function notesApi(t: Transport, namespace: string): {
179
197
  }, options?: {
180
198
  ifMatch?: string;
181
199
  idempotencyKey?: string;
182
- }) => Promise<import("./note-files.js").NoteFile>;
183
- move: (id: string, path: string, options?: {
200
+ }) => Promise<import("./note-files.js").NoteFileWriteReceipt>;
201
+ move: (ref: string, path: string, options?: {
184
202
  overwrite?: boolean;
185
203
  ifMatch?: string;
186
204
  }) => Promise<import("./note-files.js").NoteFile>;
187
- copy: (id: string, path: string, options?: {
205
+ copy: (ref: string, path: string, options?: {
188
206
  overwrite?: boolean;
189
207
  idempotencyKey?: string;
190
- }) => Promise<import("./note-files.js").NoteFile>;
191
- operation: (operationId: string, action?: "status" | "reconcile" | "cancel") => Promise<{
192
- operationId: string;
193
- state: string;
194
- historicalResult: boolean;
195
- file?: import("./note-files.js").NoteFile;
196
- }>;
197
- delete: (id: string, options?: {
208
+ }) => Promise<import("./note-files.js").NoteFileWriteReceipt>;
209
+ operation: (operationId: string, action?: "status" | "reconcile" | "cancel") => Promise<import("./note-files.js").NoteFileOperationReceipt>;
210
+ status: (id: string) => Promise<import("./note-files.js").NoteFileOperationReceipt>;
211
+ reconcile: (id: string) => Promise<import("./note-files.js").NoteFileOperationReceipt>;
212
+ cancel: (id: string) => Promise<import("./note-files.js").NoteFileOperationReceipt>;
213
+ delete: (ref: string, options?: {
198
214
  purge?: boolean;
199
215
  ifMatch?: string;
200
216
  }) => Promise<{
201
217
  id: string;
202
218
  purged: boolean;
203
219
  }>;
204
- restore: (id: string, path?: string) => Promise<import("./note-files.js").NoteFile>;
205
- preview: (id: string, share?: boolean) => Promise<{
206
- [key: string]: unknown;
207
- url: string;
208
- }>;
209
- revokePreview: (id: string) => Promise<{
220
+ restore: (ref: string, path?: string) => Promise<import("./note-files.js").NoteFile>;
221
+ preview: (ref: string, share?: boolean) => Promise<import("./note-files.js").NoteFilePreview>;
222
+ revokePreview: (ref: string) => Promise<{
210
223
  id: string;
211
224
  shared: boolean;
212
225
  }>;
213
226
  };
214
- media: (form: FormData) => Promise<unknown>;
227
+ media: (form: FormData) => Promise<NoteMediaReceipt>;
215
228
  read: (noteId: string, query?: Query) => Promise<NoteReadResult>;
229
+ readView: (noteId: string, options?: NoteReadingOptions) => Promise<import("./note-reading.js").NoteReadingPage>;
216
230
  html: (noteId: string, options?: {
217
231
  at?: string;
218
232
  section?: string;
@@ -231,7 +245,6 @@ export declare function notesApi(t: Transport, namespace: string): {
231
245
  since?: string;
232
246
  format?: "diff" | "inline-dff";
233
247
  }) => Promise<unknown>;
234
- presence: (noteId: string, input: JsonObject) => Promise<unknown>;
235
248
  saveVersion: (noteId: string, input: {
236
249
  hash: string;
237
250
  tag?: string;
@@ -300,5 +313,19 @@ export declare function notesApi(t: Transport, namespace: string): {
300
313
  after?: string;
301
314
  }, ifMatch?: string) => Promise<WriteReceipt>;
302
315
  removeSection: (noteId: string, anchor: string, ifMatch?: string) => Promise<WriteReceipt>;
316
+ presence: {
317
+ (id: string): Promise<import("./note-presence.js").NotePresenceRoster>;
318
+ (id: string, input: Record<string, unknown>): Promise<import("./note-presence.js").NotePresenceReceipt>;
319
+ };
320
+ presenceText: (id: string) => Promise<string>;
321
+ updatePresence: (id: string, input: Record<string, unknown>, options?: import("./client.js").RequestOptions) => Promise<import("./note-presence.js").NotePresenceReceipt>;
322
+ visit: (id: string, options?: {
323
+ intent?: string;
324
+ }) => Promise<import("./note-presence.js").NotePresenceReceipt>;
325
+ activity: (id: string, options?: import("./client.js").RequestOptions) => Promise<{
326
+ activities: import("./note-presence.js").NoteActivity[];
327
+ }>;
328
+ events: (id: string, signal: AbortSignal, receive: (event: import("./note-events.js").NoteEvent) => void) => Promise<void>;
329
+ selectText: (id: string, options: import("./note-presence.js").NoteSelectionOptions) => Promise<import("./note-presence.js").NoteSelectionReceipt>;
303
330
  };
304
331
  export type NotesApi = ReturnType<typeof notesApi>;
package/dist/api/notes.js CHANGED
@@ -1,9 +1,13 @@
1
+ import { readNoteView } from "./note-reading.js";
1
2
  import { validateHtmlSnapshot } from "./note-html-read.js";
2
3
  import { characterDiff } from "./note-character-plan.js";
3
4
  import * as editing from "./note-editing.js";
4
5
  import { markdownToc as outline } from "./note-toc.js";
6
+ import { parse as parseHtml, select as selectHtml, textPieces } from './note-html.js';
5
7
  /** Notes: search, read, sections, conditional writes. Mirrors the CLI `notes` group. */
6
8
  import { noteFilesApi } from "./note-files.js";
9
+ import { notePresenceApi } from "./note-presence.js";
10
+ import { watchNote } from "./note-linger.js";
7
11
  import { sharingApi } from "./workspace.js";
8
12
  import { createHash } from "node:crypto";
9
13
  import { noteEdits, } from "./note-edits.js";
@@ -49,7 +53,26 @@ export function notesApi(t, namespace) {
49
53
  return receipt;
50
54
  };
51
55
  return {
56
+ ...notePresenceApi(t, base),
57
+ linger: (noteId, options, receive) => watchNote(t, `${base}/${id(noteId)}`, noteId, options, receive),
52
58
  namespace,
59
+ /** Resolve the same ID, exact slug or exact title accepted by the CLI in this namespace. */
60
+ resolve: async (ref) => {
61
+ if (/^[a-f0-9]{24}$/i.test(ref))
62
+ return ref;
63
+ const result = await t.request('GET', base, { query: { limit: 200 } });
64
+ const hit = result.notes.find(row => row.slug === ref || row.id === ref || row.name === ref);
65
+ if (!hit)
66
+ throw new ApiError(404, 'note_not_found', { namespace, ref });
67
+ return hit.id;
68
+ },
69
+ /** CSS inspection is read-only; selectText publishes a separate agent selection. */
70
+ selectElement: async (noteId, css) => {
71
+ const body = await t.request('GET', `${base}/${id(noteId)}/body`);
72
+ const document = parseHtml(body.text), element = selectHtml(document, css);
73
+ return { etag: body.etag, tag: element.tag, attrs: element.attrs, outer: element.outer, inner: element.inner,
74
+ text: textPieces(document, element).map(piece => piece.decoded).join('') };
75
+ },
53
76
  source,
54
77
  patch,
55
78
  replaceContent: async (noteId, baseRevision, content, mode = "exact") => {
@@ -96,10 +119,18 @@ export function notesApi(t, namespace) {
96
119
  move: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/move`, { json: input }),
97
120
  share: (noteId) => sharingApi(t, namespace, "notes", id(noteId)),
98
121
  files: (noteId) => noteFilesApi(t, `${base}/${id(noteId)}`),
99
- media: (form) => t.request("POST", "/notes/media", { body: form }),
122
+ media: async (form) => {
123
+ const receipt = await t.request('POST', '/notes/media', { body: form, redirect: 'error' });
124
+ if (!receipt || typeof receipt.url !== 'string' || !/^https?:\/\/[^\s]+$/.test(receipt.url) ||
125
+ !['http:', 'https:'].includes(new URL(receipt.url).protocol) || typeof receipt.contentType !== 'string' ||
126
+ !Number.isSafeInteger(receipt.sizeBytes) || receipt.sizeBytes < 0)
127
+ throw new Error('invalid media upload response: expected url, contentType and sizeBytes');
128
+ return receipt;
129
+ },
100
130
  read: (noteId, query = {}) => t.request("GET", `${base}/${id(noteId)}/body`, {
101
131
  query: { contract: "v2", ...query },
102
132
  }),
133
+ readView: (noteId, options = {}) => readNoteView(t, namespace, id(noteId), options),
103
134
  html: async (noteId, options = {}) => {
104
135
  if (!t.raw)
105
136
  throw new Error("transport_does_not_support_streaming");
@@ -132,7 +163,6 @@ export function notesApi(t, namespace) {
132
163
  return { note: noteId, revision: snapshot.revision, html, bytes };
133
164
  },
134
165
  diff: (noteId, query) => t.request("GET", `${base}/${id(noteId)}/diff`, { query }),
135
- presence: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/presence`, { json: input }),
136
166
  saveVersion: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/versions`, { json: input }),
137
167
  find: (query) => t.request("GET", `${base}/search`, { query }),
138
168
  create: (input) => t.request("POST", base, {
@@ -52,6 +52,11 @@ export type ListSessionsQuery = {
52
52
  archived?: "exclude" | "include" | "only";
53
53
  machineId?: string;
54
54
  };
55
+ /** Explicit cross-owner filters; never access grants. */
56
+ export type AvailableSessionsQuery = ListSessionsQuery & {
57
+ owner?: string;
58
+ team?: string;
59
+ };
55
60
  export type ConversationMessage = {
56
61
  role: "user" | "assistant" | "tool" | "system";
57
62
  text: string;
@@ -189,7 +194,7 @@ export declare function sessionsApi(t: Transport, namespace: string): {
189
194
  }) => Promise<unknown>;
190
195
  list: (query?: ListSessionsQuery) => Promise<SessionPage>;
191
196
  /** Every session the caller may read across namespaces: public, team-shared and their own. */
192
- available: (query?: ListSessionsQuery) => Promise<SessionPage>;
197
+ available: (query?: AvailableSessionsQuery) => Promise<SessionPage>;
193
198
  get: (sessionId: string) => Promise<Session>;
194
199
  conversation: (sessionId: string) => Promise<{
195
200
  conversation: Conversation | null;
@@ -0,0 +1,5 @@
1
+ import type { Transport } from '../../api/client.js';
2
+ export declare function noteTransport(c: {
3
+ remote: string;
4
+ token: string;
5
+ }): Transport;
@@ -0,0 +1,20 @@
1
+ /** Adapt explicit resolved CLI credentials; attribution remains owned by the CLI transport. */
2
+ import { requestJson, requestRaw } from '../client.js';
3
+ import { requestUrl } from '../../api/http.js';
4
+ export function noteTransport(c) {
5
+ return {
6
+ request: (method, path, options) => {
7
+ if (method === 'HEAD')
8
+ throw new Error('Notes JSON transport does not support HEAD');
9
+ const { body, timeoutMs, ...request } = options ?? {};
10
+ if (body !== undefined)
11
+ throw new Error('Notes collaboration transport requires JSON');
12
+ return requestJson(c.remote, path, { token: c.token, method, ...request, timeoutMs: timeoutMs ?? undefined });
13
+ },
14
+ raw: (method, path, options) => {
15
+ if (method !== 'GET' && method !== 'HEAD')
16
+ throw new Error('Notes streaming transport requires GET or HEAD');
17
+ return requestRaw(requestUrl(c.remote, path, options?.query), { token: c.token, method, headers: options?.headers, signal: options?.signal, timeoutMs: options?.timeoutMs ?? undefined, followRedirects: false });
18
+ },
19
+ };
20
+ }
@@ -1,4 +1,5 @@
1
- import { validateHtmlSnapshot, annotatedMarkdown } from "./html-read.js";
1
+ import { readNoteView } from "../../api/note-reading.js";
2
+ import { validateHtmlSnapshot } from "./html-read.js";
2
3
  /** V2 transports exact source and opaque revisions; the backend owns patch parsing. */
3
4
  import { createHash } from "node:crypto";
4
5
  import { readFileSync, fstatSync } from "node:fs";
@@ -162,7 +163,31 @@ export async function runDocumentRead(ref, opts) {
162
163
  const query = new URLSearchParams({ contract: "v2" });
163
164
  if (opts.at)
164
165
  query.set("at", opts.at);
165
- if (opts.view === "html" || opts.view === "markdown") {
166
+ if (opts.view === "markdown") {
167
+ const transport = { request: (method, path, options = {}) => { if (method !== "GET")
168
+ throw new Error("reading transport requires GET"); return requestJson(c.remote, path, { method, query: options.query, headers: options.headers, token: c.token, redirect: "error" }); } };
169
+ let at = opts.at, start = 0, hash, total;
170
+ do {
171
+ const page = await readNoteView(transport, c.ns, id, { at, start, section: opts.section, tag: opts.tag, toc: opts.toc });
172
+ if (page.sourceType !== 'markdown')
173
+ throw new Error('annotated Markdown requires a Markdown note; use --view html for HTML source');
174
+ if (opts.ifMatch && page.revision !== opts.ifMatch) {
175
+ fail("note changed since the acknowledged revision; keep the original draft and baseline");
176
+ return 3;
177
+ }
178
+ if (hash !== undefined && (hash !== page.hash || total !== page.total))
179
+ throw new Error('Note reading view changed during pagination');
180
+ hash = page.hash;
181
+ total = page.total;
182
+ at = page.revision;
183
+ process.stdout.write(page.text);
184
+ if (page.complete)
185
+ break;
186
+ start = page.next;
187
+ } while (true);
188
+ return 0;
189
+ }
190
+ if (opts.view === "html") {
166
191
  if (opts.section !== undefined)
167
192
  query.set("section", opts.section);
168
193
  if (opts.tag)
@@ -185,7 +210,7 @@ export async function runDocumentRead(ref, opts) {
185
210
  fail("note changed since the acknowledged revision; keep the original draft and baseline");
186
211
  return 3;
187
212
  }
188
- process.stdout.write(opts.view === "markdown" ? annotatedMarkdown(html) : bytes);
213
+ process.stdout.write(bytes);
189
214
  return 0;
190
215
  }
191
216
  if (opts.since !== undefined) {
@@ -1,29 +1,6 @@
1
- /**
2
- * `dreamlake notes files …` — list, upload, download, move, copy, trash.
3
- *
4
- * Bytes are never decoded on this path. Upload reads the local file as a
5
- * Buffer and sends it raw; download writes the response body straight out.
6
- * Only `--text` touches a string, and the server refuses that for anything not
7
- * text-typed rather than round-tripping it through UTF-8.
8
- *
9
- * Downloads refuse to replace a local file unless asked. Everything else here
10
- * goes to a recoverable trash; something overwritten on the caller's disk does
11
- * not come back.
12
- */
1
+ import { type NoteFile } from '../../api/note-files.js';
13
2
  import { type ConnOpts, ctx } from "./index.js";
14
- export interface FileRow {
15
- id: string;
16
- path: string;
17
- contentType: string;
18
- sizeBytes: number;
19
- etag: string;
20
- createdBy: string;
21
- createdAt: string;
22
- updatedAt: string;
23
- trashed: boolean;
24
- previewKind: string | null;
25
- text: boolean;
26
- }
3
+ export type FileRow = NoteFile;
27
4
  /** Exit code for "the file or path was wrong", distinct from a transport failure. */
28
5
  export declare const EXIT_NO_FILE = 6;
29
6
  /** Exit code for a refused overwrite — a script can branch on it and retry. */
@@ -1,3 +1,5 @@
1
+ import { noteFilesApi, noteFileOperationId, validateNoteFileKey } from '../../api/note-files.js';
2
+ import { noteTransport } from './api-transport.js';
1
3
  /**
2
4
  * `dreamlake notes files …` — list, upload, download, move, copy, trash.
3
5
  *
@@ -87,16 +89,17 @@ function reportFile(err, recovery) {
87
89
  return report(err);
88
90
  }
89
91
  function operationIdOf(value) {
90
- return typeof value === "string" && /^[a-f0-9]{24}$/i.test(value) ? value : undefined;
92
+ return noteFileOperationId(value);
91
93
  }
92
94
  function keyValid(key) {
93
- // HTTP field values cannot represent arbitrary Unicode with fetch. Never
94
- // trim, normalize or silently replace the user's operation identity.
95
- if (key !== undefined && (!/^[\x20-\x7e]{1,256}$/.test(key) || key.trim() !== key)) {
96
- fail("--idempotency-key must be 1–256 printable ASCII bytes without surrounding spaces");
95
+ try {
96
+ validateNoteFileKey(key);
97
+ return true;
98
+ }
99
+ catch (error) {
100
+ fail(error.message);
97
101
  return false;
98
102
  }
99
- return true;
100
103
  }
101
104
  function requireFileResult(row) {
102
105
  if (!row || typeof row !== "object" || typeof row.id !== "string" || typeof row.path !== "string") {
@@ -486,24 +489,15 @@ export async function runFilesRestore(ref, opts) {
486
489
  * has to guess.
487
490
  */
488
491
  export async function resolveFile(c, noteId, ref, opts = {}) {
489
- if (/^[0-9a-f]{24}$/i.test(ref)) {
490
- try {
491
- return await requestJson(c.remote, `${filesBase(c, noteId)}/${seg(ref)}`, { token: c.token });
492
- }
493
- catch {
494
- fail(`no file with id ${ref}`);
495
- return null;
496
- }
492
+ try {
493
+ return await noteFilesApi(noteTransport(c), `/namespaces/${seg(c.ns)}/notes/${seg(noteId)}`).resolve(ref, opts.includeTrashed);
497
494
  }
498
- const lists = opts.includeTrashed ? ["", "?trashed=true"] : [""];
499
- for (const qs of lists) {
500
- const res = await requestJson(c.remote, `${filesBase(c, noteId)}${qs}`, { token: c.token });
501
- const hit = res.files.find((f) => f.path === ref);
502
- if (hit)
503
- return hit;
495
+ catch (error) {
496
+ if (error.status !== 404)
497
+ throw error;
498
+ fail(/^[a-f0-9]{24}$/i.test(ref) ? `no file with id ${ref}` : `no file at '${ref}' — 'notes files list --note …' shows what is there`);
499
+ return null;
504
500
  }
505
- fail(`no file at '${ref}' — 'notes files list --note …' shows what is there`);
506
- return null;
507
501
  }
508
502
  /**
509
503
  * `dreamlake notes files preview <file> --note N [--share] [--open]`
@@ -1,3 +1,5 @@
1
+ import { notePresenceApi, notePresenceIntent } from '../../api/note-presence.js';
2
+ import { noteTransport } from './api-transport.js';
1
3
  import { collectionList } from "../collection-list.js";
2
4
  import { registerVersionCommands, runSavedVersionRead } from "./version-commands.js";
3
5
  import { registerMoveCommand } from "./move-command.js";
@@ -1250,12 +1252,7 @@ export async function runNotesPresence(ref, opts) {
1250
1252
  /** The agent's self-reported purpose, validated before any presence request.
1251
1253
  * undefined means the flag was not given — the server then preserves intent. */
1252
1254
  export function presenceIntent(value) {
1253
- if (value === undefined)
1254
- return undefined;
1255
- const summary = value.trim();
1256
- if (!summary || Array.from(summary).length > 280)
1257
- throw new Error('--intent requires 1–280 characters of plain text (one short sentence of purpose)');
1258
- return { summary };
1255
+ return notePresenceIntent(value);
1259
1256
  }
1260
1257
  /** One-shot participation; linger owns its own maintained lease. */
1261
1258
  export async function runNotesVisit(ref, opts) {
@@ -1267,11 +1264,11 @@ export async function runNotesVisit(ref, opts) {
1267
1264
  if (!c)
1268
1265
  return 1;
1269
1266
  try {
1270
- const intent = presenceIntent(opts.intent);
1267
+ presenceIntent(opts.intent);
1271
1268
  const id = await resolveNote(c, ref);
1272
1269
  if (!id)
1273
1270
  return 1;
1274
- const result = await requestJson(c.remote, `/namespaces/${seg(c.ns)}/notes/${seg(id)}/presence`, { method: 'POST', token: c.token, json: { action: 'join', ...(intent ? { intent } : {}) } });
1271
+ const result = await notePresenceApi(noteTransport(c), `/namespaces/${seg(c.ns)}/notes`).visit(id, { intent: opts.intent });
1275
1272
  if (opts.json)
1276
1273
  emitJson(result);
1277
1274
  else
@@ -1,59 +1,4 @@
1
- import { type DocumentReadOptions } from "./document.js";
2
- import { readNoteEvents, type Participant } from "./events.js";
3
- export declare const LINGER_BATCH_MS = 2000;
4
- /** Durations are bounded to avoid accidental busy loops or effectively silent sessions. */
5
- export declare function lingerDuration(value: string | undefined, option: string): number;
6
- interface Activity {
7
- id: string;
8
- agent: {
9
- id: string;
10
- name: string;
11
- owner: string;
12
- };
13
- kind: "read" | "insert";
14
- scope: string;
15
- hash: string;
16
- ranges: {
17
- start: number;
18
- end: number;
19
- }[];
20
- at: number;
21
- expiresAt: number;
22
- }
23
- interface Read {
24
- note: string;
25
- hash: string;
26
- revision: string;
27
- content?: string;
28
- base?: string;
29
- patch?: string;
30
- format?: string;
31
- }
32
- interface Observation {
33
- body: Read;
34
- participants: Participant[];
35
- activities: Activity[];
36
- }
37
- export interface LingerRuntime {
38
- signal?: AbortSignal;
39
- events?: typeof readNoteEvents;
40
- now(): number;
41
- wait(ms: number, signal: AbortSignal): Promise<void>;
42
- }
43
- /** Stable activity fingerprints suppress renewed read/typing observations each poll. */
44
- export declare class LingerBatch {
45
- private readonly self;
46
- private participants;
47
- private activity;
48
- private selections;
49
- constructor(initial: Observation, self: string);
50
- others(rows: Participant[]): Participant[];
51
- diff(next: Observation): {
52
- joined: Participant[];
53
- left: Participant[];
54
- activities: Activity[];
55
- selections: Participant[];
56
- };
57
- }
1
+ import type { DocumentReadOptions } from './document.js';
2
+ import { type LingerRuntime } from '../../api/note-linger.js';
3
+ export { LINGER_BATCH_MS, lingerDuration, LingerBatch, type LingerRuntime } from '../../api/note-linger.js';
58
4
  export declare function runNotesLinger(ref: string | undefined, opts: DocumentReadOptions, clock?: LingerRuntime): Promise<number>;
59
- export {};