@dreamlake/dreamlake-cli 0.97.2 → 0.99.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 (70) hide show
  1. package/dist/api/client.d.ts +1 -1
  2. package/dist/api/client.js +4 -4
  3. package/dist/api/http.d.ts +48 -1
  4. package/dist/api/http.js +111 -4
  5. package/dist/api/index.d.ts +217 -511
  6. package/dist/api/index.js +12 -2
  7. package/dist/api/native-experiments.d.ts +77 -0
  8. package/dist/api/native-experiments.js +31 -0
  9. package/dist/api/note-edits.d.ts +40 -2
  10. package/dist/api/note-edits.js +197 -2
  11. package/dist/api/note-events.d.ts +40 -4
  12. package/dist/api/note-events.js +55 -2
  13. package/dist/api/note-facade.d.ts +268 -0
  14. package/dist/api/note-facade.js +376 -0
  15. package/dist/api/note-reading.d.ts +27 -0
  16. package/dist/api/note-reading.js +27 -0
  17. package/dist/api/note-write.d.ts +110 -0
  18. package/dist/api/note-write.js +217 -0
  19. package/dist/api/notes.d.ts +33 -44
  20. package/dist/api/notes.js +44 -34
  21. package/dist/api/sessions.d.ts +240 -7
  22. package/dist/api/sessions.js +56 -1
  23. package/dist/api/skills.d.ts +122 -0
  24. package/dist/api/skills.js +220 -0
  25. package/dist/cli/client.d.ts +2 -41
  26. package/dist/cli/client.js +13 -90
  27. package/dist/cli/experiments/index.js +2 -0
  28. package/dist/cli/experiments/native-commands.d.ts +13 -0
  29. package/dist/cli/experiments/native-commands.js +88 -0
  30. package/dist/cli/help-examples.generated.js +23 -6
  31. package/dist/cli/index.js +2 -0
  32. package/dist/cli/notes/api-transport.js +6 -6
  33. package/dist/cli/notes/document.d.ts +32 -26
  34. package/dist/cli/notes/document.js +150 -95
  35. package/dist/cli/notes/edit-commands.d.ts +26 -5
  36. package/dist/cli/notes/edit-commands.js +163 -36
  37. package/dist/cli/notes/events.d.ts +3 -33
  38. package/dist/cli/notes/events.js +4 -51
  39. package/dist/cli/notes/html-read.d.ts +6 -0
  40. package/dist/cli/notes/html-read.js +12 -0
  41. package/dist/cli/notes/index.d.ts +10 -1
  42. package/dist/cli/notes/index.js +98 -27
  43. package/dist/cli/notes/move-command.d.ts +4 -0
  44. package/dist/cli/notes/move-command.js +7 -0
  45. package/dist/cli/session-affiliation.js +3 -2
  46. package/dist/cli/sessions/affiliation.d.ts +12 -1
  47. package/dist/cli/sessions/affiliation.js +37 -0
  48. package/dist/cli/sessions/control.d.ts +11 -0
  49. package/dist/cli/sessions/control.js +49 -4
  50. package/dist/cli/sessions/index.js +70 -17
  51. package/dist/cli/sessions/live.d.ts +85 -0
  52. package/dist/cli/sessions/live.js +258 -0
  53. package/dist/cli/sessions/runner/exec.d.ts +118 -6
  54. package/dist/cli/sessions/runner/exec.js +298 -47
  55. package/dist/cli/sessions/runner/native.js +4 -1
  56. package/dist/cli/sessions/runner/serve.d.ts +37 -2
  57. package/dist/cli/sessions/runner/serve.js +273 -28
  58. package/dist/cli/sessions/wrap.d.ts +63 -0
  59. package/dist/cli/sessions/wrap.js +226 -0
  60. package/dist/cli/skill/index.d.ts +19 -1
  61. package/dist/cli/skill/index.js +65 -12
  62. package/dist/cli/skill/read.d.ts +25 -0
  63. package/dist/cli/skill/read.js +65 -0
  64. package/dist/cli/skill/registry.d.ts +95 -0
  65. package/dist/cli/skill/registry.js +284 -0
  66. package/dist/cli/skill/reminders.js +2 -1
  67. package/dist/cli/vault/sshTransfer.d.ts +1 -1
  68. package/dist/cli/version.d.ts +1 -1
  69. package/dist/cli/version.js +1 -1
  70. package/package.json +9 -9
