@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.
Files changed (108) hide show
  1. package/dist/api/index.d.ts +27 -17
  2. package/dist/api/index.js +25 -16
  3. package/dist/api/memo-character-plan.d.ts +2 -0
  4. package/dist/api/memo-character-plan.js +2 -0
  5. package/dist/api/memo-editing.d.ts +2 -0
  6. package/dist/api/memo-editing.js +2 -0
  7. package/dist/api/memo-edits.d.ts +63 -0
  8. package/dist/api/memo-edits.js +206 -0
  9. package/dist/api/memo-events.d.ts +44 -0
  10. package/dist/api/memo-events.js +65 -0
  11. package/dist/api/memo-facade.d.ts +294 -0
  12. package/dist/api/memo-facade.js +382 -0
  13. package/dist/api/memo-files.d.ts +111 -0
  14. package/dist/api/memo-files.js +110 -0
  15. package/dist/api/memo-html-read.d.ts +2 -0
  16. package/dist/api/memo-html-read.js +2 -0
  17. package/dist/api/memo-html.d.ts +2 -0
  18. package/dist/api/memo-html.js +2 -0
  19. package/dist/api/memo-linger.d.ts +85 -0
  20. package/dist/api/memo-linger.js +271 -0
  21. package/dist/api/memo-presence.d.ts +109 -0
  22. package/dist/api/memo-presence.js +75 -0
  23. package/dist/api/memo-reading.d.ts +55 -0
  24. package/dist/api/memo-reading.js +43 -0
  25. package/dist/api/memo-toc.d.ts +2 -0
  26. package/dist/api/memo-toc.js +2 -0
  27. package/dist/api/memo-write.d.ts +119 -0
  28. package/dist/api/memo-write.js +221 -0
  29. package/dist/api/memos.d.ts +344 -0
  30. package/dist/api/memos.js +231 -0
  31. package/dist/api/note-character-plan.d.ts +2 -2
  32. package/dist/api/note-character-plan.js +2 -2
  33. package/dist/api/note-editing.d.ts +2 -2
  34. package/dist/api/note-editing.js +2 -2
  35. package/dist/api/note-edits.d.ts +2 -59
  36. package/dist/api/note-edits.js +2 -205
  37. package/dist/api/note-events.d.ts +2 -41
  38. package/dist/api/note-events.js +2 -64
  39. package/dist/api/note-facade.d.ts +2 -268
  40. package/dist/api/note-facade.js +2 -376
  41. package/dist/api/note-files.d.ts +2 -102
  42. package/dist/api/note-files.js +2 -107
  43. package/dist/api/note-html-read.d.ts +2 -2
  44. package/dist/api/note-html-read.js +2 -2
  45. package/dist/api/note-html.d.ts +2 -2
  46. package/dist/api/note-html.js +2 -2
  47. package/dist/api/note-linger.d.ts +2 -83
  48. package/dist/api/note-linger.js +2 -270
  49. package/dist/api/note-presence.d.ts +2 -100
  50. package/dist/api/note-presence.js +2 -73
  51. package/dist/api/note-reading.d.ts +2 -51
  52. package/dist/api/note-reading.js +2 -42
  53. package/dist/api/note-toc.d.ts +2 -2
  54. package/dist/api/note-toc.js +2 -2
  55. package/dist/api/note-write.d.ts +2 -110
  56. package/dist/api/note-write.js +2 -217
  57. package/dist/api/notes.d.ts +2 -335
  58. package/dist/api/notes.js +2 -230
  59. package/dist/api/open-resources.js +3 -3
  60. package/dist/cli/folders/index.d.ts +1 -1
  61. package/dist/cli/folders/index.js +4 -4
  62. package/dist/cli/index.js +2 -2
  63. package/dist/cli/{notes → memos}/api-transport.d.ts +1 -1
  64. package/dist/cli/{notes → memos}/api-transport.js +1 -1
  65. package/dist/cli/{notes → memos}/archive-command.d.ts +1 -1
  66. package/dist/cli/{notes → memos}/archive-command.js +5 -5
  67. package/dist/cli/{notes → memos}/character-plan.d.ts +3 -1
  68. package/dist/cli/{notes → memos}/character-plan.js +7 -5
  69. package/dist/cli/{notes → memos}/document.d.ts +9 -9
  70. package/dist/cli/{notes → memos}/document.js +12 -12
  71. package/dist/cli/{notes → memos}/edit-commands.d.ts +8 -8
  72. package/dist/cli/{notes → memos}/edit-commands.js +14 -14
  73. package/dist/cli/{notes → memos}/events.d.ts +3 -3
  74. package/dist/cli/{notes → memos}/events.js +2 -2
  75. package/dist/cli/{notes → memos}/files-commands.d.ts +2 -2
  76. package/dist/cli/{notes → memos}/files-commands.js +5 -5
  77. package/dist/cli/{notes → memos}/index.d.ts +16 -16
  78. package/dist/cli/{notes → memos}/index.js +53 -53
  79. package/dist/cli/{notes → memos}/linger.d.ts +3 -3
  80. package/dist/cli/{notes → memos}/linger.js +5 -5
  81. package/dist/cli/{notes → memos}/move-command.d.ts +5 -5
  82. package/dist/cli/{notes → memos}/move-command.js +6 -6
  83. package/dist/cli/{notes → memos}/rm-command.d.ts +2 -2
  84. package/dist/cli/{notes → memos}/rm-command.js +2 -2
  85. package/dist/cli/{notes → memos}/select-command.d.ts +1 -1
  86. package/dist/cli/{notes → memos}/select-command.js +4 -4
  87. package/dist/cli/{notes → memos}/suggest-diff.d.ts +1 -1
  88. package/dist/cli/{notes → memos}/suggest-diff.js +2 -2
  89. package/dist/cli/{notes → memos}/transfer-command.d.ts +2 -2
  90. package/dist/cli/{notes → memos}/transfer-command.js +2 -2
  91. package/dist/cli/share.d.ts +1 -1
  92. package/dist/cli/share.js +1 -1
  93. package/dist/cli/update/index.js +3 -3
  94. package/dist/cli/version.d.ts +1 -1
  95. package/dist/cli/version.js +1 -1
  96. package/package.json +9 -9
  97. /package/dist/cli/{notes → memos}/editing.d.ts +0 -0
  98. /package/dist/cli/{notes → memos}/editing.js +0 -0
  99. /package/dist/cli/{notes → memos}/html-read.d.ts +0 -0
  100. /package/dist/cli/{notes → memos}/html-read.js +0 -0
  101. /package/dist/cli/{notes → memos}/html.d.ts +0 -0
  102. /package/dist/cli/{notes → memos}/html.js +0 -0
  103. /package/dist/cli/{notes → memos}/media-commands.d.ts +0 -0
  104. /package/dist/cli/{notes → memos}/media-commands.js +0 -0
  105. /package/dist/cli/{notes → memos}/toc.d.ts +0 -0
  106. /package/dist/cli/{notes → memos}/toc.js +0 -0
  107. /package/dist/cli/{notes → memos}/version-commands.d.ts +0 -0
  108. /package/dist/cli/{notes → memos}/version-commands.js +0 -0
