@dreamlake/dreamlake-cli 0.97.2 → 0.98.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 (40) 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 +17 -513
  6. package/dist/api/index.js +6 -2
  7. package/dist/api/note-edits.d.ts +40 -2
  8. package/dist/api/note-edits.js +197 -2
  9. package/dist/api/note-events.d.ts +40 -4
  10. package/dist/api/note-events.js +55 -2
  11. package/dist/api/note-facade.d.ts +268 -0
  12. package/dist/api/note-facade.js +376 -0
  13. package/dist/api/note-reading.d.ts +27 -0
  14. package/dist/api/note-reading.js +27 -0
  15. package/dist/api/note-write.d.ts +110 -0
  16. package/dist/api/note-write.js +217 -0
  17. package/dist/api/notes.d.ts +33 -44
  18. package/dist/api/notes.js +44 -34
  19. package/dist/api/sessions.d.ts +5 -5
  20. package/dist/cli/client.d.ts +2 -41
  21. package/dist/cli/client.js +13 -90
  22. package/dist/cli/help-examples.generated.js +1 -1
  23. package/dist/cli/notes/api-transport.js +6 -6
  24. package/dist/cli/notes/document.d.ts +32 -26
  25. package/dist/cli/notes/document.js +150 -95
  26. package/dist/cli/notes/edit-commands.d.ts +26 -5
  27. package/dist/cli/notes/edit-commands.js +163 -36
  28. package/dist/cli/notes/events.d.ts +3 -33
  29. package/dist/cli/notes/events.js +4 -51
  30. package/dist/cli/notes/html-read.d.ts +6 -0
  31. package/dist/cli/notes/html-read.js +12 -0
  32. package/dist/cli/notes/index.d.ts +10 -1
  33. package/dist/cli/notes/index.js +98 -27
  34. package/dist/cli/notes/move-command.d.ts +4 -0
  35. package/dist/cli/notes/move-command.js +7 -0
  36. package/dist/cli/sessions/runner/serve.d.ts +1 -1
  37. package/dist/cli/vault/sshTransfer.d.ts +1 -1
  38. package/dist/cli/version.d.ts +1 -1
  39. package/dist/cli/version.js +1 -1
  40. package/package.json +9 -9
@@ -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
  }
@@ -253,16 +253,16 @@ export declare function sessionsApi(t: Transport, namespace: string): {
253
253
  }) => Promise<{
254
254
  commands: Command[];
255
255
  }>;
256
- get: (commandId: string, wait?: number) => Promise<Command<"status" | "start" | "stop" | "resume" | "send" | "sync" | "subagents">>;
256
+ get: (commandId: string, wait?: number) => Promise<Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents">>;
257
257
  /** Wait up to `seconds` (server-bounded per call; loops for longer waits) for a terminal state. */
258
- wait: (commandId: string, seconds: number, signal?: AbortSignal) => Promise<Command<"status" | "start" | "stop" | "resume" | "send" | "sync" | "subagents">>;
259
- cancel: (commandId: string) => Promise<Command<"status" | "start" | "stop" | "resume" | "send" | "sync" | "subagents">>;
258
+ wait: (commandId: string, seconds: number, signal?: AbortSignal) => Promise<Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents">>;
259
+ cancel: (commandId: string) => Promise<Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents">>;
260
260
  renew: (commandId: string, runnerId: string, leaseToken: string) => Promise<{
261
261
  leaseMs: number;
262
262
  cancelRequested?: boolean;
263
263
  }>;
264
- reconcile: (commandId: string, runnerId: string, observation: Record<string, unknown>) => Promise<Command<"status" | "start" | "stop" | "resume" | "send" | "sync" | "subagents">>;
265
- finish: (commandId: string, runnerId: string, receipt: CommandReceipt) => Promise<Command<"status" | "start" | "stop" | "resume" | "send" | "sync" | "subagents">>;
264
+ reconcile: (commandId: string, runnerId: string, observation: Record<string, unknown>) => Promise<Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents">>;
265
+ finish: (commandId: string, runnerId: string, receipt: CommandReceipt) => Promise<Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents">>;
266
266
  };
267
267
  runners: {
268
268
  list: () => Promise<Runner[]>;
@@ -1,44 +1,5 @@
1
- export declare class HttpError extends Error {
2
- status: number;
3
- body: string;
4
- /**
5
- * The typed fields of a Source v1 error envelope, absent on every other
6
- * shape.
7
- *
8
- * Kept as fields rather than folded into the message because they are what a
9
- * caller BRANCHES on. `code` is the stable identity of a failure — the
10
- * message is a human sentence the server is free to reword — and `retryable`
11
- * is the server's own answer to "would repeating this identical request
12
- * help", which no client can derive from a status alone: a 503 from a rate
13
- * limiter and a 503 from a misconfigured binding look the same on the wire.
14
- *
15
- * `undefined` means "this response was not a v1 envelope", never "the server
16
- * said no". A caller that must fail closed has to treat undefined as
17
- * unknown rather than as false.
18
- */
19
- code?: string;
20
- retryable?: boolean;
21
- requestId?: string;
22
- constructor(status: number, body: string);
23
- /**
24
- * Pull a human message, and any typed fields, out of an error body.
25
- *
26
- * Three shapes reach here and they are not variations of one another:
27
- *
28
- * Source v1 {"error": {"code", "message", "retryable", "requestId"}}
29
- * legacy flat {"error": "..."} or {"message": "..."}
30
- * not JSON an HTML 404 page, a proxy's plain-text 502
31
- *
32
- * The v1 branch is tested FIRST and by type, not by presence. Both envelopes
33
- * key on `error`, so the old `if (parsed.error) return parsed.error` matched
34
- * the v1 object too and interpolated it — a real defect, measured before this
35
- * was written: a 503 carrying a code, a message and a requestId rendered as
36
- * `(503) [object Object]`, and the three fields a caller could have acted on
37
- * were gone. Ordering alone does not prevent that; the `typeof` check is what
38
- * does, because it is the only thing that distinguishes the two.
39
- */
40
- private static parse;
41
- }
1
+ import { HttpError, RequestNotSent } from "../api/http.js";
2
+ export { HttpError, RequestNotSent };
42
3
  export interface RequestOpts {
43
4
  method?: "GET" | "POST" | "PATCH" | "DELETE" | "PUT";
44
5
  /** JSON body — serialized and sent with Content-Type: application/json. */