@@ -1,4 +1,5 @@
1
1
  import { type Transport } from './client.js';
2
+ import type { NoteSource } from './note-edits.js';
2
3
  export interface NoteReadingOptions {
3
4
  at?: string;
4
5
  start?: number;
@@ -22,3 +23,29 @@ export interface NoteReadingPage {
22
23
  }
23
24
  /** Same addressed, revision-pinned reading contract as the built-in agent. */
24
25
  export declare function readNoteView(t: Transport, namespace: string, note: string, options?: NoteReadingOptions): Promise<NoteReadingPage>;
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 NoteFocusedRead {
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<NoteFocusedRead, 'lines' | 'chars' | 'content' | 'next'>;
51
+ export declare function focusedRead(snapshot: NoteSource, lines: [number, number]): NoteFocusedRead;
@@ -13,3 +13,30 @@ export async function readNoteView(t, namespace, note, options = {}) {
13
13
  throw new Error('invalid Note reading page');
14
14
  return page;
15
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 note`);
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
+ }
@@ -0,0 +1,110 @@
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 NotePatch, type NoteSource } from "./note-edits.js";
6
+ export { READING_VIEW_MARKER, READING_VIEW_HEADER, ReadingViewMarkerRefused, refuseReadingView, refuseNewReadingViewLines, refuseReadingViewPatch, applyInlineDff, applyUnifiedDiff } from "./note-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 NoteWriteMode = "merge" | "exact";
10
+ export type NoteWriteOutcome = "accepted" | "no-write";
11
+ export interface NotePatchRequest extends NotePatch {
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 NoteWriteReceipt {
17
+ note: string;
18
+ hash: string;
19
+ revision: string;
20
+ baseRevision: string;
21
+ mode: NoteWriteMode;
22
+ outcome: NoteWriteOutcome;
23
+ commandId: string | null;
24
+ replayed: boolean;
25
+ }
26
+ export interface NoteCommandStatus {
27
+ commandId: string;
28
+ state: "pending" | "accepted" | "no-write" | "unknown";
29
+ outcome?: NoteWriteOutcome;
30
+ receipt?: NoteWriteReceipt;
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 NoteWriteNotSubmitted 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: NotePatchRequest): NotePatchRequest;
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 verifyNoteReceipt(raw: unknown, noteId: string, input: NotePatchRequest): NoteWriteReceipt;
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 submitNotePatch(t: Transport, bodyPath: string, noteId: string, input: NotePatchRequest, options?: {
97
+ ifMatch?: string;
98
+ baseline?: NoteSource;
99
+ }): Promise<NoteWriteReceipt>;
100
+ /** GET the durable record of one command; 404 `command_not_found` passes through as the transport's error. */
101
+ export declare function readNoteCommand(t: Transport, commandPath: string, commandId: string): Promise<NoteCommandStatus>;
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: NoteSource, text: string, mode: NoteWriteMode): {
106
+ suffix: string;
107
+ request: NotePatch;
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: NoteSource, content: string, mode: NoteWriteMode): NotePatch;
@@ -0,0 +1,217 @@
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, NotePatchError, PATCH_LIMITS } from "./note-character-plan.js";
7
+ import { documentEdits, documentInsertion, refuseNewReadingViewLines, refuseReadingViewPatch } from "./note-edits.js";
8
+ export { READING_VIEW_MARKER, READING_VIEW_HEADER, ReadingViewMarkerRefused, refuseReadingView, refuseNewReadingViewLines, refuseReadingViewPatch, applyInlineDff, applyUnifiedDiff } from "./note-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" ? "Notes write outcome unknown: invalid receipt"
45
+ : reason === "server" ? `Notes 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
+ : "Notes 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 note 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 NoteWriteNotSubmitted 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 = "NoteWriteNotSubmitted";
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 (note, 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 verifyNoteReceipt(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 submitNotePatch(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 NoteWriteNotSubmitted({ 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 verifyNoteReceipt(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 readNoteCommand(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 Note 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 NotePatchError("Generated source patch exceeds the edit/byte limit", "LIMIT_EXCEEDED");
215
+ }
216
+ return request;
217
+ }
@@ -2,9 +2,10 @@ import { type NoteReadingOptions } from "./note-reading.js";
2
2
  import * as editing from "./note-editing.js";
3
3
  import { type NoteLingerOptions, type NoteLingerEvent } from "./note-linger.js";
4
4
  import type { Query } from "./common.js";
5
- import { type NoteSource, type NoteEdit, type NotePatch } from "./note-edits.js";
5
+ import { type NoteSource, type NoteEdit } from "./note-edits.js";
6
6
  export { noteEdits, type NoteSource, type NoteEdit, type NotePatch, } from "./note-edits.js";
7
7
  import { type Transport } from "./client.js";
8
+ import { type NotePatchRequest, type NoteWriteReceipt, type NoteCommandStatus } from "./note-write.js";
8
9
  export interface NoteSearchHit {
9
10
  noteId: string;
10
11
  noteSlug: string;
@@ -98,44 +99,25 @@ export declare function notesApi(t: Transport, namespace: string): {
98
99
  text: string;
99
100
  }>;
100
101
  source: (noteId: string, at?: string) => Promise<NoteSource>;
101
- patch: (noteId: string, input: NotePatch) => Promise<{
102
- note: string;
103
- hash: string;
104
- revision: string;
105
- baseRevision: string;
106
- mode: "exact" | "merge";
107
- }>;
108
- replaceContent: (noteId: string, baseRevision: string, content: string, mode?: "exact" | "merge") => Promise<{
109
- note: string;
110
- hash: string;
111
- revision: string;
112
- baseRevision: string;
113
- mode: "exact" | "merge";
114
- }>;
115
- replace: (noteId: string, baseRevision: string, text: string, where: editing.Where, mode?: "exact" | "merge") => Promise<{
116
- note: string;
117
- hash: string;
118
- revision: string;
119
- baseRevision: string;
120
- mode: "exact" | "merge";
121
- }>;
102
+ patch: (noteId: string, input: NotePatchRequest, options?: {
103
+ ifMatch?: string;
104
+ baseline?: NoteSource;
105
+ }) => Promise<NoteWriteReceipt>;
106
+ replaceContent: (noteId: string, baseRevision: string, content: string, mode?: "exact" | "merge", options?: {
107
+ commandId?: string;
108
+ }) => Promise<NoteWriteReceipt>;
109
+ replace: (noteId: string, baseRevision: string, text: string, where: editing.Where, mode?: "exact" | "merge", options?: {
110
+ commandId?: string;
111
+ }) => Promise<NoteWriteReceipt>;
122
112
  insert: (noteId: string, baseRevision: string, text: string, where: {
123
113
  line?: number;
124
114
  ind?: number;
125
- }, mode?: "exact" | "merge") => Promise<{
126
- note: string;
127
- hash: string;
128
- revision: string;
129
- baseRevision: string;
130
- mode: "exact" | "merge";
131
- }>;
132
- removeText: (noteId: string, baseRevision: string, where: editing.Where, mode?: "exact" | "merge") => Promise<{
133
- note: string;
134
- hash: string;
135
- revision: string;
136
- baseRevision: string;
137
- mode: "exact" | "merge";
138
- }>;
115
+ }, mode?: "exact" | "merge", options?: {
116
+ commandId?: string;
117
+ }) => Promise<NoteWriteReceipt>;
118
+ removeText: (noteId: string, baseRevision: string, where: editing.Where, mode?: "exact" | "merge", options?: {
119
+ commandId?: string;
120
+ }) => Promise<NoteWriteReceipt>;
139
121
  findInSource: (noteId: string, at: string, query?: string, options?: editing.FindOpts) => Promise<{
140
122
  matches: editing.Match[];
141
123
  note: string;
@@ -232,7 +214,9 @@ export declare function notesApi(t: Transport, namespace: string): {
232
214
  }>;
233
215
  };
234
216
  media: (form: FormData) => Promise<NoteMediaReceipt>;
235
- read: (noteId: string, query?: Query) => Promise<NoteReadResult>;
217
+ read: (noteId: string, query?: Query, options?: {
218
+ ifMatch?: string;
219
+ }) => Promise<NoteReadResult>;
236
220
  readView: (noteId: string, options?: NoteReadingOptions) => Promise<import("./note-reading.js").NoteReadingPage>;
237
221
  html: (noteId: string, options?: {
238
222
  at?: string;
@@ -281,13 +265,11 @@ export declare function notesApi(t: Transport, namespace: string): {
281
265
  rtcDocId: string;
282
266
  };
283
267
  }>;
284
- edit: (noteId: string, baseRevision: string, edits: NoteEdit[], mode?: "merge" | "exact") => Promise<{
285
- note: string;
286
- hash: string;
287
- revision: string;
288
- baseRevision: string;
289
- mode: "exact" | "merge";
290
- }>;
268
+ edit: (noteId: string, baseRevision: string, edits: NoteEdit[], mode?: "merge" | "exact", options?: {
269
+ commandId?: string;
270
+ }) => Promise<NoteWriteReceipt>;
271
+ /** The durable record of one command id, scoped to the calling actor; 404 `command_not_found` when none. */
272
+ commandStatus: (noteId: string, commandId: string) => Promise<NoteCommandStatus>;
291
273
  versions: (noteId: string, query?: {
292
274
  before?: string;
293
275
  }) => Promise<{
@@ -338,5 +320,12 @@ export declare function notesApi(t: Transport, namespace: string): {
338
320
  }>;
339
321
  events: (id: string, signal: AbortSignal, receive: (event: import("./note-events.js").NoteEvent) => void) => Promise<void>;
340
322
  selectText: (id: string, options: import("./note-presence.js").NoteSelectionOptions) => Promise<import("./note-presence.js").NoteSelectionReceipt>;
323
+ } & {
324
+ /** The full original span of one mapped element (`s1.p2`) at a revision: the scoped HTML read's absolute code-point range. */
325
+ addressRange: (noteId: string, address: string, at: string) => Promise<{
326
+ start: number;
327
+ end: number;
328
+ revision: string;
329
+ }>;
341
330
  };
342
331
  export type NotesApi = ReturnType<typeof notesApi>;
package/dist/api/notes.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readNoteView } from "./note-reading.js";
2
- import { validateHtmlSnapshot } from "./note-html-read.js";
2
+ import { validateHtmlSnapshot, scopedSourceRange } from "./note-html-read.js";
3
3
  import { characterDiff } from "./note-character-plan.js";
4
4
  import * as editing from "./note-editing.js";
5
5
  import { markdownToc as outline } from "./note-toc.js";
@@ -13,6 +13,7 @@ import { createHash } from "node:crypto";
13
13
  import { noteEdits, } from "./note-edits.js";
14
14
  export { noteEdits, } from "./note-edits.js";
15
15
  import { ApiError, isObjectId, seg } from "./client.js";
16
+ import { submitNotePatch, readNoteCommand, validateCommandId, refuseNewReadingViewLines } from "./note-write.js";
16
17
  export function notesApi(t, namespace) {
17
18
  const base = `/namespaces/${seg(namespace)}/notes`;
18
19
  const id = (value) => {
@@ -21,38 +22,33 @@ export function notesApi(t, namespace) {
21
22
  return value;
22
23
  };
23
24
  const source = async (noteId, at) => {
24
- const value = await t.request("GET", `${base}/${id(noteId)}/body`, { query: { contract: "v2", at } });
25
- if (value.note !== noteId ||
26
- typeof value.content !== "string" ||
25
+ const value = await t.request("GET", `${base}/${id(noteId)}/body`, { query: { contract: "v2", at }, redirect: "error" });
26
+ if (!value ||
27
+ value.note !== noteId ||
28
+ !/^sha256:[a-f0-9]{64}$/.test(value.hash ?? "") ||
27
29
  typeof value.revision !== "string" ||
28
- !value.revision ||
30
+ !value.revision.trim() ||
29
31
  /[\r\n]/.test(value.revision) ||
30
- (at !== undefined && value.revision !== at) ||
32
+ /^sha256:/i.test(value.revision))
33
+ throw new Error("server did not return the Notes v2 contract; upgrade the server");
34
+ if (at !== undefined && value.revision !== at)
35
+ throw new Error("server did not return the requested pinned revision");
36
+ if (typeof value.content !== "string" ||
31
37
  value.hash !==
32
- `sha256:${createHash("sha256").update(value.content).digest("hex")}`)
33
- throw new Error("invalid Notes v2 snapshot");
38
+ `sha256:${createHash("sha256").update(value.content, "utf8").digest("hex")}`)
39
+ throw new Error("source does not match the returned hash");
34
40
  return value;
35
41
  };
36
- const patch = async (noteId, input) => {
42
+ /** The one v2 write. `commandId` is sent only when supplied and must be echoed; see note-write.ts. */
43
+ const patch = async (noteId, input, options = {}) => {
37
44
  if (!input.baseRevision ||
38
45
  /[\r\n]/.test(input.baseRevision) ||
39
46
  !["exact", "merge"].includes(input.mode))
40
47
  throw new Error("original baseRevision and mode required");
41
- const receipt = await t.request("PATCH", `${base}/${id(noteId)}/body`, { json: input });
42
- if (receipt.note !== noteId ||
43
- receipt.baseRevision !== input.baseRevision ||
44
- receipt.mode !== input.mode ||
45
- typeof receipt.revision !== "string" ||
46
- !receipt.revision ||
47
- !/^sha256:[a-f0-9]{64}$/.test(receipt.hash) ||
48
- /[\r\n]/.test(receipt.revision))
49
- throw new ApiError(503, "note_write_receipt_unconfirmed", {
50
- note: noteId,
51
- baseRevision: input.baseRevision,
52
- });
53
- return receipt;
48
+ return submitNotePatch(t, `${base}/${id(noteId)}/body`, noteId, input, options);
54
49
  };
55
- return {
50
+ const withCommand = (request, options) => options?.commandId === undefined ? request : { ...request, commandId: options.commandId };
51
+ const api = {
56
52
  ...notePresenceApi(t, base),
57
53
  linger: (noteId, options, receive) => watchNote(t, `${base}/${id(noteId)}`, noteId, options, receive),
58
54
  namespace,
@@ -81,26 +77,27 @@ export function notesApi(t, namespace) {
81
77
  },
82
78
  source,
83
79
  patch,
84
- replaceContent: async (noteId, baseRevision, content, mode = "exact") => {
80
+ replaceContent: async (noteId, baseRevision, content, mode = "exact", options) => {
85
81
  const original = await source(noteId, baseRevision);
86
- return patch(noteId, noteEdits(original, characterDiff(original.content, content).map((e) => ({
82
+ refuseNewReadingViewLines(original.content, content, "content");
83
+ return patch(noteId, withCommand(noteEdits(original, characterDiff(original.content, content).map((e) => ({
87
84
  start: e.start,
88
85
  end: e.end,
89
86
  text: e.replacementText,
90
87
  expected: e.expectedText,
91
- })), mode));
88
+ })), mode), options));
92
89
  },
93
- replace: async (noteId, baseRevision, text, where, mode = "exact") => {
90
+ replace: async (noteId, baseRevision, text, where, mode = "exact", options) => {
94
91
  const original = await source(noteId, baseRevision), plan = editing.replacementPlan(original.content, text, where);
95
- return patch(noteId, noteEdits(original, plan.map(([start, end, text]) => ({ start, end, text })), mode));
92
+ return patch(noteId, withCommand(noteEdits(original, plan.map(([start, end, text]) => ({ start, end, text })), mode), options));
96
93
  },
97
- insert: async (noteId, baseRevision, text, where, mode = "exact") => {
94
+ insert: async (noteId, baseRevision, text, where, mode = "exact", options) => {
98
95
  const original = await source(noteId, baseRevision), placement = editing.insertPlacement(original.content, text, where);
99
- return patch(noteId, noteEdits(original, [{ start: placement.at, end: placement.at, text: placement.text }], mode));
96
+ return patch(noteId, withCommand(noteEdits(original, [{ start: placement.at, end: placement.at, text: placement.text }], mode), options));
100
97
  },
101
- removeText: async (noteId, baseRevision, where, mode = "exact") => {
98
+ removeText: async (noteId, baseRevision, where, mode = "exact", options) => {
102
99
  const original = await source(noteId, baseRevision), plan = editing.removalPlan(original.content, where);
103
- return patch(noteId, noteEdits(original, plan.map(([start, end, text]) => ({ start, end, text })), mode));
100
+ return patch(noteId, withCommand(noteEdits(original, plan.map(([start, end, text]) => ({ start, end, text })), mode), options));
104
101
  },
105
102
  findInSource: async (noteId, at, query, options = {}) => {
106
103
  const original = await source(noteId, at);
@@ -136,8 +133,9 @@ export function notesApi(t, namespace) {
136
133
  throw new Error('invalid media upload response: expected url, contentType and sizeBytes');
137
134
  return receipt;
138
135
  },
139
- read: (noteId, query = {}) => t.request("GET", `${base}/${id(noteId)}/body`, {
136
+ read: (noteId, query = {}, options = {}) => t.request("GET", `${base}/${id(noteId)}/body`, {
140
137
  query: { contract: "v2", ...query },
138
+ ...(options.ifMatch === undefined ? {} : { headers: { "If-Match": options.ifMatch } }),
141
139
  }),
142
140
  readView: (noteId, options = {}) => readNoteView(t, namespace, id(noteId), options),
143
141
  html: async (noteId, options = {}) => {
@@ -177,7 +175,9 @@ export function notesApi(t, namespace) {
177
175
  create: (input) => t.request("POST", base, {
178
176
  json: input,
179
177
  }),
180
- edit: async (noteId, baseRevision, edits, mode = "exact") => patch(noteId, noteEdits(await source(noteId, baseRevision), edits, mode)),
178
+ edit: async (noteId, baseRevision, edits, mode = "exact", options) => patch(noteId, withCommand(noteEdits(await source(noteId, baseRevision), edits, mode), options)),
179
+ /** The durable record of one command id, scoped to the calling actor; 404 `command_not_found` when none. */
180
+ commandStatus: async (noteId, commandId) => readNoteCommand(t, `${base}/${id(noteId)}/commands/${seg(validateCommandId(commandId))}`, commandId),
181
181
  versions: (noteId, query = {}) => t.request("GET", `${base}/${id(noteId)}/versions`, { query }),
182
182
  version: (noteId, versionId) => t.request("GET", `${base}/${id(noteId)}/versions/${seg(versionId)}`),
183
183
  list: (query = {}) => t.request("GET", base, { query }),
@@ -217,4 +217,14 @@ export function notesApi(t, namespace) {
217
217
  return t.request("DELETE", `${base}/${id(noteId)}/sections/${seg(anchor)}`, { headers: { "If-Match": etag } });
218
218
  },
219
219
  };
220
+ return Object.assign(api, {
221
+ /** The full original span of one mapped element (`s1.p2`) at a revision: the scoped HTML read's absolute code-point range. */
222
+ addressRange: async (noteId, address, at) => {
223
+ const scoped = await api.html(noteId, { tag: address, at });
224
+ const range = scopedSourceRange(scoped.html);
225
+ if (!range)
226
+ throw new Error(`address ${address} did not return a scoped source range`);
227
+ return { ...range, revision: scoped.revision };
228
+ },
229
+ });
220
230
  }