@@ -0,0 +1,109 @@
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 MemoEvent, type Participant } from './memo-events.js';
4
+ export interface MemoRange {
5
+ start: number;
6
+ end: number;
7
+ }
8
+ export interface MemoPresenceRoster {
9
+ participants: Participant[];
10
+ observedAt: number;
11
+ }
12
+ export interface MemoContributorsPage {
13
+ sessions: {
14
+ id: string;
15
+ name: string;
16
+ namespaceSlug: string;
17
+ contribution: {
18
+ kind: 'created' | 'edited';
19
+ firstAt: string;
20
+ lastAt: string;
21
+ } | null;
22
+ }[];
23
+ hasMore: boolean;
24
+ nextCursor: string | null;
25
+ }
26
+ export interface MemoPresenceReceipt {
27
+ state?: {
28
+ user?: Participant['user'];
29
+ expiresAt: number;
30
+ activity?: {
31
+ kind: string;
32
+ hash: string;
33
+ ranges: MemoRange[];
34
+ expiresAt: number;
35
+ };
36
+ };
37
+ [key: string]: unknown;
38
+ }
39
+ export interface MemoActivity {
40
+ id: string;
41
+ agent: {
42
+ id: string;
43
+ name: string;
44
+ owner: string;
45
+ };
46
+ kind: 'read' | 'insert';
47
+ scope: string;
48
+ hash: string;
49
+ ranges: MemoRange[];
50
+ at: number;
51
+ expiresAt: number;
52
+ }
53
+ export interface MemoSelectionOptions {
54
+ text: string;
55
+ section?: string;
56
+ occurrence?: number;
57
+ hash?: string;
58
+ }
59
+ export interface MemoSelectionReceipt {
60
+ note: string;
61
+ hash: string;
62
+ text: string;
63
+ scope: {
64
+ kind: 'note';
65
+ } | {
66
+ kind: 'section';
67
+ anchor: string;
68
+ };
69
+ range: MemoRange;
70
+ occurrence: number;
71
+ matches: number;
72
+ published: true;
73
+ selectionExpiresAt: number;
74
+ presenceExpiresAt: number;
75
+ }
76
+ export declare function memoPresenceIntent(value: string | undefined): {
77
+ summary: string;
78
+ } | undefined;
79
+ export declare function memoPresenceApi(t: Transport, base: string): {
80
+ contributors: (id: string, options?: {
81
+ cursor?: string;
82
+ pageSize?: number;
83
+ }) => Promise<MemoContributorsPage>;
84
+ /** No join or heartbeat. The optional input retains the former POST API for compatibility. */
85
+ presence: {
86
+ (id: string): Promise<MemoPresenceRoster>;
87
+ /** @deprecated Use visit or updatePresence for explicit mutations. */
88
+ (id: string, input: Record<string, unknown>): Promise<MemoPresenceReceipt>;
89
+ };
90
+ presenceText: (id: string) => Promise<string>;
91
+ updatePresence: (id: string, input: Record<string, unknown>, options?: RequestOptions) => Promise<MemoPresenceReceipt>;
92
+ visit: (id: string, options?: {
93
+ intent?: string;
94
+ }) => Promise<MemoPresenceReceipt>;
95
+ activity: (id: string, options?: RequestOptions) => Promise<{
96
+ activities: MemoActivity[];
97
+ }>;
98
+ events: (id: string, signal: AbortSignal, receive: (event: MemoEvent) => void) => Promise<void>;
99
+ selectText: (id: string, options: MemoSelectionOptions) => Promise<MemoSelectionReceipt>;
100
+ };
101
+ export type { MemoRange as NoteRange };
102
+ export type { MemoPresenceRoster as NotePresenceRoster };
103
+ export type { MemoContributorsPage as NoteContributorsPage };
104
+ export type { MemoPresenceReceipt as NotePresenceReceipt };
105
+ export type { MemoActivity as NoteActivity };
106
+ export type { MemoSelectionOptions as NoteSelectionOptions };
107
+ export type { MemoSelectionReceipt as NoteSelectionReceipt };
108
+ export { memoPresenceIntent as notePresenceIntent };
109
+ export { memoPresenceApi as notePresenceApi };
@@ -0,0 +1,75 @@
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 './memo-editing.js';
4
+ import { readMemoEvents } from './memo-events.js';
5
+ export function memoPresenceIntent(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 memoPresenceApi(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
+ contributors: (id, options = {}) => t.request('GET', path(id) + '/contributors', { query: options }),
21
+ /** No join or heartbeat. The optional input retains the former POST API for compatibility. */
22
+ presence: presence,
23
+ presenceText: async (id) => {
24
+ if (!t.raw)
25
+ throw new Error('transport_does_not_support_streaming');
26
+ return (await t.raw('GET', path(id) + '/presence', { query: { format: 'text' }, redirect: 'error' })).text();
27
+ },
28
+ updatePresence,
29
+ visit: (id, options = {}) => {
30
+ const intent = memoPresenceIntent(options.intent);
31
+ return updatePresence(id, { action: 'join', ...(intent ? { intent } : {}) });
32
+ },
33
+ activity: (id, options = {}) => t.request('GET', path(id) + '/agent-activity', options),
34
+ events: (id, signal, receive) => {
35
+ if (!t.raw)
36
+ throw new Error('transport_does_not_support_streaming');
37
+ return readMemoEvents(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' }));
38
+ },
39
+ selectText: async (id, options) => {
40
+ if (!options.text || options.section === '')
41
+ throw new Error('give nonempty text and an optional nonempty section anchor');
42
+ if (options.occurrence !== undefined && (!Number.isSafeInteger(options.occurrence) || options.occurrence === 0))
43
+ throw new Error('--occurrence (-o) must be a nonzero integer: 1 is first, -1 is last');
44
+ if (options.hash !== undefined && !/^sha256:[a-f0-9]{64}$/.test(options.hash))
45
+ throw new Error('--hash must be sha256: followed by 64 lowercase hex digits');
46
+ 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': '' } });
47
+ const source = options.section !== undefined ? snapshot.text : snapshot.content;
48
+ const offset = options.section !== undefined ? snapshot.range?.start : 0;
49
+ if (typeof source !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(snapshot.hash ?? '') || !Number.isSafeInteger(offset) || offset < 0 ||
50
+ (options.section !== undefined && snapshot.range?.end !== offset + Array.from(source).length))
51
+ throw new Error('server did not provide canonical source/hash and code-point range; section selection requires the updated Memos server');
52
+ if (options.hash !== undefined && options.hash !== snapshot.hash)
53
+ throw new ApiError(409, 'stale_range', { note: id });
54
+ const matches = find(source, options.text), requested = options.occurrence ?? 1;
55
+ const nth = requested < 0 ? matches.length + requested + 1 : requested;
56
+ if (!matches.length || nth < 1 || nth > matches.length)
57
+ throw new ApiError(422, 'note_selection_no_match', { matches: matches.length, occurrence: requested });
58
+ if (matches.length > 1 && options.occurrence === undefined)
59
+ throw new ApiError(422, 'note_selection_ambiguous', { matches: matches.length });
60
+ const match = matches[nth - 1], range = { start: offset + match.ind[0], end: offset + match.ind[1] };
61
+ const result = await updatePresence(id, { action: 'seek', hash: snapshot.hash, ranges: [range] });
62
+ const activity = result.state?.activity;
63
+ if (activity?.kind !== 'seeking' || activity.hash !== snapshot.hash || activity.ranges?.length !== 1 ||
64
+ activity.ranges[0].start !== range.start || activity.ranges[0].end !== range.end ||
65
+ !Number.isFinite(activity.expiresAt) || !Number.isFinite(result.state?.expiresAt))
66
+ throw new ApiError(503, 'note_selection_unconfirmed', { note: id, hash: snapshot.hash, range });
67
+ return { note: id, hash: snapshot.hash, text: match.text,
68
+ scope: options.section === undefined ? { kind: 'note' } : { kind: 'section', anchor: options.section },
69
+ range, occurrence: nth, matches: matches.length, published: true,
70
+ selectionExpiresAt: activity.expiresAt, presenceExpiresAt: result.state.expiresAt };
71
+ },
72
+ };
73
+ }
74
+ export { memoPresenceIntent as notePresenceIntent };
75
+ export { memoPresenceApi as notePresenceApi };
@@ -0,0 +1,55 @@
1
+ import { type Transport } from './client.js';
2
+ import type { MemoSource } from './memo-edits.js';
3
+ export interface MemoReadingOptions {
4
+ at?: string;
5
+ start?: number;
6
+ limit?: number;
7
+ section?: string;
8
+ tag?: string;
9
+ toc?: boolean;
10
+ }
11
+ export interface MemoReadingPage {
12
+ note: string;
13
+ hash: string;
14
+ revision: string;
15
+ text: string;
16
+ scope: string;
17
+ sourceType: 'markdown' | 'html';
18
+ start: number;
19
+ end: number;
20
+ total: number;
21
+ complete: boolean;
22
+ next: number | null;
23
+ }
24
+ /** Same addressed, revision-pinned reading contract as the built-in agent. */
25
+ export declare function readMemoView(t: Transport, namespace: string, note: string, options?: MemoReadingOptions): Promise<MemoReadingPage>;
26
+ export declare class InvalidLineRange extends Error {
27
+ constructor(message: string);
28
+ }
29
+ /** A focused read (contract section C): the exact slice with its global address. Never a complete body. */
30
+ export interface MemoFocusedRead {
31
+ note: string;
32
+ hash: string;
33
+ revision: string;
34
+ /** 1-based, inclusive source lines. */
35
+ lines: [number, number];
36
+ /** [start, end) in Unicode code points of the complete source. */
37
+ chars: [number, number];
38
+ /** What was selected, in the terms it was asked for. */
39
+ scope: {
40
+ lines: [number, number];
41
+ };
42
+ content: string;
43
+ complete: false;
44
+ /** The line after `lines[1]`, when the source has one. */
45
+ next?: number;
46
+ }
47
+ /** 1-based inclusive lines → a [start, end) code-point range of the source. The
48
+ * last line's newline belongs to it; a final newline does not start a line.
49
+ * Code points, never UTF-16 units, so CJK and emoji address correctly. */
50
+ export declare function lineRange(content: string, lines: [number, number]): Pick<MemoFocusedRead, 'lines' | 'chars' | 'content' | 'next'>;
51
+ export declare function focusedRead(snapshot: MemoSource, lines: [number, number]): MemoFocusedRead;
52
+ export type { MemoReadingOptions as NoteReadingOptions };
53
+ export type { MemoReadingPage as NoteReadingPage };
54
+ export { readMemoView as readNoteView };
55
+ export type { MemoFocusedRead as NoteFocusedRead };
@@ -0,0 +1,43 @@
1
+ import { isObjectId, seg } from './client.js';
2
+ /** Same addressed, revision-pinned reading contract as the built-in agent. */
3
+ export async function readMemoView(t, namespace, note, options = {}) {
4
+ if (!isObjectId(note))
5
+ throw new Error('expected a 24-hex memo 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 Memo reading page');
14
+ return page;
15
+ }
16
+ export class InvalidLineRange extends Error {
17
+ constructor(message) { super(message); this.name = 'InvalidLineRange'; }
18
+ }
19
+ /** 1-based inclusive lines → a [start, end) code-point range of the source. The
20
+ * last line's newline belongs to it; a final newline does not start a line.
21
+ * Code points, never UTF-16 units, so CJK and emoji address correctly. */
22
+ export function lineRange(content, lines) {
23
+ if (!Array.isArray(lines) || lines.length !== 2 || !lines.every(n => Number.isSafeInteger(n)))
24
+ throw new InvalidLineRange('lines must be two integers [first, last], 1-based and inclusive');
25
+ const [first, last] = lines;
26
+ if (first < 1 || last < first)
27
+ throw new InvalidLineRange(`line range ${first}:${last} is not a range; lines are 1-based and inclusive`);
28
+ const points = Array.from(content), starts = [0];
29
+ for (let i = 0; i < points.length; i++)
30
+ if (points[i] === '\n' && i + 1 < points.length)
31
+ starts.push(i + 1);
32
+ const total = points.length === 0 ? 0 : starts.length;
33
+ // Refused, not clamped: a range past the end is a misread length, not a request for "to the end".
34
+ if (last > total)
35
+ throw new InvalidLineRange(`line ${last} is past the end of a ${total}-line memo`);
36
+ const start = starts[first - 1], end = last < total ? starts[last] : points.length;
37
+ return { lines: [first, last], chars: [start, end], content: points.slice(start, end).join(''), ...(last < total ? { next: last + 1 } : {}) };
38
+ }
39
+ export function focusedRead(snapshot, lines) {
40
+ const range = lineRange(snapshot.content, lines);
41
+ return { note: snapshot.note, hash: snapshot.hash, revision: snapshot.revision, lines: range.lines, chars: range.chars, scope: { lines: range.lines }, content: range.content, complete: false, ...(range.next === undefined ? {} : { next: range.next }) };
42
+ }
43
+ export { readMemoView as readNoteView };
@@ -0,0 +1,2 @@
1
+ /** Public API export; the existing implementation stays at its original location. */
2
+ export * from "../cli/memos/toc.js";
@@ -0,0 +1,2 @@
1
+ /** Public API export; the existing implementation stays at its original location. */
2
+ export * from "../cli/memos/toc.js";
@@ -0,0 +1,119 @@
1
+ /** Notes v2 body mutations: one submission path with command identity, receipt
2
+ * verification and typed outcomes. The CLI, the facade and the built-in agent
3
+ * all compile to this PATCH; nothing here reads process state. */
4
+ import { type Transport } from "./client.js";
5
+ import { type MemoPatch, type MemoSource } from "./memo-edits.js";
6
+ export { READING_VIEW_MARKER, READING_VIEW_HEADER, ReadingViewMarkerRefused, refuseReadingView, refuseNewReadingViewLines, refuseReadingViewPatch, applyInlineDff, applyUnifiedDiff } from "./memo-edits.js";
7
+ /** Caller-stable command identity: 8–128 characters of `[A-Za-z0-9._:-]`, the server's rule. */
8
+ export declare const COMMAND_ID_PATTERN: RegExp;
9
+ export type MemoWriteMode = "merge" | "exact";
10
+ export type MemoWriteOutcome = "accepted" | "no-write";
11
+ export interface MemoPatchRequest extends MemoPatch {
12
+ /** Sent only when supplied; the receipt must echo it. */
13
+ commandId?: string;
14
+ }
15
+ /** The v2 write receipt. `outcome`, `commandId` and `replayed` are filled in for servers that predate them. */
16
+ export interface MemoWriteReceipt {
17
+ note: string;
18
+ hash: string;
19
+ revision: string;
20
+ baseRevision: string;
21
+ mode: MemoWriteMode;
22
+ outcome: MemoWriteOutcome;
23
+ commandId: string | null;
24
+ replayed: boolean;
25
+ }
26
+ export interface MemoCommandStatus {
27
+ commandId: string;
28
+ state: "pending" | "accepted" | "no-write" | "unknown";
29
+ outcome?: MemoWriteOutcome;
30
+ receipt?: MemoWriteReceipt;
31
+ error?: unknown;
32
+ createdAt: string;
33
+ updatedAt: string;
34
+ }
35
+ export declare class InvalidCommandId extends Error {
36
+ readonly commandId: unknown;
37
+ constructor(commandId: unknown);
38
+ }
39
+ /** The server accepted the write but did not echo the command id: it predates command identity, so a retry is not deduplicated. */
40
+ export declare class CommandIdentityUnsupported extends Error {
41
+ readonly commandId: string;
42
+ readonly receipt: unknown;
43
+ constructor(commandId: string, receipt: unknown);
44
+ }
45
+ /** The request may or may not have been applied. Keep the original baseline and draft.
46
+ * `transport`: lost acknowledgment (network, 5xx, 503); `receipt`: the server
47
+ * answered but the receipt cannot be verified; `server`: the server recorded
48
+ * the command and reports its own outcome as unknown (409 command_outcome_unknown). */
49
+ export declare class UncertainOutcome extends Error {
50
+ readonly commandId: string | null;
51
+ readonly reason: "transport" | "receipt" | "server";
52
+ readonly status?: number;
53
+ constructor(commandId: string | null, reason: "transport" | "receipt" | "server", options?: {
54
+ cause?: unknown;
55
+ status?: number;
56
+ });
57
+ }
58
+ /** The server proved the edit never started (503 `rtc_unavailable` with the typed baseline marker): nothing to reconcile. */
59
+ export declare class MemoWriteNotSubmitted extends Error {
60
+ constructor(options?: {
61
+ cause?: unknown;
62
+ });
63
+ }
64
+ /** 409 `command_in_progress`: an earlier request with this id is still running. */
65
+ export declare class CommandInProgress extends Error {
66
+ readonly commandId: string | null;
67
+ constructor(commandId: string | null, options?: {
68
+ cause?: unknown;
69
+ });
70
+ }
71
+ /** 409 `command_intent_mismatch`: the id was already bound to a different note, baseline, mode, format or patch. */
72
+ export declare class CommandIntentMismatch extends Error {
73
+ readonly commandId: string | null;
74
+ constructor(commandId: string | null, options?: {
75
+ cause?: unknown;
76
+ });
77
+ }
78
+ /** Status, stable code and parsed body of a transport failure, for either error class. */
79
+ export declare function failureInfo(error: unknown): {
80
+ status?: number;
81
+ code?: string;
82
+ body?: unknown;
83
+ };
84
+ /** Current API proof only: exactly `{apiVersion: 1, started: false, phase: "baseline_read"}`. Human text proves nothing. */
85
+ export declare function provenUnsubmitted(body: unknown): boolean;
86
+ export declare function validateCommandId(commandId: string): string;
87
+ /** The exact request body: `commandId` is present only when the caller supplied one. */
88
+ export declare function patchRequestBody(input: MemoPatchRequest): MemoPatchRequest;
89
+ /** Validate a receipt against the request it answers; older servers' receipts are normalized, never guessed beyond the empty-patch case. */
90
+ export declare function verifyMemoReceipt(raw: unknown, noteId: string, input: MemoPatchRequest): MemoWriteReceipt;
91
+ /** PATCH one compiled edit set. Deterministic refusals pass through; a lost
92
+ * acknowledgment or an unverifiable receipt is an UncertainOutcome and is
93
+ * never retried here. The reading-view header check is exact when
94
+ * `options.baseline` is given and best-effort (payload inspection) for a
95
+ * read-free patch; the server is the authoritative enforcement point. */
96
+ export declare function submitMemoPatch(t: Transport, bodyPath: string, noteId: string, input: MemoPatchRequest, options?: {
97
+ ifMatch?: string;
98
+ baseline?: MemoSource;
99
+ }): Promise<MemoWriteReceipt>;
100
+ /** GET the durable record of one command; 404 `command_not_found` passes through as the transport's error. */
101
+ export declare function readMemoCommand(t: Transport, commandPath: string, commandId: string): Promise<MemoCommandStatus>;
102
+ /** Append is verbatim (Notes API contract): the given text, every intended
103
+ * newline included and nothing added, at the end of the retained source. An
104
+ * empty addition compiles to an empty patch — nothing to send. */
105
+ export declare function appendPlan(source: MemoSource, text: string, mode: MemoWriteMode): {
106
+ suffix: string;
107
+ request: MemoPatch;
108
+ };
109
+ /** Replace the whole source: a code-point character diff against the retained snapshot, within the alignment limits. */
110
+ export declare function writePlan(source: MemoSource, content: string, mode: MemoWriteMode): MemoPatch;
111
+ export type { MemoWriteMode as NoteWriteMode };
112
+ export type { MemoWriteOutcome as NoteWriteOutcome };
113
+ export type { MemoPatchRequest as NotePatchRequest };
114
+ export type { MemoWriteReceipt as NoteWriteReceipt };
115
+ export type { MemoCommandStatus as NoteCommandStatus };
116
+ export { MemoWriteNotSubmitted as NoteWriteNotSubmitted };
117
+ export { verifyMemoReceipt as verifyNoteReceipt };
118
+ export { submitMemoPatch as submitNotePatch };
119
+ export { readMemoCommand as readNoteCommand };
@@ -0,0 +1,221 @@
1
+ /** Notes v2 body mutations: one submission path with command identity, receipt
2
+ * verification and typed outcomes. The CLI, the facade and the built-in agent
3
+ * all compile to this PATCH; nothing here reads process state. */
4
+ import { ApiError } from "./client.js";
5
+ import { HttpError, RequestNotSent } from "./http.js";
6
+ import { characterDiff, MemoPatchError, PATCH_LIMITS } from "./memo-character-plan.js";
7
+ import { documentEdits, documentInsertion, refuseNewReadingViewLines, refuseReadingViewPatch } from "./memo-edits.js";
8
+ export { READING_VIEW_MARKER, READING_VIEW_HEADER, ReadingViewMarkerRefused, refuseReadingView, refuseNewReadingViewLines, refuseReadingViewPatch, applyInlineDff, applyUnifiedDiff } from "./memo-edits.js";
9
+ /** Caller-stable command identity: 8–128 characters of `[A-Za-z0-9._:-]`, the server's rule. */
10
+ export const COMMAND_ID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
11
+ /** Every 4xx is settled by the server (the write did not happen), except the
12
+ * command-identity 409s mapped below. 503 after the request left is the lost
13
+ * acknowledgment family; 5xx and network failures are uncertain. */
14
+ const UNCERTAIN_409 = ["command_outcome_unknown", "command_in_progress", "command_intent_mismatch"];
15
+ export class InvalidCommandId extends Error {
16
+ commandId;
17
+ constructor(commandId) {
18
+ super("commandId must be 8–128 characters of A-Z a-z 0-9 . _ : -");
19
+ this.commandId = commandId;
20
+ this.name = "InvalidCommandId";
21
+ }
22
+ }
23
+ /** The server accepted the write but did not echo the command id: it predates command identity, so a retry is not deduplicated. */
24
+ export class CommandIdentityUnsupported extends Error {
25
+ commandId;
26
+ receipt;
27
+ constructor(commandId, receipt) {
28
+ super("server did not echo the command id; it does not support command identity, so this write cannot be retried safely");
29
+ this.commandId = commandId;
30
+ this.receipt = receipt;
31
+ this.name = "CommandIdentityUnsupported";
32
+ }
33
+ }
34
+ /** The request may or may not have been applied. Keep the original baseline and draft.
35
+ * `transport`: lost acknowledgment (network, 5xx, 503); `receipt`: the server
36
+ * answered but the receipt cannot be verified; `server`: the server recorded
37
+ * the command and reports its own outcome as unknown (409 command_outcome_unknown). */
38
+ export class UncertainOutcome extends Error {
39
+ commandId;
40
+ reason;
41
+ status;
42
+ constructor(commandId, reason, options = {}) {
43
+ const cause = options.cause instanceof Error ? options.cause.message : undefined;
44
+ super((reason === "receipt" ? "Memos write outcome unknown: invalid receipt"
45
+ : reason === "server" ? `Memos write outcome unknown: the server recorded command ${commandId} but could not settle it`
46
+ : options.status === 503 ? "the realtime acknowledgment is unavailable; the result may be ambiguous"
47
+ : "Memos write outcome unknown") +
48
+ (reason === "server"
49
+ ? "; keep the original baseline and draft and query the command status before resubmitting; never resend it under a new id"
50
+ : "; keep the original baseline and draft, inspect the memo before resubmitting" +
51
+ (commandId ? `, or retry with the same commandId ${commandId} / query its command status` : "")) +
52
+ (options.status === 503 && cause ? ` (${cause})` : ""), options.cause === undefined ? undefined : { cause: options.cause });
53
+ this.commandId = commandId;
54
+ this.reason = reason;
55
+ this.name = "UncertainOutcome";
56
+ this.status = options.status;
57
+ }
58
+ }
59
+ /** The server proved the edit never started (503 `rtc_unavailable` with the typed baseline marker): nothing to reconcile. */
60
+ export class MemoWriteNotSubmitted extends Error {
61
+ constructor(options) {
62
+ super("patch not submitted: the requested edit did not start because its baseline is unavailable; preserve the original baseline and draft", options);
63
+ this.name = "MemoWriteNotSubmitted";
64
+ }
65
+ }
66
+ /** 409 `command_in_progress`: an earlier request with this id is still running. */
67
+ export class CommandInProgress extends Error {
68
+ commandId;
69
+ constructor(commandId, options) {
70
+ super(`a write with commandId ${commandId} is still in progress on the server; wait, then query its command status before retrying with the same id`, options);
71
+ this.commandId = commandId;
72
+ this.name = "CommandInProgress";
73
+ }
74
+ }
75
+ /** 409 `command_intent_mismatch`: the id was already bound to a different note, baseline, mode, format or patch. */
76
+ export class CommandIntentMismatch extends Error {
77
+ commandId;
78
+ constructor(commandId, options) {
79
+ super(`commandId ${commandId} was already used for a different edit (memo, baseline revision, mode, format or patch differ); a new command needs a new id`, options);
80
+ this.commandId = commandId;
81
+ this.name = "CommandIntentMismatch";
82
+ }
83
+ }
84
+ /** Status, stable code and parsed body of a transport failure, for either error class. */
85
+ export function failureInfo(error) {
86
+ if (error instanceof ApiError) {
87
+ const flat = error.body && typeof error.body === "object" ? error.body.error : undefined;
88
+ return { status: error.status, code: typeof flat === "string" ? flat : error.code, body: error.body };
89
+ }
90
+ if (error instanceof HttpError) {
91
+ let body;
92
+ try {
93
+ body = JSON.parse(error.body);
94
+ }
95
+ catch {
96
+ body = undefined;
97
+ }
98
+ const flat = body && typeof body === "object" ? body.error : undefined;
99
+ return { status: error.status, code: typeof flat === "string" ? flat : error.code, body };
100
+ }
101
+ return {};
102
+ }
103
+ /** Current API proof only: exactly `{apiVersion: 1, started: false, phase: "baseline_read"}`. Human text proves nothing. */
104
+ export function provenUnsubmitted(body) {
105
+ if (!body || typeof body !== "object" || Array.isArray(body))
106
+ return false;
107
+ const envelope = body, marker = envelope.mutation;
108
+ if (envelope.error !== "rtc_unavailable" || !marker || typeof marker !== "object" || Array.isArray(marker))
109
+ return false;
110
+ const value = marker;
111
+ return Object.keys(value).length === 3 && value.apiVersion === 1 && value.started === false && value.phase === "baseline_read";
112
+ }
113
+ export function validateCommandId(commandId) {
114
+ if (typeof commandId !== "string" || !COMMAND_ID_PATTERN.test(commandId))
115
+ throw new InvalidCommandId(commandId);
116
+ return commandId;
117
+ }
118
+ /** The exact request body: `commandId` is present only when the caller supplied one. */
119
+ export function patchRequestBody(input) {
120
+ const body = { format: input.format, patch: input.patch, baseRevision: input.baseRevision, mode: input.mode };
121
+ if (input.commandId !== undefined)
122
+ body.commandId = validateCommandId(input.commandId);
123
+ return body;
124
+ }
125
+ /** Validate a receipt against the request it answers; older servers' receipts are normalized, never guessed beyond the empty-patch case. */
126
+ export function verifyMemoReceipt(raw, noteId, input) {
127
+ const sent = input.commandId ?? null;
128
+ const receipt = raw;
129
+ const invalid = () => new UncertainOutcome(sent, "receipt");
130
+ if (!receipt || typeof receipt !== "object" || receipt.note !== noteId || !/^sha256:[a-f0-9]{64}$/.test(receipt.hash ?? "")
131
+ || typeof receipt.revision !== "string" || !receipt.revision.trim() || /[\r\n]/.test(receipt.revision) || /^sha256:/i.test(receipt.revision)
132
+ || receipt.mode !== input.mode || receipt.baseRevision !== input.baseRevision)
133
+ throw invalid();
134
+ if (receipt.outcome !== undefined && receipt.outcome !== "accepted" && receipt.outcome !== "no-write")
135
+ throw invalid();
136
+ if (receipt.replayed !== undefined && typeof receipt.replayed !== "boolean")
137
+ throw invalid();
138
+ const echoed = receipt.commandId ?? null;
139
+ if (sent !== null) {
140
+ if (echoed === null)
141
+ throw new CommandIdentityUnsupported(sent, raw);
142
+ if (echoed !== sent)
143
+ throw invalid();
144
+ }
145
+ else if (echoed !== null || receipt.replayed)
146
+ throw invalid();
147
+ return {
148
+ note: receipt.note, hash: receipt.hash, revision: receipt.revision, baseRevision: receipt.baseRevision, mode: receipt.mode,
149
+ outcome: receipt.outcome ?? (input.patch === "" ? "no-write" : "accepted"),
150
+ commandId: echoed, replayed: receipt.replayed ?? false,
151
+ };
152
+ }
153
+ /** PATCH one compiled edit set. Deterministic refusals pass through; a lost
154
+ * acknowledgment or an unverifiable receipt is an UncertainOutcome and is
155
+ * never retried here. The reading-view header check is exact when
156
+ * `options.baseline` is given and best-effort (payload inspection) for a
157
+ * read-free patch; the server is the authoritative enforcement point. */
158
+ export async function submitMemoPatch(t, bodyPath, noteId, input, options = {}) {
159
+ const body = patchRequestBody(input);
160
+ refuseReadingViewPatch(body.patch, body.format, options.baseline?.revision === body.baseRevision ? options.baseline.content : undefined);
161
+ let raw;
162
+ try {
163
+ raw = await t.request("PATCH", bodyPath, {
164
+ json: body, redirect: "error",
165
+ headers: options.ifMatch === undefined ? {} : { "If-Match": options.ifMatch },
166
+ });
167
+ }
168
+ catch (error) {
169
+ // The transport could not even build the request: nothing left the process, so nothing is uncertain.
170
+ if (error instanceof RequestNotSent)
171
+ throw error;
172
+ const commandId = body.commandId ?? null, failure = failureInfo(error);
173
+ if (failure.status === 503) {
174
+ if (provenUnsubmitted(failure.body))
175
+ throw new MemoWriteNotSubmitted({ cause: error });
176
+ throw new UncertainOutcome(commandId, "transport", { cause: error, status: 503 });
177
+ }
178
+ if (failure.status === 409 && failure.code !== undefined && UNCERTAIN_409.includes(failure.code)) {
179
+ if (failure.code === "command_outcome_unknown")
180
+ throw new UncertainOutcome(commandId, "server", { cause: error, status: 409 });
181
+ if (failure.code === "command_in_progress")
182
+ throw new CommandInProgress(commandId, { cause: error });
183
+ throw new CommandIntentMismatch(commandId, { cause: error });
184
+ }
185
+ if (failure.status !== undefined && failure.status >= 400 && failure.status < 500)
186
+ throw error;
187
+ throw new UncertainOutcome(commandId, "transport", { cause: error, status: failure.status });
188
+ }
189
+ return verifyMemoReceipt(raw, noteId, body);
190
+ }
191
+ /** GET the durable record of one command; 404 `command_not_found` passes through as the transport's error. */
192
+ export async function readMemoCommand(t, commandPath, commandId) {
193
+ const status = await t.request("GET", commandPath, { redirect: "error" });
194
+ if (!status || typeof status !== "object" || status.commandId !== commandId
195
+ || !["pending", "accepted", "no-write", "unknown"].includes(status.state ?? "")
196
+ || (status.outcome !== undefined && status.outcome !== "accepted" && status.outcome !== "no-write")
197
+ || typeof status.createdAt !== "string" || typeof status.updatedAt !== "string")
198
+ throw new Error("invalid Memo command status");
199
+ return status;
200
+ }
201
+ /** Append is verbatim (Notes API contract): the given text, every intended
202
+ * newline included and nothing added, at the end of the retained source. An
203
+ * empty addition compiles to an empty patch — nothing to send. */
204
+ export function appendPlan(source, text, mode) {
205
+ return { suffix: text, request: documentInsertion(source, Array.from(source.content).length, text, mode === "exact") };
206
+ }
207
+ /** Replace the whole source: a code-point character diff against the retained snapshot, within the alignment limits. */
208
+ export function writePlan(source, content, mode) {
209
+ // Against the baseline, on whole lines: a character diff can split the header across edits, hiding it from documentEdits.
210
+ refuseNewReadingViewLines(source.content, content, "content");
211
+ const edits = characterDiff(source.content, content);
212
+ const request = documentEdits(source, edits.map(edit => ({ start: edit.start, end: edit.end, text: edit.replacementText })), mode === "exact");
213
+ if (edits.length > PATCH_LIMITS.maxEdits || new TextEncoder().encode(request.patch).length > PATCH_LIMITS.maxPatchBytes) {
214
+ throw new MemoPatchError("Generated source patch exceeds the edit/byte limit", "LIMIT_EXCEEDED");
215
+ }
216
+ return request;
217
+ }
218
+ export { MemoWriteNotSubmitted as NoteWriteNotSubmitted };
219
+ export { verifyMemoReceipt as verifyNoteReceipt };
220
+ export { submitMemoPatch as submitNotePatch };
221
+ export { readMemoCommand as readNoteCommand };