@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
package/dist/api/index.js CHANGED
@@ -10,6 +10,8 @@ export * from "./registered-runs.js";
10
10
  import { pagesApi } from "./streams.js";
11
11
  export * from "./streams.js";
12
12
  import { platformApi, machineApi } from "./platform.js";
13
+ import { nativeExperimentsApi } from "./native-experiments.js";
14
+ export * from "./native-experiments.js";
13
15
  export * from "./platform.js";
14
16
  import { vaultApi } from "./vault.js";
15
17
  export * from "./vault.js";
@@ -46,12 +48,14 @@ export * from "./infra.js";
46
48
  */
47
49
  import { agentApi, projectToolsApi } from "./agent.js";
48
50
  import { createTransport, } from "./client.js";
49
- import { notesApi } from "./notes.js";
51
+ import { notesFacade } from "./note-facade.js";
50
52
  import { sessionsApi } from "./sessions.js";
53
+ import { skillsApi } from "./skills.js";
51
54
  export * from "./client.js";
52
55
  export * from "./sessions.js";
53
56
  export * from "./notes.js";
54
57
  export * from "./agent.js";
58
+ export * from "./skills.js";
55
59
  /** TypeScript operations use an explicit transport; importing does not execute CLI startup. */
56
60
  export function createApi(transport) {
57
61
  return {
@@ -62,6 +66,7 @@ export function createApi(transport) {
62
66
  registeredRuns: registeredRunsApi(transport),
63
67
  pages: pagesApi(transport),
64
68
  platform: (namespace) => platformApi(transport, namespace),
69
+ experiments: (namespace, project) => nativeExperimentsApi(transport, namespace, project),
65
70
  machine: machineApi(transport),
66
71
  projectTools: projectToolsApi(transport),
67
72
  vault: (scope) => vaultApi(transport, scope),
@@ -72,7 +77,8 @@ export function createApi(transport) {
72
77
  teams: teamsApi(transport),
73
78
  sessions: (namespace) => sessionsApi(transport, namespace),
74
79
  terminal: (namespace) => terminalApi(transport, namespace),
75
- notes: (namespace) => notesApi(transport, namespace),
80
+ notes: notesFacade(transport),
81
+ skills: skillsApi(transport),
76
82
  projects: (namespace) => projectsApi(transport, namespace),
77
83
  nodes: nodesApi(transport),
78
84
  tasks: (namespace, project) => tasksApi(transport, namespace, project),
@@ -114,3 +120,7 @@ export * from "./note-html-read.js";
114
120
  export { characterDiff, NotePatchError, PATCH_LIMITS, } from "./note-character-plan.js";
115
121
  export * from "./presigned-transfer.js";
116
122
  export * from "./note-events.js";
123
+ export * from "./note-write.js";
124
+ export { documentEdits, documentInsertion } from "./note-edits.js";
125
+ export * from "./note-facade.js";
126
+ export { lineRange, focusedRead, InvalidLineRange } from "./note-reading.js";
@@ -0,0 +1,77 @@
1
+ import { type Transport } from "./client.js";
2
+ export interface NativeExperimentRun {
3
+ id: string;
4
+ name: string;
5
+ projectId: string;
6
+ status: string;
7
+ archivedAt: string | null;
8
+ deletedAt: string | null;
9
+ createdAt: string;
10
+ updatedAt: string;
11
+ }
12
+ export declare function nativeExperimentsApi(t: Transport, namespace: string, project: string): {
13
+ status: () => Promise<unknown>;
14
+ session: (mode: "read" | "write") => Promise<{
15
+ token: string;
16
+ expiresAt: number;
17
+ apiUrl: string;
18
+ provider: string;
19
+ }>;
20
+ create: (key: string) => Promise<{
21
+ experiment: NativeExperimentRun;
22
+ }>;
23
+ list: (query?: {
24
+ limit?: number;
25
+ cursor?: string;
26
+ includeArchived?: boolean;
27
+ }) => Promise<{
28
+ runs: NativeExperimentRun[];
29
+ hasMore: boolean;
30
+ nextCursor: string | null;
31
+ }>;
32
+ get: (id: string) => Promise<{
33
+ experiment: NativeExperimentRun;
34
+ }>;
35
+ trash: (query?: {
36
+ limit?: number;
37
+ cursor?: string;
38
+ }) => Promise<{
39
+ runs: NativeExperimentRun[];
40
+ hasMore: boolean;
41
+ nextCursor: string | null;
42
+ }>;
43
+ delete: (id: string) => Promise<{
44
+ experiment: NativeExperimentRun;
45
+ }>;
46
+ restoreDeleted: (id: string) => Promise<{
47
+ experiment: NativeExperimentRun;
48
+ }>;
49
+ archive: (id: string, archived: boolean) => Promise<{
50
+ experiment: NativeExperimentRun;
51
+ }>;
52
+ parameters: {
53
+ get: (id: string) => Promise<unknown>;
54
+ set: (id: string, data: Record<string, unknown>) => Promise<unknown>;
55
+ };
56
+ logs: {
57
+ list: (id: string, query?: {
58
+ limit?: number;
59
+ cursor?: string;
60
+ }) => Promise<unknown>;
61
+ append: (id: string, entries: Array<{
62
+ timestamp: string;
63
+ level: string;
64
+ message: string;
65
+ metadata?: unknown;
66
+ }>) => Promise<unknown>;
67
+ };
68
+ metrics: {
69
+ list: (id: string) => Promise<unknown>;
70
+ rows: (id: string, name: string, query?: {
71
+ limit?: number;
72
+ cursor?: string;
73
+ }) => Promise<unknown>;
74
+ append: (id: string, name: string, dataPoints: Record<string, unknown>[]) => Promise<unknown>;
75
+ };
76
+ setStatus: (id: string, status: "RUNNING" | "COMPLETED" | "FAILED" | "CANCELLED") => Promise<unknown>;
77
+ };
@@ -0,0 +1,31 @@
1
+ import { seg } from "./client.js";
2
+ import { call } from "./common.js";
3
+ export function nativeExperimentsApi(t, namespace, project) {
4
+ const base = `/native-experiments/ns/${seg(namespace)}/projects/${seg(project)}`;
5
+ const run = (id) => `${base}/runs/${seg(id)}`;
6
+ return {
7
+ status: () => call(t, "GET", `${base}/status`),
8
+ session: (mode) => call(t, "POST", `${base}/session`, { mode }),
9
+ create: (key) => call(t, "PUT", run(key)),
10
+ list: (query = {}) => call(t, "GET", `${base}/runs`, undefined, query),
11
+ get: (id) => call(t, "GET", run(id)),
12
+ trash: (query = {}) => call(t, "GET", `${base}/trash`, undefined, query),
13
+ delete: (id) => call(t, "DELETE", run(id)),
14
+ restoreDeleted: (id) => call(t, "POST", `${run(id)}/restore`),
15
+ archive: (id, archived) => call(t, "PATCH", run(id), { archived }),
16
+ parameters: {
17
+ get: (id) => call(t, "GET", `${run(id)}/parameters`),
18
+ set: (id, data) => call(t, "POST", `${run(id)}/parameters`, { data }),
19
+ },
20
+ logs: {
21
+ list: (id, query = {}) => call(t, "GET", `${run(id)}/logs`, undefined, query),
22
+ append: (id, entries) => call(t, "POST", `${run(id)}/logs`, { entries }),
23
+ },
24
+ metrics: {
25
+ list: (id) => call(t, "GET", `${run(id)}/metrics`),
26
+ rows: (id, name, query = {}) => call(t, "GET", `${run(id)}/metrics/${seg(name)}`, undefined, query),
27
+ append: (id, name, dataPoints) => call(t, "POST", `${run(id)}/metrics/${seg(name)}`, { dataPoints }),
28
+ },
29
+ setStatus: (id, status) => call(t, "POST", `${run(id)}/status`, { status }),
30
+ };
31
+ }
@@ -5,10 +5,12 @@ export interface NoteSource {
5
5
  hash: string;
6
6
  revision: string;
7
7
  }
8
- export interface NoteEdit {
8
+ export interface SourceEdit {
9
9
  start: number;
10
10
  end: number;
11
11
  text: string;
12
+ }
13
+ export interface NoteEdit extends SourceEdit {
12
14
  expected?: string;
13
15
  }
14
16
  export interface NotePatch {
@@ -17,5 +19,41 @@ export interface NotePatch {
17
19
  baseRevision: string;
18
20
  mode: "merge" | "exact";
19
21
  }
20
- /** Validate optional expected text, then use the existing source-span compiler. */
22
+ /** The CLI's names for the same shapes; `src/cli/notes/document.ts` re-exports them. */
23
+ export type SourceSnapshot = NoteSource;
24
+ export type DocumentPatchPayload = NotePatch;
25
+ /** Generated reading-view annotations are never saved as source. What is
26
+ * forbidden is NEW text that carries the generated header line
27
+ * (`<!-- notes-reading-view revision=… hash=…`). Deleting such a line, keeping
28
+ * one the note already has, or mentioning the marker in prose or a code block
29
+ * is allowed. Checked on raw inserted text before compilation (escaping would
30
+ * hide it) and on the insertion payloads of a caller-supplied patch. */
31
+ export declare const READING_VIEW_MARKER = "<!-- notes-reading-view";
32
+ export declare const READING_VIEW_HEADER: RegExp;
33
+ export declare class ReadingViewMarkerRefused extends Error {
34
+ constructor(what: string);
35
+ }
36
+ /** Inserted or replacement text only, never deletions or unchanged context. */
37
+ export declare function refuseReadingView(text: string, what: string): void;
38
+ /** Whole-body replacement: only lines that are new relative to the baseline count, so a header the note already holds survives a write. */
39
+ export declare function refuseNewReadingViewLines(baseline: string, content: string, what: string): void;
40
+ /** Apply the inline-dff subset this client emits (`@@ chars s:e @@` + one `~` line of `[-old-]`/`{+new+}`
41
+ * segments) to a baseline. null when the patch is outside that subset or its old text does not match. */
42
+ export declare function applyInlineDff(baseline: string, patch: string): string | null;
43
+ /** Apply a unified diff to a baseline, verifying context and removed lines. null when it does not apply cleanly. */
44
+ export declare function applyUnifiedDiff(baseline: string, patch: string): string | null;
45
+ /** A caller-supplied patch. With the baseline it was written against, the target is reconstructed and
46
+ * checked like a whole-body write (so a header split across hunks is seen assembled, and one the note
47
+ * already has may be re-added). Without a baseline, or when the patch does not apply to it, the check is
48
+ * BEST-EFFORT on the insertion payloads: inline-dff `{+…+}` (escapes decoded), concatenated across hunks
49
+ * that are adjacent in the original (one's end offset is the next's start, so no baseline text lies
50
+ * between them), or unified-diff `+` lines. Authoritative enforcement belongs to the server. */
51
+ export declare function refuseReadingViewPatch(patch: string, format: "inline-dff" | "diff", baseline?: string): void;
52
+ /** Exact original-source spans, with untouched gaps omitted from the PATCH. The target the edits
53
+ * produce is reconstructed and checked against the baseline, so a generated header assembled from
54
+ * several spans is refused exactly as a whole-body write would be. */
55
+ export declare function documentEdits(source: SourceSnapshot, edits: SourceEdit[], exact?: boolean): DocumentPatchPayload;
56
+ /** One literal insertion at an original-source Unicode code-point boundary. */
57
+ export declare function documentInsertion(source: SourceSnapshot, at: number, text: string, exact?: boolean): DocumentPatchPayload;
58
+ /** Validate optional expected text, then use the same source-span compiler. */
21
59
  export declare function noteEdits(source: NoteSource, edits: NoteEdit[], mode?: "merge" | "exact"): NotePatch;
@@ -1,5 +1,200 @@
1
- import { documentEdits } from "../cli/notes/document.js";
2
- /** Validate optional expected text, then use the existing source-span compiler. */
1
+ /** Generated reading-view annotations are never saved as source. What is
2
+ * forbidden is NEW text that carries the generated header line
3
+ * (`<!-- notes-reading-view revision=… hash=…`). Deleting such a line, keeping
4
+ * one the note already has, or mentioning the marker in prose or a code block
5
+ * is allowed. Checked on raw inserted text before compilation (escaping would
6
+ * hide it) and on the insertion payloads of a caller-supplied patch. */
7
+ export const READING_VIEW_MARKER = "<!-- notes-reading-view";
8
+ export const READING_VIEW_HEADER = /^\s*<!-- notes-reading-view revision=/m;
9
+ export class ReadingViewMarkerRefused extends Error {
10
+ constructor(what) {
11
+ super(`${what} adds a generated reading-view marker header ("${READING_VIEW_MARKER} revision=…"); generated annotations are never saved as source`);
12
+ this.name = "ReadingViewMarkerRefused";
13
+ }
14
+ }
15
+ /** Inserted or replacement text only, never deletions or unchanged context. */
16
+ export function refuseReadingView(text, what) {
17
+ if (READING_VIEW_HEADER.test(text))
18
+ throw new ReadingViewMarkerRefused(what);
19
+ }
20
+ /** Whole-body replacement: only lines that are new relative to the baseline count, so a header the note already holds survives a write. */
21
+ export function refuseNewReadingViewLines(baseline, content, what) {
22
+ const kept = new Set(baseline.split("\n"));
23
+ for (const line of content.split("\n"))
24
+ if (READING_VIEW_HEADER.test(line) && !kept.has(line))
25
+ throw new ReadingViewMarkerRefused(what);
26
+ }
27
+ /** inline-dff escapes only (`\\ \n \r \t \[ \] \{ \} \+ \-`); anything else keeps its backslash. Never applied to unified-diff lines. */
28
+ const INLINE_ESCAPES = { "\\": "\\", n: "\n", r: "\r", t: "\t", "[": "[", "]": "]", "{": "{", "}": "}", "+": "+", "-": "-" };
29
+ const decodeInline = (text) => text.replace(/\\(.)/g, (whole, char) => INLINE_ESCAPES[char] ?? whole);
30
+ /** Apply the inline-dff subset this client emits (`@@ chars s:e @@` + one `~` line of `[-old-]`/`{+new+}`
31
+ * segments) to a baseline. null when the patch is outside that subset or its old text does not match. */
32
+ export function applyInlineDff(baseline, patch) {
33
+ const points = Array.from(baseline), lines = patch.split("\n");
34
+ let out = "", cursor = 0;
35
+ for (let i = 0; i < lines.length;) {
36
+ if (lines[i] === "") {
37
+ i++;
38
+ continue;
39
+ }
40
+ const header = /^@@ chars (\d+):(\d+) @@$/.exec(lines[i]), body = lines[i + 1];
41
+ if (!header || body === undefined || !body.startsWith("~ "))
42
+ return null;
43
+ const start = Number(header[1]), end = Number(header[2]);
44
+ if (start < cursor || end < start || end > points.length)
45
+ return null;
46
+ let rest = body.slice(2), old = "", added = "";
47
+ while (rest) {
48
+ const segment = /^(?:\[-((?:\\.|[^\\])*?)-\]|\{\+((?:\\.|[^\\])*?)\+\})/.exec(rest);
49
+ if (!segment)
50
+ return null;
51
+ if (segment[1] !== undefined)
52
+ old += decodeInline(segment[1]);
53
+ else
54
+ added += decodeInline(segment[2]);
55
+ rest = rest.slice(segment[0].length);
56
+ }
57
+ if (points.slice(start, end).join("") !== old)
58
+ return null;
59
+ out += points.slice(cursor, start).join("") + added;
60
+ cursor = end;
61
+ i += 2;
62
+ }
63
+ return out + points.slice(cursor).join("");
64
+ }
65
+ /** Apply a unified diff to a baseline, verifying context and removed lines. null when it does not apply cleanly. */
66
+ export function applyUnifiedDiff(baseline, patch) {
67
+ const src = baseline.split("\n"), lines = patch.split("\n"), out = [];
68
+ let at = 0, i = 0;
69
+ while (i < lines.length && (lines[i].startsWith("--- ") || lines[i].startsWith("+++ ")))
70
+ i++;
71
+ while (i < lines.length) {
72
+ if (lines[i] === "" && i === lines.length - 1)
73
+ break;
74
+ const hunk = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/.exec(lines[i]);
75
+ if (!hunk)
76
+ return null;
77
+ const index = hunk[2] === "0" ? Number(hunk[1]) : Number(hunk[1]) - 1;
78
+ if (index < at || index > src.length)
79
+ return null;
80
+ out.push(...src.slice(at, index));
81
+ at = index;
82
+ i++;
83
+ while (i < lines.length && !lines[i].startsWith("@@")) {
84
+ const line = lines[i++];
85
+ if (line.startsWith("\\"))
86
+ continue;
87
+ if (line === "") {
88
+ if (i === lines.length)
89
+ break;
90
+ return null;
91
+ }
92
+ const tag = line[0], text = line.slice(1);
93
+ if (tag === " " || tag === "-") {
94
+ if (src[at] !== text)
95
+ return null;
96
+ if (tag === " ")
97
+ out.push(text);
98
+ at++;
99
+ }
100
+ else if (tag === "+")
101
+ out.push(text);
102
+ else
103
+ return null;
104
+ }
105
+ }
106
+ out.push(...src.slice(at));
107
+ return out.join("\n");
108
+ }
109
+ /** Insertion payloads of an inline-dff patch, hunk by hunk with their original spans; null outside the parseable subset. */
110
+ function inlineInsertions(patch) {
111
+ const lines = patch.split("\n"), hunks = [];
112
+ for (let i = 0; i < lines.length;) {
113
+ if (lines[i] === "") {
114
+ i++;
115
+ continue;
116
+ }
117
+ const header = /^@@ chars (\d+):(\d+) @@$/.exec(lines[i]), body = lines[i + 1];
118
+ if (!header || body === undefined || !body.startsWith("~ "))
119
+ return null;
120
+ let rest = body.slice(2), added = "";
121
+ while (rest) {
122
+ const segment = /^(?:\[-((?:\\.|[^\\])*?)-\]|\{\+((?:\\.|[^\\])*?)\+\})/.exec(rest);
123
+ if (!segment)
124
+ return null;
125
+ if (segment[2] !== undefined)
126
+ added += decodeInline(segment[2]);
127
+ rest = rest.slice(segment[0].length);
128
+ }
129
+ hunks.push({ start: Number(header[1]), end: Number(header[2]), added });
130
+ i += 2;
131
+ }
132
+ return hunks;
133
+ }
134
+ /** A caller-supplied patch. With the baseline it was written against, the target is reconstructed and
135
+ * checked like a whole-body write (so a header split across hunks is seen assembled, and one the note
136
+ * already has may be re-added). Without a baseline, or when the patch does not apply to it, the check is
137
+ * BEST-EFFORT on the insertion payloads: inline-dff `{+…+}` (escapes decoded), concatenated across hunks
138
+ * that are adjacent in the original (one's end offset is the next's start, so no baseline text lies
139
+ * between them), or unified-diff `+` lines. Authoritative enforcement belongs to the server. */
140
+ export function refuseReadingViewPatch(patch, format, baseline) {
141
+ if (baseline !== undefined) {
142
+ const target = format === "diff" ? applyUnifiedDiff(baseline, patch) : applyInlineDff(baseline, patch);
143
+ if (target !== null) {
144
+ refuseNewReadingViewLines(baseline, target, "the patch");
145
+ return;
146
+ }
147
+ }
148
+ if (format === "diff") {
149
+ for (const line of patch.split("\n"))
150
+ if (line.startsWith("+") && !line.startsWith("+++ "))
151
+ refuseReadingView(line.slice(1), "the patch");
152
+ return;
153
+ }
154
+ const hunks = inlineInsertions(patch);
155
+ if (hunks === null) {
156
+ for (const match of patch.matchAll(/\{\+((?:\\[\s\S]|[^\\])*?)\+\}/g))
157
+ refuseReadingView(decodeInline(match[1]), "the patch");
158
+ return;
159
+ }
160
+ let run = "", previousEnd = -1;
161
+ for (const hunk of hunks) {
162
+ run = hunk.start === previousEnd ? run + hunk.added : hunk.added;
163
+ previousEnd = hunk.end;
164
+ refuseReadingView(run, "the patch");
165
+ }
166
+ }
167
+ function inlineLiteral(text) {
168
+ return text.replace(/[\\\n\r\t\[\]{}+\-]/g, char => char === "\n" ? "\\n" : char === "\r" ? "\\r" : char === "\t" ? "\\t" : `\\${char}`);
169
+ }
170
+ /** Exact original-source spans, with untouched gaps omitted from the PATCH. The target the edits
171
+ * produce is reconstructed and checked against the baseline, so a generated header assembled from
172
+ * several spans is refused exactly as a whole-body write would be. */
173
+ export function documentEdits(source, edits, exact = false) {
174
+ const points = Array.from(source.content);
175
+ let lastEnd = 0, lastStart = -1, target = "";
176
+ const hunks = [];
177
+ for (const edit of edits) {
178
+ if (!Number.isSafeInteger(edit.start) || !Number.isSafeInteger(edit.end) || edit.start < lastEnd
179
+ || edit.start <= lastStart || edit.end < edit.start || edit.end > points.length) {
180
+ throw new Error("Edit spans must be ordered and disjoint within the original source");
181
+ }
182
+ target += points.slice(lastEnd, edit.start).join("") + edit.text;
183
+ lastStart = edit.start;
184
+ lastEnd = edit.end;
185
+ const old = points.slice(edit.start, edit.end).join("");
186
+ if (old === edit.text)
187
+ continue;
188
+ hunks.push(`@@ chars ${edit.start}:${edit.end} @@\n~ ${old ? `[-${inlineLiteral(old)}-]` : ""}${edit.text ? `{+${inlineLiteral(edit.text)}+}` : ""}\n`);
189
+ }
190
+ refuseNewReadingViewLines(source.content, target + points.slice(lastEnd).join(""), "the edit");
191
+ return { format: "inline-dff", patch: hunks.join(""), baseRevision: source.revision, mode: exact ? "exact" : "merge" };
192
+ }
193
+ /** One literal insertion at an original-source Unicode code-point boundary. */
194
+ export function documentInsertion(source, at, text, exact = false) {
195
+ return documentEdits(source, [{ start: at, end: at, text }], exact);
196
+ }
197
+ /** Validate optional expected text, then use the same source-span compiler. */
3
198
  export function noteEdits(source, edits, mode = "exact") {
4
199
  const points = Array.from(source.content);
5
200
  for (const edit of edits) {
@@ -1,5 +1,41 @@
1
- /** Explicit-token adapter; the existing stream parser stays at its original location. */
2
- import { readNoteEvents as readEvents, type NoteEvent } from "../cli/notes/events.js";
3
- export type { Selection, Participant, NoteEvent } from "../cli/notes/events.js";
4
- export type NoteEventRequest = Parameters<typeof readEvents>[5];
1
+ export type NoteEventRequest = (url: string, options: {
2
+ token?: string | null;
3
+ headers?: Record<string, string>;
4
+ signal?: AbortSignal;
5
+ followRedirects?: boolean;
6
+ }) => Promise<Response>;
7
+ export type Selection = null | {
8
+ status: 'unresolved';
9
+ } | {
10
+ status: 'resolved';
11
+ anchor: number;
12
+ head: number;
13
+ start: number;
14
+ end: number;
15
+ unit: 'unicode-code-point';
16
+ text: string;
17
+ truncated: boolean;
18
+ };
19
+ export interface Participant {
20
+ client: string;
21
+ user: {
22
+ id: string;
23
+ name: string;
24
+ kind: 'human' | 'agent';
25
+ owner?: {
26
+ id: string;
27
+ name: string;
28
+ };
29
+ };
30
+ selection?: Selection;
31
+ }
32
+ export interface NoteEvent {
33
+ type: 'observation';
34
+ note: string;
35
+ hash: string;
36
+ observedAt: number;
37
+ participants: Participant[];
38
+ activityVersion: string;
39
+ }
40
+ /** Explicit-token adapter: no login files, telemetry or process state. */
5
41
  export declare function readNoteEvents(url: string, token: string, note: string, signal: AbortSignal, receive: (event: NoteEvent) => void, request?: NoteEventRequest): Promise<void>;
@@ -1,6 +1,59 @@
1
- /** Explicit-token adapter; the existing stream parser stays at its original location. */
2
- import { readNoteEvents as readEvents } from "../cli/notes/events.js";
1
+ /** Notes SSE parser over an injected request; the CLI supplies its own `requestRaw`. */
3
2
  import { httpResponse, HttpError } from "./http.js";
3
+ /** Fetch SSE with auth headers, abort/idle bounds, and no automatic replay across gaps. */
4
+ async function readEvents(url, token, note, signal, receive, request) {
5
+ const idle = new AbortController();
6
+ let timer;
7
+ const touch = () => { clearTimeout(timer); timer = setTimeout(() => idle.abort(new Error('Notes event stream timed out')), 45000); };
8
+ touch();
9
+ let reader;
10
+ try {
11
+ const res = await request(url, { token, headers: { Accept: 'text/event-stream' },
12
+ signal: AbortSignal.any([signal, idle.signal]), followRedirects: false });
13
+ if (!/^text\/event-stream(?:;|$)/i.test(res.headers.get('content-type') ?? '') || !res.body)
14
+ throw new Error('server does not support Notes events; upgrade the server');
15
+ reader = res.body.getReader();
16
+ const decoder = new TextDecoder('utf-8', { fatal: true });
17
+ let buffer = '', data = [], frameSize = 0;
18
+ while (!signal.aborted) {
19
+ const { done, value } = await reader.read();
20
+ if (done)
21
+ throw new Error('Notes event stream disconnected; run --linger again for a fresh snapshot');
22
+ touch();
23
+ buffer += decoder.decode(value, { stream: true });
24
+ if (buffer.length > 4_000_000)
25
+ throw new Error('Notes event frame exceeds limit');
26
+ let newline;
27
+ while ((newline = buffer.indexOf('\n')) >= 0) {
28
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
29
+ buffer = buffer.slice(newline + 1);
30
+ if (line.startsWith('data:')) {
31
+ const part = line.slice(5).replace(/^ /, '');
32
+ frameSize += part.length;
33
+ if (frameSize > 4_000_000)
34
+ throw new Error('Notes event frame exceeds limit');
35
+ data.push(part);
36
+ }
37
+ else if (!line && data.length) {
38
+ const event = JSON.parse(data.join('\n'));
39
+ data = [];
40
+ frameSize = 0;
41
+ if (event.type === 'error')
42
+ throw new Error(`Notes event stream ended (${String(event.error)})`);
43
+ if (event.type !== 'observation' || event.note !== note || !/^sha256:[a-f0-9]{64}$/.test(event.hash) ||
44
+ !Array.isArray(event.participants) || typeof event.activityVersion !== 'string')
45
+ throw new Error('invalid Notes event response');
46
+ receive(event);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ finally {
52
+ clearTimeout(timer);
53
+ await reader?.cancel().catch(() => { });
54
+ }
55
+ }
56
+ /** Explicit-token adapter: no login files, telemetry or process state. */
4
57
  export function readNoteEvents(url, token, note, signal, receive, request) {
5
58
  return readEvents(url, token, note, signal, receive, request ?? (async (url, options = {}) => {
6
59
  const response = await httpResponse(url, { token: options.token, headers: options.headers, signal: options.signal, redirect: "manual" });