@appsoftwareltd/etherpk-mcp 0.34.0 → 0.36.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.
package/dist/main.js CHANGED
@@ -820,7 +820,7 @@ function looksLikeAgentSetupCode(value) {
820
820
  }
821
821
  var package_default = {
822
822
  name: "@appsoftwareltd/etherpk-mcp",
823
- version: "0.34.0",
823
+ version: "0.36.0",
824
824
  license: "Elastic-2.0",
825
825
  description: "EtherPK Headless Client: an MCP server over a synced knowledge graph, run beside the agent on the user's own machine.",
826
826
  type: "module",
@@ -4047,6 +4047,19 @@ function indentChars(line) {
4047
4047
  return leading(line).length;
4048
4048
  }
4049
4049
  /**
4050
+ * How far a whitespace-only line at `indent` moves. One that closed a branch lands past the node
4051
+ * still open (`open`) and no deeper than where the closed branch now starts, so it closes the same
4052
+ * branches once they have moved; else, and when no column lies between the two (only off the
4053
+ * two-space grid, where a bullet can move right), it moves with the bullet that owns it.
4054
+ */
4055
+ function blankDelta(indent, closed, open, owner) {
4056
+ const byOwner = owner ? owner.written - owner.raw : 0;
4057
+ if (!closed) return byOwner;
4058
+ const floor = open ? open.written + 1 : 0;
4059
+ if (floor > closed.written) return byOwner;
4060
+ return Math.min(Math.max(indent, floor), closed.written) - indent;
4061
+ }
4062
+ /**
4050
4063
  * The structural walk under both {@link outlineLines} and {@link normaliseIndentUnit}: visits each
4051
4064
  * line in order with the node stack resolved, reporting the line's owner (the nearest open bullet
4052
4065
  * whose block the line is inside) and the delta that would put it on the grid.
@@ -4066,8 +4079,11 @@ function walk(lines, blocks, measure, visit) {
4066
4079
  for (const b of blocks) starts.set(b.start, b);
4067
4080
  const stack = [];
4068
4081
  const top = () => stack.length ? stack[stack.length - 1] : null;
4082
+ /** Close the nodes at or past `indent`, and return the shallowest of them, if any. */
4069
4083
  const popTo = (indent) => {
4070
- while (stack.length && stack[stack.length - 1].raw >= indent) stack.pop();
4084
+ let closed = null;
4085
+ while (stack.length && stack[stack.length - 1].raw >= indent) closed = stack.pop();
4086
+ return closed;
4071
4087
  };
4072
4088
  /** The nearest open bullet on the stack, or null when only prose nodes (or nothing) remain. */
4073
4089
  const owningBullet = () => {
@@ -4086,13 +4102,13 @@ function walk(lines, blocks, measure, visit) {
4086
4102
  const block = starts.get(i);
4087
4103
  const span = block ? block.end - i + 1 : 1;
4088
4104
  const indent = measure(line);
4089
- popTo(indent);
4105
+ const closed = popTo(indent);
4090
4106
  if (isBlank(line) && !block) {
4091
4107
  const owner = owningBullet();
4092
4108
  visit(i, {
4093
4109
  depth: top()?.depth ?? 0,
4094
4110
  owner: owner ? owner.bullet : -1,
4095
- delta: owner ? owner.written - owner.raw : 0,
4111
+ delta: blankDelta(indent, closed, top(), owner),
4096
4112
  span
4097
4113
  });
4098
4114
  continue;
@@ -4185,8 +4201,86 @@ function relead(line, within, delta) {
4185
4201
  return " ".repeat(Math.max(0, col + delta)) + line.slice(chars);
4186
4202
  }
4187
4203
  /**
4204
+ * A section shifted left as a whole when it starts with a bullet indented with no bullet above it:
4205
+ * `## H` then ` - a` then ` - b` becomes `## H`, `- a`, ` - b`. A heading nests what follows
4206
+ * by its `#` level, not by indentation, and the editor writes the bullets under a heading at
4207
+ * column 0; to the outline walk an indented bullet would be the heading's child instead, and stay
4208
+ * indented with no parent.
4209
+ *
4210
+ * A section starts after a heading at column 0 with a bullet and runs to the next non-blank line at
4211
+ * column 0. It moves only when no line in it is shallower than that first bullet, and then every
4212
+ * line moves left by the bullet's indent (a fenced block only up to its fence column, so code keeps
4213
+ * its own indentation). That keeps every line where it was relative to every other, as the outline
4214
+ * reads them: a sub-heading or a paragraph beside the bullets stays beside them, never inside a
4215
+ * bullet's block. A section with a shallower line, one that a fenced block crosses, or one that
4216
+ * holds a fence line the editor pairs with nothing is left to the walk, as before: CommonMark may
4217
+ * read such a fence line as a fence the shift would open or close differently. Returns `lines`
4218
+ * itself when nothing moves.
4219
+ */
4220
+ function dedentHeadingSections(lines, blocks = fencedBlocks(lines)) {
4221
+ const first = frontmatterLines(lines);
4222
+ let out = null;
4223
+ const at = (i) => (out ?? lines)[i];
4224
+ for (let h = first; h < lines.length; h++) {
4225
+ if (!isHeading(at(h)) || indentColumns(at(h)) > 0 || insideBlock(blocks, h)) continue;
4226
+ const section = sectionUnder(at, lines.length, h);
4227
+ if (!section || !movable(at, lines, blocks, section)) continue;
4228
+ out ??= lines.slice();
4229
+ shiftSection(out, blocks, section);
4230
+ }
4231
+ return out ?? lines;
4232
+ }
4233
+ /**
4234
+ * The section after the heading on line `h`: from its first non-blank line, which must be a bullet
4235
+ * indented past column 0, to the next non-blank line at column 0. Null when there is none to move.
4236
+ */
4237
+ function sectionUnder(at, length, h) {
4238
+ let start = h + 1;
4239
+ while (start < length && isBlank(at(start))) start++;
4240
+ if (start >= length || !isBullet$1(at(start))) return null;
4241
+ let end = start;
4242
+ while (end < length && (isBlank(at(end)) || indentColumns(at(end)) > 0)) end++;
4243
+ return end === start ? null : {
4244
+ start,
4245
+ end,
4246
+ shift: indentColumns(at(start))
4247
+ };
4248
+ }
4249
+ /** Whether a section moves: nothing in it shallower than its first bullet, no fenced block across its edges, no loose fence line. */
4250
+ function movable(at, lines, blocks, { start, end, shift }) {
4251
+ for (let k = start; k < end; k++) if (!isBlank(at(k)) && indentColumns(at(k)) < shift) return false;
4252
+ if (blocks.some((b) => b.start < start && b.end >= start || b.start < end && b.end >= end)) return false;
4253
+ return !holdsLooseFence(lines, blocks, start, end);
4254
+ }
4255
+ /** Move every line of the section left by its shift, in place: a fenced block only up to its fence column. */
4256
+ function shiftSection(out, blocks, { start, end, shift }) {
4257
+ for (let k = start; k < end; k++) {
4258
+ const block = blocks.find((b) => b.start === k);
4259
+ if (block) {
4260
+ const within = indentColumns(out[k]);
4261
+ for (let j = k; j <= block.end; j++) out[j] = relead(out[j], within, -shift);
4262
+ k = block.end;
4263
+ continue;
4264
+ }
4265
+ out[k] = relead(out[k], Infinity, -shift);
4266
+ }
4267
+ }
4268
+ /** A tilde fence line: text to the editor, which pairs backtick fences only, but a fence to CommonMark. */
4269
+ var TILDE_FENCE = /^\s*(?:-\s)?~{3,}/;
4270
+ /** Whether a line from `start` to `end` (exclusive) is a fence line no fenced block pairs. */
4271
+ function holdsLooseFence(lines, blocks, start, end) {
4272
+ for (let k = start; k < end; k++) if ((fenceLineInfo(lines[k]) !== null || TILDE_FENCE.test(lines[k])) && !insideBlock(blocks, k)) return true;
4273
+ return false;
4274
+ }
4275
+ /** Whether line `i` is inside a fenced block, its fences included. */
4276
+ function insideBlock(blocks, i) {
4277
+ return blocks.some((b) => i >= b.start && i <= b.end);
4278
+ }
4279
+ /**
4188
4280
  * The document with every bullet on the Indent Unit grid: each bullet one unit under its parent
4189
- * (a top-level bullet at column 0, over-nesting collapsed), its continuation lines, soft lines and
4281
+ * (a top-level bullet at column 0, over-nesting collapsed, and the section under a top-level
4282
+ * heading shifted to column 0 when it starts indented: {@link dedentHeadingSections}), its
4283
+ * continuation lines, soft lines and
4190
4284
  * fenced block moved by the same amount so their indentation beyond the content column is kept
4191
4285
  * (an indented code block inside a bullet stays code). Tabs in leading whitespace become columns
4192
4286
  * (inside a fenced block only up to the fence column: a tab in the code is code); a line owned
@@ -4194,7 +4288,14 @@ function relead(line, within, delta) {
4194
4288
  * the grid comes back byte-identical, so callers may compare by reference.
4195
4289
  */
4196
4290
  function normaliseIndentUnit(text) {
4197
- const lines = text.split("\n");
4291
+ const split = text.split("\n");
4292
+ const once = regrid(dedentHeadingSections(split));
4293
+ const sections = dedentHeadingSections(once);
4294
+ const lines = sections === once ? once : regrid(sections);
4295
+ return lines === split ? text : lines.join("\n");
4296
+ }
4297
+ /** The walk's half of {@link normaliseIndentUnit}: `lines` with every bullet on the grid, or `lines` itself when none moves. */
4298
+ function regrid(lines) {
4198
4299
  const out = lines.slice();
4199
4300
  const frontmatter = frontmatterLines(lines);
4200
4301
  let changed = false;
@@ -4209,7 +4310,7 @@ function normaliseIndentUnit(text) {
4209
4310
  }
4210
4311
  }
4211
4312
  });
4212
- return changed ? out.join("\n") : text;
4313
+ return changed ? out : lines;
4213
4314
  }
4214
4315
  // ../client/src/lib/document/block-model.ts
4215
4316
  /**
@@ -14806,118 +14907,520 @@ function parseImageDisplaySizeHint(alt) {
14806
14907
  }
14807
14908
  return parsed;
14808
14909
  }
14809
- // ../client/src/lib/document/outliner.ts
14810
- function lineIndent(line) {
14811
- return line.length - line.trimStart().length;
14812
- }
14813
- function isBulletLine(line) {
14814
- return /^-\s/.test(line.trimStart());
14815
- }
14816
- /** A bullet whose content is `[ ]` / `[x]`; undefined if not a task. */
14817
- function taskDone(line) {
14818
- const m = /^-\s+\[([ xX])\]/.exec(line.trimStart());
14819
- return m ? m[1].toLowerCase() === "x" : void 0;
14910
+ // ../client/src/lib/storage/fs/asset-store.ts
14911
+ /**
14912
+ * The **Asset store** over a {@link DirectoryAdapter}: uploads land as binary files
14913
+ * under `assets/`, named `kebab-stem.<contenthash>.ext` (DESIGN.md → On-disk layout).
14914
+ * Identical bytes de-duplicate to one file **by content and extension alone** - the stem is
14915
+ * display, not identity - so the same file added again under a different name references the
14916
+ * one already stored rather than writing a second copy. Built on the same File-System seam as
14917
+ * {@link createFilesystemDocumentStore}, so the pure naming/dedup logic is Node-testable
14918
+ * over the in-memory adapter before any browser code runs.
14919
+ *
14920
+ * Assets are referenced from documents by a relative path — `../assets/<name>` — which
14921
+ * resolves from any journal entry or page (both sit one level under the graph root,
14922
+ * the Logseq convention). `resolve` reads those bytes back and hands out an object URL plus
14923
+ * the name and MIME type a download or a viewer needs; the URLs are cached per asset and
14924
+ * revoked on {@link AssetStore.dispose}.
14925
+ *
14926
+ * Remote (S3) upload and per-graph access control are deferred (DESIGN.md → Server
14927
+ * Backend); this is the Filesystem Backend path only.
14928
+ */
14929
+ /** Extensions rendered inline as images (everything else renders as a download link). */
14930
+ var IMAGE_EXTS = /* @__PURE__ */ new Set([
14931
+ "png",
14932
+ "jpg",
14933
+ "jpeg",
14934
+ "gif",
14935
+ "webp",
14936
+ "svg",
14937
+ "avif",
14938
+ "bmp"
14939
+ ]);
14940
+ /** A doc-relative asset reference: optional `../` hops, then `assets/<name>`. */
14941
+ var ASSET_REF$1 = /^(?:\.\.\/)*assets\/(.+)$/;
14942
+ /**
14943
+ * An asset could not be fetched just now: the connection failed, or the server answered with a
14944
+ * status that means "try again". It says nothing about whether the file exists, so something
14945
+ * showing the file asks again rather than calling it missing. `status` is the server's answer,
14946
+ * absent when the connection failed before there was one.
14947
+ */
14948
+ var AssetUnavailableError = class extends Error {
14949
+ name = "AssetUnavailableError";
14950
+ status;
14951
+ constructor(message, options = {}) {
14952
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
14953
+ this.status = options.status;
14954
+ }
14955
+ };
14956
+ /**
14957
+ * An asset arrived, but not as it was stored: the server offered a different number of chunks than
14958
+ * its encrypted metadata records, or the joined bytes do not match the size or hash recorded there.
14959
+ * Each chunk is authenticated on its own, so this is what catches a file cut short, or a reuse
14960
+ * answer that points at a different file (ADR 0027, amended 2026-10-05). The bytes are never
14961
+ * handed over. Distinct from a missing file (`null`), which is gone, and from an unavailable one,
14962
+ * which may come good by itself.
14963
+ */
14964
+ var AssetIntegrityError = class extends Error {
14965
+ name = "AssetIntegrityError";
14966
+ constructor(message = "This file did not arrive complete, so it was not opened. Try again in a moment.") {
14967
+ super(message);
14968
+ }
14969
+ };
14970
+ /** Split a file name into its stem and lower-cased extension (`''` ext when there is none). */
14971
+ function splitNameExt(fileName) {
14972
+ const dot = fileName.lastIndexOf(".");
14973
+ if (dot <= 0) return {
14974
+ stem: fileName,
14975
+ ext: ""
14976
+ };
14977
+ return {
14978
+ stem: fileName.slice(0, dot),
14979
+ ext: fileName.slice(dot + 1).toLowerCase()
14980
+ };
14820
14981
  }
14821
- /** Length of the bullet marker incl. its trailing space: `- ` (2) or `- [ ] ` (6). */
14822
- function markerLength(line) {
14823
- const indent = lineIndent(line);
14824
- const rest = line.slice(indent);
14825
- const task = /^-\s+\[[ xX]\]\s?/.exec(rest);
14826
- if (task) return task[0].length;
14827
- const bullet = /^-\s/.exec(rest);
14828
- return bullet ? bullet[0].length : 0;
14982
+ /** True when `ext` (with or without a leading dot) names an inline-rendered image format. */
14983
+ function isImageExt(ext) {
14984
+ return IMAGE_EXTS.has(ext.replace(/^\./, "").toLowerCase());
14829
14985
  }
14830
- /** Offset of a line's content: past its indent and, on a bullet, past the `- ` / `- [ ] ` marker. */
14831
- function contentStart(line) {
14832
- return lineIndent(line) + markerLength(line);
14986
+ /** The video formats the app plays, by extension ([[2026-11-18 Audio And Video Players]]). */
14987
+ var VIDEO_EXTS = ["webm", "mp4"];
14988
+ /** The audio formats the app plays, by extension. */
14989
+ var AUDIO_EXTS = [
14990
+ "mp3",
14991
+ "m4a",
14992
+ "wav",
14993
+ "ogg",
14994
+ "opus",
14995
+ "flac"
14996
+ ];
14997
+ /** Whether a file with this extension (with or without a leading dot) is played, and as what. */
14998
+ function mediaKindOfExt(ext) {
14999
+ const bare = ext.replace(/^\./, "").toLowerCase();
15000
+ if (VIDEO_EXTS.includes(bare)) return "video";
15001
+ if (AUDIO_EXTS.includes(bare)) return "audio";
15002
+ return null;
14833
15003
  }
14834
- /** The bullet's content (everything after the marker). `""` for an empty bullet. */
14835
- function bulletContent(line) {
14836
- return line.slice(contentStart(line));
15004
+ /** The on-disk asset name: `kebab-stem.<hash>.ext` (stem falls back to `asset` when slugging empties it). */
15005
+ function assetFileName(originalName, hash) {
15006
+ const { stem, ext } = splitNameExt(originalName);
15007
+ const slug = publishSlug(stem) || "asset";
15008
+ return ext ? `${slug}.${hash}.${ext}` : `${slug}.${hash}`;
14837
15009
  }
14838
- /** A heading line (`#`…`######` + space), tolerant of leading indent — matches the block model. */
14839
- function isHeadingLine(line) {
14840
- return /^#{1,6}\s/.test(line.trimStart());
15010
+ /** The de-duplication key: content plus extension. The stem is display, not identity. */
15011
+ function contentKey(hash, ext) {
15012
+ return `${hash}.${ext}`;
14841
15013
  }
14842
- /** Map from a fenced block's opener line index to the block, for O(1) "does a fence start here?". */
14843
- function fenceStartMap(blocks) {
14844
- const m = /* @__PURE__ */ new Map();
14845
- for (const b of blocks) m.set(b.start, b);
14846
- return m;
15014
+ /**
15015
+ * An on-disk asset name with its content hash taken back out — `q3-report.a1b2c3d4.pdf` reads as
15016
+ * `q3-report.pdf`. What a download is called and what titles an asset tab, so neither shows a
15017
+ * user a hash they never typed. A name this store did not write is returned unchanged.
15018
+ */
15019
+ function displayAssetName(fileName) {
15020
+ const parsed = assetHashFromName(fileName);
15021
+ if (!parsed) return fileName;
15022
+ const stem = fileName.slice(0, fileName.length - `.${parsed.hash}`.length - (parsed.ext ? parsed.ext.length + 1 : 0));
15023
+ return parsed.ext ? `${stem}.${parsed.ext}` : stem;
14847
15024
  }
14848
15025
  /**
14849
- * The branch rooted at line `i`: `i` plus all following lines more indented than it — its
14850
- * descendants and continuation lines. **Fence-opaque** (ADR 0021): a fenced block deeper than the
14851
- * root is swallowed whole, so its internal blank lines don't truncate the branch. **Indent decides
14852
- * blankness** (ADR 0021): a whitespace-only line is judged by its indentation like any other line —
14853
- * an indented soft line stays in the branch; a flush-left empty line (or one at/left of the root)
14854
- * ends it, as do a heading and any same-or-shallower content line.
15026
+ * MIME types for the formats the app itself renders, plus the handful a browser needs told about
15027
+ * to do anything sensible with a download. Deliberately small and deliberately **empty for
15028
+ * anything else**: a wrong type is worse than none, because a wrong one is acted on. The
15029
+ * Filesystem Backend has nowhere else to learn a type from — unlike the Server Backend, which
15030
+ * carries the uploader's own MIME type inside the encrypted asset metadata.
14855
15031
  */
14856
- function branchRange(lines, i, blocks = fencedBlocks(lines)) {
14857
- return {
14858
- start: i,
14859
- end: branchEnd$1(lines, i, fenceStartMap(blocks))
14860
- };
15032
+ var MIME_TYPES = {
15033
+ png: "image/png",
15034
+ jpg: "image/jpeg",
15035
+ jpeg: "image/jpeg",
15036
+ gif: "image/gif",
15037
+ webp: "image/webp",
15038
+ svg: "image/svg+xml",
15039
+ avif: "image/avif",
15040
+ bmp: "image/bmp",
15041
+ pdf: "application/pdf",
15042
+ epub: "application/epub+zip",
15043
+ txt: "text/plain",
15044
+ csv: "text/csv",
15045
+ json: "application/json",
15046
+ md: "text/markdown",
15047
+ mp3: "audio/mpeg",
15048
+ m4a: "audio/mp4",
15049
+ wav: "audio/wav",
15050
+ ogg: "audio/ogg",
15051
+ opus: "audio/ogg",
15052
+ flac: "audio/flac",
15053
+ mp4: "video/mp4",
15054
+ webm: "video/webm",
15055
+ zip: "application/zip"
15056
+ };
15057
+ /** The MIME type for a file extension (with or without a leading dot), or `''` when unknown. */
15058
+ function mimeTypeForExt(ext) {
15059
+ return MIME_TYPES[ext.replace(/^\./, "").toLowerCase()] ?? "";
14861
15060
  }
14862
- /** The last line of the branch rooted at line `i` ({@link branchRange}), given the fence openers. */
14863
- function branchEnd$1(lines, i, starts) {
14864
- const root = lineIndent(lines[i]);
14865
- const own = starts.get(i);
14866
- let end = own ? own.end : i;
14867
- let j = end + 1;
14868
- while (j < lines.length) {
14869
- const b = starts.get(j);
14870
- if (b) {
14871
- if (lineIndent(lines[b.start]) > root) {
14872
- end = b.end;
14873
- j = b.end + 1;
14874
- continue;
14875
- }
14876
- break;
14877
- }
14878
- const line = lines[j];
14879
- if (isHeadingLine(line)) break;
14880
- if (lineIndent(line) <= root) break;
14881
- end = j;
14882
- j++;
15061
+ /**
15062
+ * The on-disk name referenced by a doc-relative asset ref, or `null` if `ref` is not an asset
15063
+ * reference. A reference whose name decodes to anything but one file inside `assets/`, or does not
15064
+ * decode at all, is not one: it can never name a file on disk (see `isSafeAssetName`).
15065
+ */
15066
+ function assetNameFromRef(ref) {
15067
+ const clean = ref.split(/[?#]/)[0];
15068
+ const match = ASSET_REF$1.exec(clean);
15069
+ if (!match) return null;
15070
+ let name;
15071
+ try {
15072
+ name = decodeURIComponent(match[1]);
15073
+ } catch {
15074
+ return null;
14883
15075
  }
14884
- return end;
14885
- }
14886
- // ../client/src/lib/document/publish/markdown/list-item-end-rule.ts
14887
- /** The lines this parse ended a list item at. */
14888
- function endedAt(state) {
14889
- const env = state.env;
14890
- env.etherpkListItemEnds ??= /* @__PURE__ */ new Set();
14891
- return env.etherpkListItemEnds;
14892
- }
14893
- /** A line whose indentation, if any, is spaces only. */
14894
- var SPACE_INDENTED = /^ *\S/;
14895
- /** An empty bullet as the editor reads one: a dash and whitespace, indented with spaces. */
14896
- var EMPTY_BULLET = /^ *-[ \t]+$/;
14897
- /** The block rules whose reading of a line this rule ended an item at is never the editor's. */
14898
- var READ_AS_A_PARAGRAPH = [
14899
- "lheading",
14900
- "reference",
14901
- "html_block",
14902
- "code"
14903
- ];
14904
- /** Line `line` as typed, from its true start: inside a quote `bMarks` starts after the `>`. */
14905
- function rawLine(state, line) {
14906
- const end = state.eMarks[line];
14907
- return state.src.slice(state.src.lastIndexOf("\n", end - 1) + 1, end);
15076
+ return isSafeAssetName(name) ? name : null;
14908
15077
  }
14909
15078
  /**
14910
- * The first line of the innermost list item the parse is inside, or null when it is in no item or
14911
- * inside a quote. Walking back over the tokens pushed so far, the openers not yet closed are the
14912
- * containers the parse is inside, innermost first. A block being read has not pushed its own tokens.
15079
+ * The markdown to embed a saved asset: an inline image, a recording in the same image form (the
15080
+ * editor draws a player under it, `media-line.ts`), or a plain link that downloads on click.
15081
+ * For an image, an optional `displaySize` (e.g. `300` or `300x200`) is added as a `|` display-size
15082
+ * hint; the caller is responsible for passing a valid spec (see `normalizeDisplaySize`).
14913
15083
  */
14914
- function openItemLine(state) {
14915
- let closed = 0;
14916
- let item = null;
14917
- for (let i = state.tokens.length - 1; i >= 0; i--) {
14918
- const token = state.tokens[i];
14919
- if (token.nesting === -1) closed++;
14920
- else if (token.nesting === 1) {
15084
+ function buildAssetMarkdown(asset, displaySize) {
15085
+ if (!asset.isImage) return `${mediaKindOfExt(splitNameExt(asset.ref.split(/[?#]/)[0]).ext) !== null ? "!" : ""}[${asset.stem}](${asset.ref})`;
15086
+ return `![${displaySize ? `${asset.stem}|${displaySize}` : asset.stem}](${asset.ref})`;
15087
+ }
15088
+ /** First 8 hex chars of the SHA-256 of the bytes — the content hash in the asset name. */
15089
+ async function contentHash(bytes) {
15090
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
15091
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 8);
15092
+ }
15093
+ function createAssetStore(adapter) {
15094
+ const urlCache = /* @__PURE__ */ new Map();
15095
+ /**
15096
+ * Content key → the on-disk name already holding those bytes. Built from `assets/` on the
15097
+ * first save (so a store that only ever resolves never pays for the listing) and maintained
15098
+ * on every write after that.
15099
+ *
15100
+ * This is what keeps the [[Asset]] guarantee honest on this backend: identity is content,
15101
+ * not the name it was added under. Keying the write on the whole file name instead — which
15102
+ * is what this did before — stored the same bytes twice whenever the stem differed.
15103
+ */
15104
+ let contentIndex;
15105
+ /**
15106
+ * The index, listed once. The promise is what is kept, not the map: saves run several at once
15107
+ * (an upload's pool), and each one that found no map yet used to list the folder into a map of
15108
+ * its own. The last listing to finish replaced the rest, and every write recorded in the others
15109
+ * was forgotten, so adding the same files again stored and reported most of them as new.
15110
+ */
15111
+ function assetsByContent() {
15112
+ contentIndex ??= listByContent().catch((err) => {
15113
+ contentIndex = void 0;
15114
+ throw err;
15115
+ });
15116
+ return contentIndex;
15117
+ }
15118
+ async function listByContent() {
15119
+ const index = /* @__PURE__ */ new Map();
15120
+ for (const { name } of await adapter.list("assets")) {
15121
+ const parsed = assetHashFromName(name);
15122
+ if (parsed && !index.has(contentKey(parsed.hash, parsed.ext))) index.set(contentKey(parsed.hash, parsed.ext), name);
15123
+ }
15124
+ return index;
15125
+ }
15126
+ /**
15127
+ * Content key → the save storing those bytes right now. Two saves of the same bytes at once (a
15128
+ * file dropped twice in one batch) both missed the index and wrote the file twice, under each
15129
+ * name. The second waits for the first and references its file instead.
15130
+ */
15131
+ const storing = /* @__PURE__ */ new Map();
15132
+ /** The file holding `bytes` under `key`: one the folder already has, or one written now. */
15133
+ async function store(key, name, hash, bytes) {
15134
+ const index = await assetsByContent();
15135
+ const held = index.get(key);
15136
+ if (held !== void 0 && await adapter.exists("assets", held)) return {
15137
+ fileName: held,
15138
+ reused: true
15139
+ };
15140
+ const fileName = assetFileName(name, hash);
15141
+ await adapter.writeBinary("assets", fileName, bytes);
15142
+ index.set(key, fileName);
15143
+ return {
15144
+ fileName,
15145
+ reused: false
15146
+ };
15147
+ }
15148
+ return {
15149
+ async save({ name, bytes }, onBytes) {
15150
+ const hash = await contentHash(bytes);
15151
+ const { stem, ext } = splitNameExt(name);
15152
+ const key = contentKey(hash, ext);
15153
+ let stored;
15154
+ const pending = storing.get(key);
15155
+ if (pending) stored = await pending.then((fileName) => ({
15156
+ fileName,
15157
+ reused: true
15158
+ }), () => store(key, name, hash, bytes));
15159
+ else {
15160
+ const work = store(key, name, hash, bytes);
15161
+ storing.set(key, work.then((done) => done.fileName));
15162
+ try {
15163
+ stored = await work;
15164
+ } finally {
15165
+ storing.delete(key);
15166
+ }
15167
+ }
15168
+ onBytes?.(bytes.length);
15169
+ return {
15170
+ ref: `../assets/${stored.fileName}`,
15171
+ name: stored.fileName,
15172
+ stem: publishSlug(stem) || "asset",
15173
+ isImage: isImageExt(ext),
15174
+ ...stored.reused ? { reused: true } : {}
15175
+ };
15176
+ },
15177
+ async readBytes(ref) {
15178
+ const assetName = assetNameFromRef(ref);
15179
+ if (!assetName) return null;
15180
+ const { ext } = splitNameExt(assetName);
15181
+ try {
15182
+ const { bytes } = await adapter.readBinary("assets", assetName);
15183
+ return {
15184
+ bytes,
15185
+ name: displayAssetName(assetName),
15186
+ type: mimeTypeForExt(ext)
15187
+ };
15188
+ } catch {
15189
+ return null;
15190
+ }
15191
+ },
15192
+ async resolve(ref) {
15193
+ const assetName = assetNameFromRef(ref);
15194
+ if (!assetName) return null;
15195
+ const { ext } = splitNameExt(assetName);
15196
+ const meta = {
15197
+ name: displayAssetName(assetName),
15198
+ type: mimeTypeForExt(ext)
15199
+ };
15200
+ const cached = urlCache.get(assetName);
15201
+ if (cached) return {
15202
+ url: cached,
15203
+ ...meta
15204
+ };
15205
+ let content;
15206
+ try {
15207
+ content = await adapter.readBinary("assets", assetName);
15208
+ } catch {
15209
+ return null;
15210
+ }
15211
+ const url = URL.createObjectURL(new Blob([content.bytes], meta.type ? { type: meta.type } : {}));
15212
+ urlCache.set(assetName, url);
15213
+ return {
15214
+ url,
15215
+ ...meta
15216
+ };
15217
+ },
15218
+ dispose() {
15219
+ for (const url of urlCache.values()) URL.revokeObjectURL(url);
15220
+ urlCache.clear();
15221
+ },
15222
+ renamed(from, to) {
15223
+ const url = urlCache.get(from);
15224
+ if (url) URL.revokeObjectURL(url);
15225
+ urlCache.delete(from);
15226
+ const parsed = assetHashFromName(to);
15227
+ if (parsed) contentIndex?.then((index) => index.set(contentKey(parsed.hash, parsed.ext), to)).catch(() => {});
15228
+ }
15229
+ };
15230
+ }
15231
+ // ../client/src/lib/document/markdown-link-target.ts
15232
+ /**
15233
+ * The one definition of markdown link syntax, shared by every reader of one.
15234
+ *
15235
+ * Ten places used to spell this out, and each spelled the destination `[^)\s]+`, which stops at
15236
+ * the FIRST closing parenthesis. That is wrong the moment a file name contains one, and imported
15237
+ * attachments contain them all the time - `Quote_320_from_Garden_Fencing_ltd_(1)_1700000000000_0.pdf`
15238
+ * has the shape they take. Every reader then saw the same truncated target, so the link styling and the
15239
+ * download and delete controls landed in the middle of the text, and the [[Local Mirror]] reported
15240
+ * the stub as a document link to an attachment the graph plainly had (2026-09-10).
15241
+ *
15242
+ * Sharing only the destination would have left the same duplication one layer down: nine call
15243
+ * sites each re-spelling `\[([^\]]*)\]\(` around it. So the whole link is defined here, once, as
15244
+ * regex source with **named groups** - which is also what lets a caller read `groups.target`
15245
+ * without counting brackets, and what stops the next change to the grammar from silently missing
15246
+ * a site.
15247
+ *
15248
+ * Source rather than a compiled RegExp, because what varies between callers is not the link: it is
15249
+ * the anchoring and what surrounds it. One wants a whole line to be nothing but an image, one
15250
+ * wants a Logseq `{:height 100}` suffix after it, one scans prose. Each composes what it needs.
15251
+ *
15252
+ * CommonMark's rule for the unbracketed destination form: no whitespace, and parentheses only in
15253
+ * balanced pairs. Nesting is bounded here at two levels, one more than any real file name uses,
15254
+ * because an unbounded version needs a recursive parser and would buy nothing.
15255
+ *
15256
+ * Pure: strings of regex source, no DOM, no CodeMirror.
15257
+ */
15258
+ /**
15259
+ * The destination grammar. `excluded` adds characters the caller's context forbids on top of
15260
+ * whitespace and parentheses - an HTML attribute cannot hold its own quote, and a target inside
15261
+ * markdown brackets cannot hold `]`.
15262
+ */
15263
+ function linkTargetPattern(excluded = "") {
15264
+ const plain = `[^\\s()${excluded}]`;
15265
+ return `(?:${plain}|\\((?:${plain}|\\(${plain}*\\))*\\))+`;
15266
+ }
15267
+ /**
15268
+ * A whole markdown link or image, as regex source with named groups.
15269
+ *
15270
+ * - `bang` - `!` for an image, empty for a link.
15271
+ * - `label` - the alt text or link text, size hint and all.
15272
+ * - `target` - the destination.
15273
+ *
15274
+ * A regex may not repeat a group name, so compose this **once** per pattern. Wrap it in a group of
15275
+ * your own where you need the whole link as one capture.
15276
+ */
15277
+ var MARKDOWN_LINK = `(?<bang>!?)\\[(?<label>(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*)\\]\\((?<target>${linkTargetPattern()})\\)`;
15278
+ /** A match's groups, typed. Every {@link MARKDOWN_LINK} match has all three. */
15279
+ function linkGroups(match) {
15280
+ return match.groups;
15281
+ }
15282
+ new RegExp(`^\\s*${MARKDOWN_LINK}\\s*$`);
15283
+ new RegExp(`^(\\s*-\\s(?:\\[[ xX]\\]\\s)?)${MARKDOWN_LINK}\\s*$`);
15284
+ // ../client/src/lib/document/media-line.ts
15285
+ /**
15286
+ * What a **media line** is: a line whose only content is `![alt](target)` over an audio or video
15287
+ * [[Asset]], which the editor draws a player under ([[2026-11-18 Audio And Video Players]]).
15288
+ *
15289
+ * The syntax is the image form of an [[Asset Reference]], and the file's type decides what is
15290
+ * drawn: a picture for an image (`image-line.ts`), a player for a recording. Both read the line
15291
+ * through `embed-line.ts`.
15292
+ *
15293
+ * Only an Asset Reference (`../assets/clip.webm`) is a media line. A recording on another site
15294
+ * (`![clip](https://example.com/clip.mp4)`) is not played: the Client's Content Security Policy
15295
+ * lets media come from the graph's own files only, so it stays the link it is.
15296
+ *
15297
+ * Pure over the line text, no DOM, no CodeMirror.
15298
+ */
15299
+ /** Whether a file with this extension is played, and as what: the Asset Store's list, as `isImageExt` is. */
15300
+ var mediaKindOfExtension = mediaKindOfExt;
15301
+ /**
15302
+ * Whether `![…](target)` names a recording in the graph's own files, and of which kind. Only an
15303
+ * [[Asset Reference]] can: the same question the asset link asks (`assetNameFromRef`), so a media
15304
+ * line always has its link above the player and its file where the Asset Store looks.
15305
+ */
15306
+ function mediaKindOfTarget(target) {
15307
+ const name = assetNameFromRef(target.trim());
15308
+ if (name === null) return null;
15309
+ const dot = name.lastIndexOf(".");
15310
+ return dot <= 0 ? null : mediaKindOfExtension(name.slice(dot + 1));
15311
+ }
15312
+ // ../client/src/lib/document/outliner.ts
15313
+ function lineIndent(line) {
15314
+ return line.length - line.trimStart().length;
15315
+ }
15316
+ function isBulletLine(line) {
15317
+ return /^-\s/.test(line.trimStart());
15318
+ }
15319
+ /** A bullet whose content is `[ ]` / `[x]`; undefined if not a task. */
15320
+ function taskDone(line) {
15321
+ const m = /^-\s+\[([ xX])\]/.exec(line.trimStart());
15322
+ return m ? m[1].toLowerCase() === "x" : void 0;
15323
+ }
15324
+ /** Length of the bullet marker incl. its trailing space: `- ` (2) or `- [ ] ` (6). */
15325
+ function markerLength(line) {
15326
+ const indent = lineIndent(line);
15327
+ const rest = line.slice(indent);
15328
+ const task = /^-\s+\[[ xX]\]\s?/.exec(rest);
15329
+ if (task) return task[0].length;
15330
+ const bullet = /^-\s/.exec(rest);
15331
+ return bullet ? bullet[0].length : 0;
15332
+ }
15333
+ /** Offset of a line's content: past its indent and, on a bullet, past the `- ` / `- [ ] ` marker. */
15334
+ function contentStart(line) {
15335
+ return lineIndent(line) + markerLength(line);
15336
+ }
15337
+ /** The bullet's content (everything after the marker). `""` for an empty bullet. */
15338
+ function bulletContent(line) {
15339
+ return line.slice(contentStart(line));
15340
+ }
15341
+ /** A heading line (`#`…`######` + space), tolerant of leading indent — matches the block model. */
15342
+ function isHeadingLine(line) {
15343
+ return /^#{1,6}\s/.test(line.trimStart());
15344
+ }
15345
+ /** Map from a fenced block's opener line index to the block, for O(1) "does a fence start here?". */
15346
+ function fenceStartMap(blocks) {
15347
+ const m = /* @__PURE__ */ new Map();
15348
+ for (const b of blocks) m.set(b.start, b);
15349
+ return m;
15350
+ }
15351
+ /**
15352
+ * The branch rooted at line `i`: `i` plus all following lines more indented than it — its
15353
+ * descendants and continuation lines. **Fence-opaque** (ADR 0021): a fenced block deeper than the
15354
+ * root is swallowed whole, so its internal blank lines don't truncate the branch. **Indent decides
15355
+ * blankness** (ADR 0021): a whitespace-only line is judged by its indentation like any other line —
15356
+ * an indented soft line stays in the branch; a flush-left empty line (or one at/left of the root)
15357
+ * ends it, as do a heading and any same-or-shallower content line.
15358
+ */
15359
+ function branchRange(lines, i, blocks = fencedBlocks(lines)) {
15360
+ return {
15361
+ start: i,
15362
+ end: branchEnd$1(lines, i, fenceStartMap(blocks))
15363
+ };
15364
+ }
15365
+ /** The last line of the branch rooted at line `i` ({@link branchRange}), given the fence openers. */
15366
+ function branchEnd$1(lines, i, starts) {
15367
+ const root = lineIndent(lines[i]);
15368
+ const own = starts.get(i);
15369
+ let end = own ? own.end : i;
15370
+ let j = end + 1;
15371
+ while (j < lines.length) {
15372
+ const b = starts.get(j);
15373
+ if (b) {
15374
+ if (lineIndent(lines[b.start]) > root) {
15375
+ end = b.end;
15376
+ j = b.end + 1;
15377
+ continue;
15378
+ }
15379
+ break;
15380
+ }
15381
+ const line = lines[j];
15382
+ if (isHeadingLine(line)) break;
15383
+ if (lineIndent(line) <= root) break;
15384
+ end = j;
15385
+ j++;
15386
+ }
15387
+ return end;
15388
+ }
15389
+ // ../client/src/lib/document/publish/markdown/list-item-end-rule.ts
15390
+ /** The lines this parse ended a list item at. */
15391
+ function endedAt(state) {
15392
+ const env = state.env;
15393
+ env.etherpkListItemEnds ??= /* @__PURE__ */ new Set();
15394
+ return env.etherpkListItemEnds;
15395
+ }
15396
+ /** A line whose indentation, if any, is spaces only. */
15397
+ var SPACE_INDENTED = /^ *\S/;
15398
+ /** An empty bullet as the editor reads one: a dash and whitespace, indented with spaces. */
15399
+ var EMPTY_BULLET = /^ *-[ \t]+$/;
15400
+ /** The block rules whose reading of a line this rule ended an item at is never the editor's. */
15401
+ var READ_AS_A_PARAGRAPH = [
15402
+ "lheading",
15403
+ "reference",
15404
+ "html_block",
15405
+ "code"
15406
+ ];
15407
+ /** Line `line` as typed, from its true start: inside a quote `bMarks` starts after the `>`. */
15408
+ function rawLine(state, line) {
15409
+ const end = state.eMarks[line];
15410
+ return state.src.slice(state.src.lastIndexOf("\n", end - 1) + 1, end);
15411
+ }
15412
+ /**
15413
+ * The first line of the innermost list item the parse is inside, or null when it is in no item or
15414
+ * inside a quote. Walking back over the tokens pushed so far, the openers not yet closed are the
15415
+ * containers the parse is inside, innermost first. A block being read has not pushed its own tokens.
15416
+ */
15417
+ function openItemLine(state) {
15418
+ let closed = 0;
15419
+ let item = null;
15420
+ for (let i = state.tokens.length - 1; i >= 0; i--) {
15421
+ const token = state.tokens[i];
15422
+ if (token.nesting === -1) closed++;
15423
+ else if (token.nesting === 1) {
14921
15424
  if (closed > 0) closed--;
14922
15425
  else if (token.type === "blockquote_open") return null;
14923
15426
  else if (token.type === "list_item_open" && item === null) item = token.map?.[0] ?? null;
@@ -15179,14 +15682,14 @@ function mapNames(source) {
15179
15682
  return readMapBody(source.split("\n")).items.map((item) => item.name).filter((name) => name !== "").join(", ");
15180
15683
  }
15181
15684
  /** A document-relative asset reference: any number of `../`, `assets/`, the name. */
15182
- var ASSET_REF$1 = /^(?:\.\.\/)*assets\/(.+)$/;
15685
+ var ASSET_REF = /^(?:\.\.\/)*assets\/(.+)$/;
15183
15686
  /**
15184
15687
  * The asset a reference names, decoded, or null when it names none. A name that decodes to
15185
15688
  * anything but one file inside `assets/` is not an asset: it would become a bundle path, and a site
15186
15689
  * folder, outside `assets/` (see `isSafeAssetName`). The link is then left as the author wrote it.
15187
15690
  */
15188
15691
  function assetNameOf(ref) {
15189
- const match = ASSET_REF$1.exec(ref);
15692
+ const match = ASSET_REF.exec(ref);
15190
15693
  if (!match) return null;
15191
15694
  const raw = match[1].split(/[?#]/)[0];
15192
15695
  let name;
@@ -15225,6 +15728,12 @@ function plainText(tokens) {
15225
15728
  }
15226
15729
  return lines.join("\n");
15227
15730
  }
15731
+ /** The browser's own player for a recording in the graph's files written as `target`, or null when it is none. */
15732
+ function mediaElement(asset, target, src, label) {
15733
+ const media = asset === null ? null : mediaKindOfTarget(target);
15734
+ if (media === null) return null;
15735
+ return `<${media} controls preload="metadata" src="${escapeHtml$3(src)}" aria-label="${escapeHtml$3(label)}"></${media}>`;
15736
+ }
15228
15737
  function createDocumentRenderer(options) {
15229
15738
  const md = new MarkdownIt({
15230
15739
  html: true,
@@ -15246,18 +15755,23 @@ function createDocumentRenderer(options) {
15246
15755
  mermaidFallback: false,
15247
15756
  assets: []
15248
15757
  };
15758
+ /** Where the site serves the asset `name`, noted as one the page uses; null when it is none or is not published. */
15759
+ function publishedAsset(name) {
15760
+ const href = name === null ? null : options.assetHref(name);
15761
+ if (name === null || href === null) return null;
15762
+ if (!state.assets.includes(name)) state.assets.push(name);
15763
+ return href;
15764
+ }
15249
15765
  md.renderer.rules.image;
15250
15766
  md.renderer.rules.image = (tokens, idx, opts, env, self) => {
15251
15767
  const token = tokens[idx];
15252
- const name = assetNameOf(String(token.attrGet("src") ?? ""));
15253
- if (name !== null) {
15254
- const href = options.assetHref(name);
15255
- if (href !== null) {
15256
- token.attrSet("src", href);
15257
- if (!state.assets.includes(name)) state.assets.push(name);
15258
- }
15259
- }
15768
+ const src = String(token.attrGet("src") ?? "");
15769
+ const name = assetNameOf(src);
15770
+ const href = publishedAsset(name);
15771
+ if (href !== null) token.attrSet("src", href);
15260
15772
  const parsed = parseImageDisplaySizeHint(self.renderInlineAsText(token.children ?? [], opts, env));
15773
+ const player = mediaElement(name, src, href ?? src, parsed.cleanAlt);
15774
+ if (player !== null) return player;
15261
15775
  token.attrSet("alt", parsed.cleanAlt);
15262
15776
  if (parsed.maxWidth !== void 0) {
15263
15777
  const style = [`max-width:${displayMaxWidth(parsed.maxWidth)}`];
@@ -15326,101 +15840,50 @@ function createDocumentRenderer(options) {
15326
15840
  return self.renderToken(tokens, idx, opts);
15327
15841
  };
15328
15842
  function render(body) {
15329
- state = {
15330
- toc: [],
15331
- ids: /* @__PURE__ */ new Set(),
15332
- hasMath: false,
15333
- hasMermaid: false,
15334
- mermaidFallback: false,
15335
- assets: []
15336
- };
15337
- const env = {};
15338
- const tokens = md.parse(body, env);
15339
- const html = md.renderer.render(tokens, md.options, env);
15340
- const hasMath = state.hasMath || html.includes("class=\"math math-inline\"");
15341
- const text = plainText(tokens);
15342
- return {
15343
- html,
15344
- toc: state.toc,
15345
- hasMath,
15346
- hasMermaid: state.hasMermaid,
15347
- mermaidFallback: state.mermaidFallback,
15348
- text,
15349
- excerpt: excerptOf(text),
15350
- assets: state.assets
15351
- };
15352
- }
15353
- function renderInline(text) {
15354
- return md.renderInline(text, {});
15355
- }
15356
- function fences(body) {
15357
- const out = [];
15358
- for (const token of md.parse(body, {})) {
15359
- if (token.type !== "fence") continue;
15360
- const lang = token.info.trim().split(/\s+/)[0] ?? "";
15361
- out.push({
15362
- lang,
15363
- code: token.content
15364
- });
15365
- }
15366
- return out;
15367
- }
15368
- return {
15369
- render,
15370
- renderInline,
15371
- fences
15372
- };
15373
- }
15374
- // ../client/src/lib/document/markdown-link-target.ts
15375
- /**
15376
- * The one definition of markdown link syntax, shared by every reader of one.
15377
- *
15378
- * Ten places used to spell this out, and each spelled the destination `[^)\s]+`, which stops at
15379
- * the FIRST closing parenthesis. That is wrong the moment a file name contains one, and imported
15380
- * attachments contain them all the time - `Quote_320_from_Garden_Fencing_ltd_(1)_1700000000000_0.pdf`
15381
- * has the shape they take. Every reader then saw the same truncated target, so the link styling and the
15382
- * download and delete controls landed in the middle of the text, and the [[Local Mirror]] reported
15383
- * the stub as a document link to an attachment the graph plainly had (2026-09-10).
15384
- *
15385
- * Sharing only the destination would have left the same duplication one layer down: nine call
15386
- * sites each re-spelling `\[([^\]]*)\]\(` around it. So the whole link is defined here, once, as
15387
- * regex source with **named groups** - which is also what lets a caller read `groups.target`
15388
- * without counting brackets, and what stops the next change to the grammar from silently missing
15389
- * a site.
15390
- *
15391
- * Source rather than a compiled RegExp, because what varies between callers is not the link: it is
15392
- * the anchoring and what surrounds it. One wants a whole line to be nothing but an image, one
15393
- * wants a Logseq `{:height 100}` suffix after it, one scans prose. Each composes what it needs.
15394
- *
15395
- * CommonMark's rule for the unbracketed destination form: no whitespace, and parentheses only in
15396
- * balanced pairs. Nesting is bounded here at two levels, one more than any real file name uses,
15397
- * because an unbounded version needs a recursive parser and would buy nothing.
15398
- *
15399
- * Pure: strings of regex source, no DOM, no CodeMirror.
15400
- */
15401
- /**
15402
- * The destination grammar. `excluded` adds characters the caller's context forbids on top of
15403
- * whitespace and parentheses - an HTML attribute cannot hold its own quote, and a target inside
15404
- * markdown brackets cannot hold `]`.
15405
- */
15406
- function linkTargetPattern(excluded = "") {
15407
- const plain = `[^\\s()${excluded}]`;
15408
- return `(?:${plain}|\\((?:${plain}|\\(${plain}*\\))*\\))+`;
15409
- }
15410
- /**
15411
- * A whole markdown link or image, as regex source with named groups.
15412
- *
15413
- * - `bang` - `!` for an image, empty for a link.
15414
- * - `label` - the alt text or link text, size hint and all.
15415
- * - `target` - the destination.
15416
- *
15417
- * A regex may not repeat a group name, so compose this **once** per pattern. Wrap it in a group of
15418
- * your own where you need the whole link as one capture.
15419
- */
15420
- var MARKDOWN_LINK = `(?<bang>!?)\\[(?<label>(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*)\\]\\((?<target>${linkTargetPattern()})\\)`;
15421
- /** A match's groups, typed. Every {@link MARKDOWN_LINK} match has all three. */
15422
- function linkGroups(match) {
15423
- return match.groups;
15843
+ state = {
15844
+ toc: [],
15845
+ ids: /* @__PURE__ */ new Set(),
15846
+ hasMath: false,
15847
+ hasMermaid: false,
15848
+ mermaidFallback: false,
15849
+ assets: []
15850
+ };
15851
+ const env = {};
15852
+ const tokens = md.parse(body, env);
15853
+ const html = md.renderer.render(tokens, md.options, env);
15854
+ const hasMath = state.hasMath || html.includes("class=\"math math-inline\"");
15855
+ const text = plainText(tokens);
15856
+ return {
15857
+ html,
15858
+ toc: state.toc,
15859
+ hasMath,
15860
+ hasMermaid: state.hasMermaid,
15861
+ mermaidFallback: state.mermaidFallback,
15862
+ text,
15863
+ excerpt: excerptOf(text),
15864
+ assets: state.assets
15865
+ };
15866
+ }
15867
+ function renderInline(text) {
15868
+ return md.renderInline(text, {});
15869
+ }
15870
+ function fences(body) {
15871
+ const out = [];
15872
+ for (const token of md.parse(body, {})) {
15873
+ if (token.type !== "fence") continue;
15874
+ const lang = token.info.trim().split(/\s+/)[0] ?? "";
15875
+ out.push({
15876
+ lang,
15877
+ code: token.content
15878
+ });
15879
+ }
15880
+ return out;
15881
+ }
15882
+ return {
15883
+ render,
15884
+ renderInline,
15885
+ fences
15886
+ };
15424
15887
  }
15425
15888
  // ../client/src/lib/document/line-endings.ts
15426
15889
  /** `text` with every `\r\n` and every lone `\r` written as `\n`; `text` itself when it holds no `\r`. */
@@ -16956,385 +17419,88 @@ async function setupDiagrams(env, say) {
16956
17419
  child.on("error", reject);
16957
17420
  child.on("close", (code) => code === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`Playwright's installer exited with code ${code}.`)));
16958
17421
  });
16959
- const after = await chromiumStatus(env);
16960
- if (!after.executable) throw new Error("The installer finished but no Chromium executable was found - set ETHERPK_CHROMIUM to a browser on this machine instead.");
16961
- say(`Chromium is set up: ${after.executable}`);
16962
- return after;
16963
- }
16964
- /** The page every render runs in: Mermaid loaded once, configured as the Client configures it. */
16965
- var PAGE$2 = "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>";
16966
- /** A headless browser from whichever Chromium is available, or null. The caller closes it. */
16967
- async function launchChromium(env) {
16968
- const status = await chromiumStatus(env);
16969
- if (!status.executable) return null;
16970
- const { chromium } = await playwright(env);
16971
- return chromium.launch({
16972
- executablePath: status.executable,
16973
- headless: true
16974
- });
16975
- }
16976
- /**
16977
- * What a failed launch reports: the lines the browser wrote to stderr, each once, or the message's
16978
- * first line when it wrote none. Playwright's message around them is its own log of the launch.
16979
- */
16980
- function browserLogErrors(message) {
16981
- const said = [...message.split("Call log:")[0].matchAll(/\[pid=\d+\]\[err\] (.*)/g)].map((match) => match[1]);
16982
- return said.length > 0 ? [...new Set(said)].join("\n") : message.split("\n")[0];
16983
- }
16984
- /**
16985
- * Why the browser a publish would use does not start, or null when it starts or there is none. A file
16986
- * that exists can still fail to run: a missing library, or a library path this process inherited.
16987
- */
16988
- async function chromiumStartFailure(env) {
16989
- try {
16990
- await (await launchChromium(env))?.close();
16991
- return null;
16992
- } catch (error) {
16993
- return browserLogErrors(error instanceof Error ? error.message : String(error));
16994
- }
16995
- }
16996
- /**
16997
- * A renderer over one headless browser, opened for a publish and closed after it. Null when no
16998
- * browser is available; the caller decides what that means (a publish with diagrams refuses).
16999
- */
17000
- async function openDiagramRenderer(env) {
17001
- const browser = await launchChromium(env);
17002
- if (!browser) return null;
17003
- let pagePromise;
17004
- const page = () => {
17005
- if (!pagePromise) pagePromise = (async () => {
17006
- const p = await (await browser.newContext({ javaScriptEnabled: true })).newPage();
17007
- await p.setContent(PAGE$2);
17008
- await p.addScriptTag({ path: require$2.resolve("mermaid/dist/mermaid.min.js") });
17009
- await p.evaluate(() => {
17010
- window.mermaid.initialize({
17011
- startOnLoad: false,
17012
- securityLevel: "strict",
17013
- theme: "neutral"
17014
- });
17015
- });
17016
- return p;
17017
- })();
17018
- return pagePromise;
17019
- };
17020
- let seq = 0;
17021
- return {
17022
- async render(source) {
17023
- const p = await page();
17024
- const id = `gk-mermaid-${++seq}`;
17025
- return p.evaluate(async ([renderId, text]) => {
17026
- const m = window.mermaid;
17027
- try {
17028
- const { svg } = await m.render(renderId, text);
17029
- const el = new DOMParser().parseFromString(svg, "text/html").querySelector("svg");
17030
- if (!el) throw new Error("Mermaid produced no diagram.");
17031
- el.setAttribute("role", "img");
17032
- return el.outerHTML;
17033
- } finally {
17034
- document.getElementById(renderId)?.remove();
17035
- document.getElementById(`d${renderId}`)?.remove();
17036
- }
17037
- }, [id, source]);
17038
- },
17039
- async dispose() {
17040
- await browser.close().catch(() => {});
17041
- }
17042
- };
17043
- }
17044
- // ../client/src/lib/storage/fs/asset-store.ts
17045
- /**
17046
- * The **Asset store** over a {@link DirectoryAdapter}: uploads land as binary files
17047
- * under `assets/`, named `kebab-stem.<contenthash>.ext` (DESIGN.md → On-disk layout).
17048
- * Identical bytes de-duplicate to one file **by content and extension alone** - the stem is
17049
- * display, not identity - so the same file added again under a different name references the
17050
- * one already stored rather than writing a second copy. Built on the same File-System seam as
17051
- * {@link createFilesystemDocumentStore}, so the pure naming/dedup logic is Node-testable
17052
- * over the in-memory adapter before any browser code runs.
17053
- *
17054
- * Assets are referenced from documents by a relative path — `../assets/<name>` — which
17055
- * resolves from any journal entry or page (both sit one level under the graph root,
17056
- * the Logseq convention). `resolve` reads those bytes back and hands out an object URL plus
17057
- * the name and MIME type a download or a viewer needs; the URLs are cached per asset and
17058
- * revoked on {@link AssetStore.dispose}.
17059
- *
17060
- * Remote (S3) upload and per-graph access control are deferred (DESIGN.md → Server
17061
- * Backend); this is the Filesystem Backend path only.
17062
- */
17063
- /** Extensions rendered inline as images (everything else renders as a download link). */
17064
- var IMAGE_EXTS = /* @__PURE__ */ new Set([
17065
- "png",
17066
- "jpg",
17067
- "jpeg",
17068
- "gif",
17069
- "webp",
17070
- "svg",
17071
- "avif",
17072
- "bmp"
17073
- ]);
17074
- /** A doc-relative asset reference: optional `../` hops, then `assets/<name>`. */
17075
- var ASSET_REF = /^(?:\.\.\/)*assets\/(.+)$/;
17076
- /**
17077
- * An asset could not be fetched just now: the connection failed, or the server answered with a
17078
- * status that means "try again". It says nothing about whether the file exists, so something
17079
- * showing the file asks again rather than calling it missing. `status` is the server's answer,
17080
- * absent when the connection failed before there was one.
17081
- */
17082
- var AssetUnavailableError = class extends Error {
17083
- name = "AssetUnavailableError";
17084
- status;
17085
- constructor(message, options = {}) {
17086
- super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
17087
- this.status = options.status;
17088
- }
17089
- };
17090
- /**
17091
- * An asset arrived, but not as it was stored: the server offered a different number of chunks than
17092
- * its encrypted metadata records, or the joined bytes do not match the size or hash recorded there.
17093
- * Each chunk is authenticated on its own, so this is what catches a file cut short, or a reuse
17094
- * answer that points at a different file (ADR 0027, amended 2026-10-05). The bytes are never
17095
- * handed over. Distinct from a missing file (`null`), which is gone, and from an unavailable one,
17096
- * which may come good by itself.
17097
- */
17098
- var AssetIntegrityError = class extends Error {
17099
- name = "AssetIntegrityError";
17100
- constructor(message = "This file did not arrive complete, so it was not opened. Try again in a moment.") {
17101
- super(message);
17102
- }
17103
- };
17104
- /** Split a file name into its stem and lower-cased extension (`''` ext when there is none). */
17105
- function splitNameExt(fileName) {
17106
- const dot = fileName.lastIndexOf(".");
17107
- if (dot <= 0) return {
17108
- stem: fileName,
17109
- ext: ""
17110
- };
17111
- return {
17112
- stem: fileName.slice(0, dot),
17113
- ext: fileName.slice(dot + 1).toLowerCase()
17114
- };
17115
- }
17116
- /** True when `ext` (with or without a leading dot) names an inline-rendered image format. */
17117
- function isImageExt(ext) {
17118
- return IMAGE_EXTS.has(ext.replace(/^\./, "").toLowerCase());
17119
- }
17120
- /** The on-disk asset name: `kebab-stem.<hash>.ext` (stem falls back to `asset` when slugging empties it). */
17121
- function assetFileName(originalName, hash) {
17122
- const { stem, ext } = splitNameExt(originalName);
17123
- const slug = publishSlug(stem) || "asset";
17124
- return ext ? `${slug}.${hash}.${ext}` : `${slug}.${hash}`;
17125
- }
17126
- /** The de-duplication key: content plus extension. The stem is display, not identity. */
17127
- function contentKey(hash, ext) {
17128
- return `${hash}.${ext}`;
17129
- }
17130
- /**
17131
- * An on-disk asset name with its content hash taken back out — `q3-report.a1b2c3d4.pdf` reads as
17132
- * `q3-report.pdf`. What a download is called and what titles an asset tab, so neither shows a
17133
- * user a hash they never typed. A name this store did not write is returned unchanged.
17134
- */
17135
- function displayAssetName(fileName) {
17136
- const parsed = assetHashFromName(fileName);
17137
- if (!parsed) return fileName;
17138
- const stem = fileName.slice(0, fileName.length - `.${parsed.hash}`.length - (parsed.ext ? parsed.ext.length + 1 : 0));
17139
- return parsed.ext ? `${stem}.${parsed.ext}` : stem;
17140
- }
17141
- /**
17142
- * MIME types for the formats the app itself renders, plus the handful a browser needs told about
17143
- * to do anything sensible with a download. Deliberately small and deliberately **empty for
17144
- * anything else**: a wrong type is worse than none, because a wrong one is acted on. The
17145
- * Filesystem Backend has nowhere else to learn a type from — unlike the Server Backend, which
17146
- * carries the uploader's own MIME type inside the encrypted asset metadata.
17147
- */
17148
- var MIME_TYPES = {
17149
- png: "image/png",
17150
- jpg: "image/jpeg",
17151
- jpeg: "image/jpeg",
17152
- gif: "image/gif",
17153
- webp: "image/webp",
17154
- svg: "image/svg+xml",
17155
- avif: "image/avif",
17156
- bmp: "image/bmp",
17157
- pdf: "application/pdf",
17158
- epub: "application/epub+zip",
17159
- txt: "text/plain",
17160
- csv: "text/csv",
17161
- json: "application/json",
17162
- md: "text/markdown",
17163
- mp3: "audio/mpeg",
17164
- mp4: "video/mp4",
17165
- webm: "video/webm",
17166
- zip: "application/zip"
17167
- };
17168
- /** The MIME type for a file extension (with or without a leading dot), or `''` when unknown. */
17169
- function mimeTypeForExt(ext) {
17170
- return MIME_TYPES[ext.replace(/^\./, "").toLowerCase()] ?? "";
17422
+ const after = await chromiumStatus(env);
17423
+ if (!after.executable) throw new Error("The installer finished but no Chromium executable was found - set ETHERPK_CHROMIUM to a browser on this machine instead.");
17424
+ say(`Chromium is set up: ${after.executable}`);
17425
+ return after;
17426
+ }
17427
+ /** The page every render runs in: Mermaid loaded once, configured as the Client configures it. */
17428
+ var PAGE$2 = "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>";
17429
+ /** A headless browser from whichever Chromium is available, or null. The caller closes it. */
17430
+ async function launchChromium(env) {
17431
+ const status = await chromiumStatus(env);
17432
+ if (!status.executable) return null;
17433
+ const { chromium } = await playwright(env);
17434
+ return chromium.launch({
17435
+ executablePath: status.executable,
17436
+ headless: true
17437
+ });
17171
17438
  }
17172
17439
  /**
17173
- * The on-disk name referenced by a doc-relative asset ref, or `null` if `ref` is not an asset
17174
- * reference. A reference whose name decodes to anything but one file inside `assets/`, or does not
17175
- * decode at all, is not one: it can never name a file on disk (see `isSafeAssetName`).
17440
+ * What a failed launch reports: the lines the browser wrote to stderr, each once, or the message's
17441
+ * first line when it wrote none. Playwright's message around them is its own log of the launch.
17176
17442
  */
17177
- function assetNameFromRef(ref) {
17178
- const clean = ref.split(/[?#]/)[0];
17179
- const match = ASSET_REF.exec(clean);
17180
- if (!match) return null;
17181
- let name;
17443
+ function browserLogErrors(message) {
17444
+ const said = [...message.split("Call log:")[0].matchAll(/\[pid=\d+\]\[err\] (.*)/g)].map((match) => match[1]);
17445
+ return said.length > 0 ? [...new Set(said)].join("\n") : message.split("\n")[0];
17446
+ }
17447
+ /**
17448
+ * Why the browser a publish would use does not start, or null when it starts or there is none. A file
17449
+ * that exists can still fail to run: a missing library, or a library path this process inherited.
17450
+ */
17451
+ async function chromiumStartFailure(env) {
17182
17452
  try {
17183
- name = decodeURIComponent(match[1]);
17184
- } catch {
17453
+ await (await launchChromium(env))?.close();
17185
17454
  return null;
17455
+ } catch (error) {
17456
+ return browserLogErrors(error instanceof Error ? error.message : String(error));
17186
17457
  }
17187
- return isSafeAssetName(name) ? name : null;
17188
17458
  }
17189
17459
  /**
17190
- * The markdown to embed a saved asset: an inline image, or a plain link that downloads on click.
17191
- * For an image, an optional `displaySize` (e.g. `300` or `300x200`) is added as a `|` display-size
17192
- * hint; the caller is responsible for passing a valid spec (see `normalizeDisplaySize`).
17460
+ * A renderer over one headless browser, opened for a publish and closed after it. Null when no
17461
+ * browser is available; the caller decides what that means (a publish with diagrams refuses).
17193
17462
  */
17194
- function buildAssetMarkdown(asset, displaySize) {
17195
- if (!asset.isImage) return `[${asset.stem}](${asset.ref})`;
17196
- return `![${displaySize ? `${asset.stem}|${displaySize}` : asset.stem}](${asset.ref})`;
17197
- }
17198
- /** First 8 hex chars of the SHA-256 of the bytes — the content hash in the asset name. */
17199
- async function contentHash(bytes) {
17200
- const digest = await crypto.subtle.digest("SHA-256", bytes);
17201
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 8);
17202
- }
17203
- function createAssetStore(adapter) {
17204
- const urlCache = /* @__PURE__ */ new Map();
17205
- /**
17206
- * Content key → the on-disk name already holding those bytes. Built from `assets/` on the
17207
- * first save (so a store that only ever resolves never pays for the listing) and maintained
17208
- * on every write after that.
17209
- *
17210
- * This is what keeps the [[Asset]] guarantee honest on this backend: identity is content,
17211
- * not the name it was added under. Keying the write on the whole file name instead — which
17212
- * is what this did before — stored the same bytes twice whenever the stem differed.
17213
- */
17214
- let contentIndex;
17215
- /**
17216
- * The index, listed once. The promise is what is kept, not the map: saves run several at once
17217
- * (an upload's pool), and each one that found no map yet used to list the folder into a map of
17218
- * its own. The last listing to finish replaced the rest, and every write recorded in the others
17219
- * was forgotten, so adding the same files again stored and reported most of them as new.
17220
- */
17221
- function assetsByContent() {
17222
- contentIndex ??= listByContent().catch((err) => {
17223
- contentIndex = void 0;
17224
- throw err;
17225
- });
17226
- return contentIndex;
17227
- }
17228
- async function listByContent() {
17229
- const index = /* @__PURE__ */ new Map();
17230
- for (const { name } of await adapter.list("assets")) {
17231
- const parsed = assetHashFromName(name);
17232
- if (parsed && !index.has(contentKey(parsed.hash, parsed.ext))) index.set(contentKey(parsed.hash, parsed.ext), name);
17233
- }
17234
- return index;
17235
- }
17236
- /**
17237
- * Content key → the save storing those bytes right now. Two saves of the same bytes at once (a
17238
- * file dropped twice in one batch) both missed the index and wrote the file twice, under each
17239
- * name. The second waits for the first and references its file instead.
17240
- */
17241
- const storing = /* @__PURE__ */ new Map();
17242
- /** The file holding `bytes` under `key`: one the folder already has, or one written now. */
17243
- async function store(key, name, hash, bytes) {
17244
- const index = await assetsByContent();
17245
- const held = index.get(key);
17246
- if (held !== void 0 && await adapter.exists("assets", held)) return {
17247
- fileName: held,
17248
- reused: true
17249
- };
17250
- const fileName = assetFileName(name, hash);
17251
- await adapter.writeBinary("assets", fileName, bytes);
17252
- index.set(key, fileName);
17253
- return {
17254
- fileName,
17255
- reused: false
17256
- };
17257
- }
17463
+ async function openDiagramRenderer(env) {
17464
+ const browser = await launchChromium(env);
17465
+ if (!browser) return null;
17466
+ let pagePromise;
17467
+ const page = () => {
17468
+ if (!pagePromise) pagePromise = (async () => {
17469
+ const p = await (await browser.newContext({ javaScriptEnabled: true })).newPage();
17470
+ await p.setContent(PAGE$2);
17471
+ await p.addScriptTag({ path: require$2.resolve("mermaid/dist/mermaid.min.js") });
17472
+ await p.evaluate(() => {
17473
+ window.mermaid.initialize({
17474
+ startOnLoad: false,
17475
+ securityLevel: "strict",
17476
+ theme: "neutral"
17477
+ });
17478
+ });
17479
+ return p;
17480
+ })();
17481
+ return pagePromise;
17482
+ };
17483
+ let seq = 0;
17258
17484
  return {
17259
- async save({ name, bytes }, onBytes) {
17260
- const hash = await contentHash(bytes);
17261
- const { stem, ext } = splitNameExt(name);
17262
- const key = contentKey(hash, ext);
17263
- let stored;
17264
- const pending = storing.get(key);
17265
- if (pending) stored = await pending.then((fileName) => ({
17266
- fileName,
17267
- reused: true
17268
- }), () => store(key, name, hash, bytes));
17269
- else {
17270
- const work = store(key, name, hash, bytes);
17271
- storing.set(key, work.then((done) => done.fileName));
17485
+ async render(source) {
17486
+ const p = await page();
17487
+ const id = `gk-mermaid-${++seq}`;
17488
+ return p.evaluate(async ([renderId, text]) => {
17489
+ const m = window.mermaid;
17272
17490
  try {
17273
- stored = await work;
17491
+ const { svg } = await m.render(renderId, text);
17492
+ const el = new DOMParser().parseFromString(svg, "text/html").querySelector("svg");
17493
+ if (!el) throw new Error("Mermaid produced no diagram.");
17494
+ el.setAttribute("role", "img");
17495
+ return el.outerHTML;
17274
17496
  } finally {
17275
- storing.delete(key);
17497
+ document.getElementById(renderId)?.remove();
17498
+ document.getElementById(`d${renderId}`)?.remove();
17276
17499
  }
17277
- }
17278
- onBytes?.(bytes.length);
17279
- return {
17280
- ref: `../assets/${stored.fileName}`,
17281
- name: stored.fileName,
17282
- stem: publishSlug(stem) || "asset",
17283
- isImage: isImageExt(ext),
17284
- ...stored.reused ? { reused: true } : {}
17285
- };
17286
- },
17287
- async readBytes(ref) {
17288
- const assetName = assetNameFromRef(ref);
17289
- if (!assetName) return null;
17290
- const { ext } = splitNameExt(assetName);
17291
- try {
17292
- const { bytes } = await adapter.readBinary("assets", assetName);
17293
- return {
17294
- bytes,
17295
- name: displayAssetName(assetName),
17296
- type: mimeTypeForExt(ext)
17297
- };
17298
- } catch {
17299
- return null;
17300
- }
17301
- },
17302
- async resolve(ref) {
17303
- const assetName = assetNameFromRef(ref);
17304
- if (!assetName) return null;
17305
- const { ext } = splitNameExt(assetName);
17306
- const meta = {
17307
- name: displayAssetName(assetName),
17308
- type: mimeTypeForExt(ext)
17309
- };
17310
- const cached = urlCache.get(assetName);
17311
- if (cached) return {
17312
- url: cached,
17313
- ...meta
17314
- };
17315
- let content;
17316
- try {
17317
- content = await adapter.readBinary("assets", assetName);
17318
- } catch {
17319
- return null;
17320
- }
17321
- const url = URL.createObjectURL(new Blob([content.bytes], meta.type ? { type: meta.type } : {}));
17322
- urlCache.set(assetName, url);
17323
- return {
17324
- url,
17325
- ...meta
17326
- };
17327
- },
17328
- dispose() {
17329
- for (const url of urlCache.values()) URL.revokeObjectURL(url);
17330
- urlCache.clear();
17500
+ }, [id, source]);
17331
17501
  },
17332
- renamed(from, to) {
17333
- const url = urlCache.get(from);
17334
- if (url) URL.revokeObjectURL(url);
17335
- urlCache.delete(from);
17336
- const parsed = assetHashFromName(to);
17337
- if (parsed) contentIndex?.then((index) => index.set(contentKey(parsed.hash, parsed.ext), to)).catch(() => {});
17502
+ async dispose() {
17503
+ await browser.close().catch(() => {});
17338
17504
  }
17339
17505
  };
17340
17506
  }
@@ -18214,16 +18380,51 @@ function lastNonBlank(lines) {
18214
18380
  var READ_TEXT_CAP = 2e5;
18215
18381
  /** UTF-16 units across one bulk read before the rest is cut. */
18216
18382
  var READ_MANY_TEXT_CAP = 4e5;
18217
- /** `text` cut at `cap`, and whether it was. */
18218
- function capText(text, cap = READ_TEXT_CAP) {
18219
- return text.length > cap ? {
18220
- text: text.slice(0, cap),
18221
- truncated: true
18222
- } : {
18223
- text,
18224
- truncated: false
18383
+ /**
18384
+ * The part of `text` from `offset` that fits in `cap` UTF-16 units, so an agent can read a long
18385
+ * document to its end, a window at a time, by passing each `nextOffset` back. A cut window ends
18386
+ * after the last line break inside it, so the next starts on a line of its own; a line longer than
18387
+ * the whole cap is cut at the cap instead. A window never ends between the two halves of a
18388
+ * surrogate pair. An offset past the end, negative or not a whole number is a RangeError.
18389
+ */
18390
+ function textWindow(text, offset = 0, cap = READ_TEXT_CAP) {
18391
+ if (!Number.isInteger(offset) || offset < 0 || offset > text.length) throw new RangeError(`offset must be a whole number from 0 to ${text.length}, the text's length.`);
18392
+ const startLine = lineBreaksBefore(text, offset);
18393
+ if (text.length - offset <= cap) return {
18394
+ text: text.slice(offset),
18395
+ truncated: false,
18396
+ offset,
18397
+ startLine
18398
+ };
18399
+ const end = windowEnd(text, offset, offset + cap);
18400
+ return {
18401
+ text: text.slice(offset, end),
18402
+ truncated: true,
18403
+ offset,
18404
+ startLine,
18405
+ nextOffset: end
18225
18406
  };
18226
18407
  }
18408
+ /** How many line breaks come before `offset`: the 0-based line it falls on. */
18409
+ function lineBreaksBefore(text, offset) {
18410
+ let count = 0;
18411
+ for (let at = text.indexOf("\n"); at !== -1 && at < offset; at = text.indexOf("\n", at + 1)) count++;
18412
+ return count;
18413
+ }
18414
+ /**
18415
+ * Where a window from `offset` that may reach `limit` ends: after its last line break, or at
18416
+ * `limit` when it holds none, moved off the middle of a surrogate pair (back, or forward past
18417
+ * the pair when going back would leave the window empty).
18418
+ */
18419
+ function windowEnd(text, offset, limit) {
18420
+ const lastBreak = text.lastIndexOf("\n", limit - 1);
18421
+ if (lastBreak >= offset) return lastBreak + 1;
18422
+ if (!isHighSurrogate(text.charCodeAt(limit - 1))) return limit;
18423
+ return limit - 1 > offset ? limit - 1 : limit + 1;
18424
+ }
18425
+ function isHighSurrogate(unit) {
18426
+ return unit >= 55296 && unit <= 56319;
18427
+ }
18227
18428
  /**
18228
18429
  * Whether `text` holds encrypted text anywhere: a Protected Document, or any other document with an
18229
18430
  * `etherpk-cipher` fence in it. The index flags both as protected (`index-db.ts`), and a reader whose
@@ -19436,14 +19637,36 @@ function imagePixelSize(bytes) {
19436
19637
  function encodeConceptPath(concept) {
19437
19638
  return concept.split("/").map(encodeURIComponent).join("/");
19438
19639
  }
19439
- // ../client/src/lib/navigation/document-url.ts
19440
- /** The Document URL for a concept within a graph. */
19441
- function documentUrl(graphId, concept) {
19442
- return `${graphUrl(graphId)}/d/${encodeConceptPath(concept)}`;
19640
+ // ../client/src/lib/navigation/graph-address.ts
19641
+ var ROOT = "/graph";
19642
+ /** The path a reference's graph is written as. A legacy graph is written as it was read. */
19643
+ function referencedGraphPath(graph) {
19644
+ return graph.where === "legacy" ? `/g/${encodeURIComponent(graph.name)}` : graphAddressPath(graph);
19645
+ }
19646
+ /** The pattern of a referenced graph at the start of a path, capturing where (or none) and the name. */
19647
+ var REFERENCED_GRAPH_PATTERN = String.raw`\/(?:graph\/(folder|sync|browser)|g)\/([^/?#\s]+)`;
19648
+ /** The graph the two captures of {@link REFERENCED_GRAPH_PATTERN} name. Throws on a malformed escape. */
19649
+ function referencedGraphFrom(where, name) {
19650
+ return {
19651
+ where: where === void 0 ? "legacy" : where,
19652
+ name: decodeURIComponent(name)
19653
+ };
19654
+ }
19655
+ /**
19656
+ * Whether a reference is for the graph being served. A legacy reference carries an id: a synced
19657
+ * graph's is checked, and a folder graph's is not, since each browser gave the folder an id of its
19658
+ * own. A graph kept in the browser is checked by id, in either shape.
19659
+ */
19660
+ function referencesGraph(reference, served) {
19661
+ if (reference.where === "legacy") return served.where === "folder" || reference.name === served.name;
19662
+ return sameGraphAddress(reference, served);
19663
+ }
19664
+ /** The path a workspace address begins with: `/graph/folder/reports`. */
19665
+ function graphAddressPath(address) {
19666
+ return `${ROOT}/${address.where}/${encodeURIComponent(address.name)}`;
19443
19667
  }
19444
- /** The bare workspace URL for a graph. */
19445
- function graphUrl(graphId) {
19446
- return `/g/${encodeURIComponent(graphId)}`;
19668
+ function sameGraphAddress(left, right) {
19669
+ return left.where === right.where && left.name === right.name;
19447
19670
  }
19448
19671
  /**
19449
19672
  * The words that identify a task while its tags change: the text after the checkbox and the tag
@@ -19461,7 +19684,7 @@ async function taskFingerprint(label) {
19461
19684
  }
19462
19685
  /** The reference's address: the Document URL with the task in its fragment, which a browser never sends. */
19463
19686
  function taskReferenceUrl(reference, origin = "") {
19464
- return `${origin}${documentUrl(reference.graphId, reference.document)}#task=${reference.line}-${reference.fingerprint}`;
19687
+ return `${origin}${referencedGraphPath(reference.graph)}/d/${encodeConceptPath(reference.document)}#task=${reference.line}-${reference.fingerprint}`;
19465
19688
  }
19466
19689
  /** The scheme that marks a Task Reference as EtherPK's own, and not a web address to fetch. */
19467
19690
  var SCHEME = "etherpk:";
@@ -19469,7 +19692,7 @@ var SCHEME = "etherpk:";
19469
19692
  function taskReferenceId(reference) {
19470
19693
  return `${SCHEME}${taskReferenceUrl(reference)}`;
19471
19694
  }
19472
- var PATH = String.raw`\/g\/([^/?#\s]+)\/d\/([^?#\s]+?)(?:\?[^#\s]*)?#task=(\d+)-([0-9a-f]{12})(?![0-9a-f])`;
19695
+ var PATH = `${REFERENCED_GRAPH_PATTERN}${String.raw`\/d\/([^?#\s]+?)(?:\?[^#\s]*)?#task=(\d+)-([0-9a-f]{12})(?![0-9a-f])`}`;
19473
19696
  /** The `etherpk:` form, read first so that nothing shaped like a reference in a task's words wins. */
19474
19697
  var ETHERPK_REFERENCE = new RegExp(`${SCHEME}${PATH}`);
19475
19698
  /** The reference anywhere, with any origin or none: the web address an earlier version copied. */
@@ -19481,10 +19704,10 @@ var ANY_REFERENCE = new RegExp(PATH);
19481
19704
  function parseTaskReference(input) {
19482
19705
  const match = ETHERPK_REFERENCE.exec(input) ?? ANY_REFERENCE.exec(input);
19483
19706
  if (!match) return null;
19484
- const [, graph, path, line, fingerprint] = match;
19707
+ const [, where, graph, path, line, fingerprint] = match;
19485
19708
  try {
19486
19709
  return {
19487
- graphId: decodeURIComponent(graph),
19710
+ graph: referencedGraphFrom(where, graph),
19488
19711
  document: path.split("/").map(decodeURIComponent).join("/"),
19489
19712
  line: Number(line),
19490
19713
  fingerprint
@@ -19500,10 +19723,10 @@ function parseTaskReference(input) {
19500
19723
  * wrong task. A document that no longer answers to its name goes straight to the graph.
19501
19724
  */
19502
19725
  async function resolveTaskReference(reference, sources) {
19503
- if (sources.graphId !== null && sources.graphId !== reference.graphId) return {
19726
+ if (!referencesGraph(reference.graph, sources.graph)) return {
19504
19727
  ok: false,
19505
19728
  code: "other_graph",
19506
- servedGraphId: sources.graphId
19729
+ served: sources.graph
19507
19730
  };
19508
19731
  const named = sources.resolveDocument(reference.document);
19509
19732
  if (named !== null) {
@@ -19578,8 +19801,8 @@ async function taskLinesWith(lines, fingerprint) {
19578
19801
  return out;
19579
19802
  }
19580
19803
  // ../client/src/lib/document/lane-reference.ts
19581
- /** `/g/<graph>/k/<concept>#lane=<status>` or `/g/<graph>/kanban#lane=<status>`, the scheme before it optional. */
19582
- var LANE_REFERENCE = /(?:etherpk:)?\/g\/([^/?#\s]+)\/(?:k\/([^?#\s]+?)|kanban)#lane=([a-z]+)(?![a-z])/;
19804
+ /** `<graph address>/k/<concept>#lane=<status>` or `<graph address>/kanban#lane=<status>`, the scheme before it optional. */
19805
+ var LANE_REFERENCE = new RegExp(`(?:etherpk:)?${REFERENCED_GRAPH_PATTERN}${String.raw`\/(?:k\/([^?#\s]+?)|kanban)#lane=([a-z]+)(?![a-z])`}`);
19583
19806
  /**
19584
19807
  * The lane reference in `input`: the text as copied, or the `etherpk:` reference alone; null when
19585
19808
  * `input` holds none, or names a lane that is no task status.
@@ -19587,11 +19810,11 @@ var LANE_REFERENCE = /(?:etherpk:)?\/g\/([^/?#\s]+)\/(?:k\/([^?#\s]+?)|kanban)#l
19587
19810
  function parseLaneReference(input) {
19588
19811
  const match = LANE_REFERENCE.exec(input);
19589
19812
  if (!match) return null;
19590
- const [, graph, path, status] = match;
19813
+ const [, where, graph, path, status] = match;
19591
19814
  if (!TASK_STATUSES.includes(status)) return null;
19592
19815
  try {
19593
19816
  return {
19594
- graphId: decodeURIComponent(graph),
19817
+ graph: referencedGraphFrom(where, graph),
19595
19818
  concept: path === void 0 ? null : path.split("/").map(decodeURIComponent).join("/"),
19596
19819
  status
19597
19820
  };
@@ -20319,6 +20542,18 @@ var ToolError = class extends Error {
20319
20542
  this.name = "ToolError";
20320
20543
  }
20321
20544
  };
20545
+ /**
20546
+ * The window of `text` a read answers, from `offset` up to `cap`, in the shape read results carry.
20547
+ * An offset outside the text is the agent's to correct, so it is refused as an argument.
20548
+ */
20549
+ function readWindow(text, offset, cap = READ_TEXT_CAP) {
20550
+ try {
20551
+ return textWindow(text, offset ?? 0, cap);
20552
+ } catch (error) {
20553
+ if (error instanceof RangeError) throw new ToolError("invalid_argument", error.message);
20554
+ throw error;
20555
+ }
20556
+ }
20322
20557
  /** Keys the frontmatter tools never read or write; each has a tool of its own. */
20323
20558
  var OWNED_KEYS = /* @__PURE__ */ new Set([
20324
20559
  "title",
@@ -20504,17 +20739,19 @@ async function listDocuments(graph, args = {}) {
20504
20739
  hasMore: paged.hasMore
20505
20740
  };
20506
20741
  }
20507
- async function readDocument(graph, concept) {
20742
+ /**
20743
+ * One document's body and frontmatter. A body longer than {@link READ_TEXT_CAP} comes a window at
20744
+ * a time: each cut answer gives the `nextOffset` to read on from, so the end is always reachable.
20745
+ */
20746
+ async function readDocument(graph, concept, options = {}) {
20508
20747
  await graph.store.refresh();
20509
20748
  const { identity, text } = await requireReadable(graph, concept);
20510
- const capped = capText(text, READ_TEXT_CAP);
20511
20749
  return {
20512
20750
  concept: identity.concept,
20513
20751
  kind: identity.kind,
20514
20752
  aliases: identity.aliases,
20515
- text: capped.text,
20516
- frontmatter: agentFrontmatter(graph.store.openRaw(identity.concept).getText()),
20517
- truncated: capped.truncated
20753
+ ...readWindow(text, options.offset),
20754
+ frontmatter: agentFrontmatter(graph.store.openRaw(identity.concept).getText())
20518
20755
  };
20519
20756
  }
20520
20757
  function requireVersions(graph) {
@@ -20539,7 +20776,7 @@ async function listVersions(graph, concept) {
20539
20776
  };
20540
20777
  }
20541
20778
  /** One earlier version's text (ADR 0184). */
20542
- async function readVersion(graph, concept, version) {
20779
+ async function readVersion(graph, concept, version, options = {}) {
20543
20780
  await graph.store.refresh();
20544
20781
  const versions = requireVersions(graph);
20545
20782
  const { identity } = await requireReadable(graph, concept);
@@ -20552,14 +20789,13 @@ async function readVersion(graph, concept, version) {
20552
20789
  }
20553
20790
  if (!read) throw notFound(concept);
20554
20791
  if (holdsEncryptedText(read.text)) throw protectedDocument(concept);
20555
- const capped = capText(read.text, READ_TEXT_CAP);
20792
+ const window = readWindow(read.text, options.offset);
20556
20793
  const nameThen = read.identity.kind === "journal" ? read.identity.date ?? identity.concept : read.identity.title ?? identity.concept;
20557
20794
  return {
20558
20795
  concept: identity.concept,
20559
20796
  version,
20560
20797
  nameThen,
20561
- text: capped.text,
20562
- truncated: capped.truncated
20798
+ ...window
20563
20799
  };
20564
20800
  }
20565
20801
  async function search(graph, args) {
@@ -20743,9 +20979,9 @@ async function graphPath(graph, args) {
20743
20979
  function taskSelection(graph, args) {
20744
20980
  if (args.reference !== void 0) {
20745
20981
  const lane = parseLaneReference(args.reference);
20746
- if (!lane) throw new ToolError("invalid_argument", "reference is not a lane reference. Pass the text Copy agent instruction wrote, or its etherpk:/g/…#lane= address; for one task, use read_task.");
20982
+ if (!lane) throw new ToolError("invalid_argument", "reference is not a lane reference. Pass the text Copy agent instruction wrote, or its etherpk:/graph/…#lane= address; for one task, use read_task.");
20747
20983
  if (args.concept !== void 0 || args.statuses !== void 0) throw new ToolError("invalid_argument", "A lane reference names the concept and status itself: pass reference without concept or statuses.");
20748
- if (graph.backend.kind === "synced" && lane.graphId !== graph.graphId) throw new ToolError("other_graph", `That lane reference is for another graph. This server serves "${graph.name}" (${graph.graphId}); ask the user to connect the graph the reference is from.`);
20984
+ if (!referencesGraph(lane.graph, servedAddress(graph))) throw new ToolError("other_graph", `That lane reference is for another graph. This server serves "${graph.name}" (${graphAddressPath(servedAddress(graph))}); ask the user to connect the graph the reference is from.`);
20749
20985
  return {
20750
20986
  concept: lane.concept,
20751
20987
  statuses: [lane.status],
@@ -21283,14 +21519,17 @@ async function listAssets(graph, args = {}) {
21283
21519
  for (const [concept, body] of bodies) for (const ref of assetReferencesIn(body)) {
21284
21520
  const id = assets.identify(ref);
21285
21521
  if (!id) continue;
21286
- const entry = found.get(id) ?? {
21522
+ const name = displayNameOf(ref);
21523
+ const key = `${id}\n${name}`;
21524
+ const entry = found.get(key) ?? {
21525
+ id,
21287
21526
  ref,
21288
- name: displayNameOf(ref),
21289
- type: mimeTypeForExt(splitNameExt(displayNameOf(ref)).ext),
21527
+ name,
21528
+ type: mimeTypeForExt(splitNameExt(name).ext),
21290
21529
  documents: /* @__PURE__ */ new Set()
21291
21530
  };
21292
21531
  entry.documents.add(concept);
21293
- found.set(id, entry);
21532
+ found.set(key, entry);
21294
21533
  }
21295
21534
  let sizes;
21296
21535
  try {
@@ -21298,11 +21537,11 @@ async function listAssets(graph, args = {}) {
21298
21537
  } catch {
21299
21538
  sizes = void 0;
21300
21539
  }
21301
- const list = [...found.entries()].map(([id, entry]) => ({
21540
+ const list = [...found.values()].map((entry) => ({
21302
21541
  reference: entry.ref,
21303
21542
  name: entry.name,
21304
21543
  type: entry.type,
21305
- ...sizes?.has(id) ? { bytes: sizes.get(id) } : {},
21544
+ ...sizes?.has(entry.id) ? { bytes: sizes.get(entry.id) } : {},
21306
21545
  documents: [...entry.documents].sort()
21307
21546
  })).sort((a, b) => a.name.localeCompare(b.name));
21308
21547
  return {
@@ -21334,16 +21573,14 @@ async function readDocuments(graph, args) {
21334
21573
  });
21335
21574
  continue;
21336
21575
  }
21337
- const cap = Math.max(0, Math.min(READ_TEXT_CAP, budget));
21338
- const cut = text.length > cap;
21339
- budget -= Math.min(text.length, cap);
21576
+ const window = textWindow(text, 0, Math.max(0, Math.min(READ_TEXT_CAP, budget)));
21577
+ budget -= window.text.length;
21340
21578
  documents.push({
21341
21579
  concept: identity.concept,
21342
21580
  kind: identity.kind,
21343
21581
  aliases: identity.aliases,
21344
- text: cut ? text.slice(0, cap) : text,
21345
- frontmatter: agentFrontmatter(graph.store.openRaw(identity.concept).getText()),
21346
- truncated: cut
21582
+ ...window,
21583
+ frontmatter: agentFrontmatter(graph.store.openRaw(identity.concept).getText())
21347
21584
  });
21348
21585
  }
21349
21586
  return { documents };
@@ -21402,7 +21639,7 @@ async function setTask(graph, args) {
21402
21639
  return {
21403
21640
  concept: identity.concept,
21404
21641
  line,
21405
- text: after.text,
21642
+ text: bulletLabel(next),
21406
21643
  status,
21407
21644
  priority: after.priority,
21408
21645
  due: after.due,
@@ -21416,11 +21653,25 @@ async function setTask(graph, args) {
21416
21653
  reference: await referenceFor(graph, identity.concept, line, bulletLabel(next))
21417
21654
  };
21418
21655
  }
21656
+ /**
21657
+ * The [[Graph Address]] of the graph served (ADR 0192), which a reference is checked against and
21658
+ * written with: a synced graph by its id, a folder by its own name, as a browser that opened the
21659
+ * folder names it. The folder's id here is a key for this computer's caches and is in no address.
21660
+ */
21661
+ function servedAddress(graph) {
21662
+ return graph.backend.kind === "synced" ? {
21663
+ where: "sync",
21664
+ name: graph.graphId
21665
+ } : {
21666
+ where: "folder",
21667
+ name: basename(resolve(graph.backend.path))
21668
+ };
21669
+ }
21419
21670
  /** Where a Task Reference is resolved in this graph: its documents, read live, and its index. */
21420
21671
  function referenceSources(graph) {
21421
21672
  const hidden = hiddenKeys(graph);
21422
21673
  return {
21423
- graphId: graph.backend.kind === "synced" ? graph.graphId : null,
21674
+ graph: servedAddress(graph),
21424
21675
  resolveDocument: (name) => {
21425
21676
  const identity = resolveIdentity(graph, name);
21426
21677
  return identity && !isHidden(hidden, identity) ? identity.concept : null;
@@ -21436,7 +21687,7 @@ function referenceSources(graph) {
21436
21687
  async function referenceFor(graph, concept, line, label) {
21437
21688
  const fingerprint = await taskFingerprint(label);
21438
21689
  return taskReferenceId({
21439
- graphId: graph.graphId,
21690
+ graph: servedAddress(graph),
21440
21691
  document: concept,
21441
21692
  line,
21442
21693
  fingerprint
@@ -21449,11 +21700,11 @@ async function referenceFor(graph, concept, line, label) {
21449
21700
  */
21450
21701
  async function requireReferencedTask(graph, reference, purpose = "read") {
21451
21702
  const parsed = parseTaskReference(reference);
21452
- if (!parsed) throw new ToolError("invalid_argument", "That is not a task reference: one is etherpk:/g/<graph>/d/<document>#task=<line>-<fingerprint>, as Copy agent instruction in EtherPK writes it.");
21703
+ if (!parsed) throw new ToolError("invalid_argument", "That is not a task reference: one is etherpk:/graph/sync/<graph id>/d/<document>#task=<line>-<fingerprint>, or etherpk:/graph/folder/<folder name>/d/… for a graph folder, as Copy agent instruction in EtherPK writes it.");
21453
21704
  await graph.store.refresh();
21454
21705
  const found = await resolveTaskReference(parsed, referenceSources(graph));
21455
21706
  if (found.ok) return found;
21456
- if (found.code === "other_graph") throw new ToolError("other_graph", `That task reference is for another graph. This server serves "${graph.name}" (${found.servedGraphId}); ask the user to connect the graph the reference is from.`);
21707
+ if (found.code === "other_graph") throw new ToolError("other_graph", `That task reference is for another graph. This server serves "${graph.name}" (${graphAddressPath(found.served)}); ask the user to connect the graph the reference is from.`);
21457
21708
  if (found.code === "task_ambiguous") throw new ToolError("task_ambiguous", `More than one task has those words (${found.candidates.map((candidate) => `"${candidate.document}" line ${candidate.line}`).join(", ")}), so none was chosen. Ask the user which one, or name it by concept and line.`);
21458
21709
  const named = resolveIdentity(graph, parsed.document);
21459
21710
  if (purpose === "write" && named && await visibleText(graph, named) === null) throw protectedDocument(parsed.document);
@@ -21520,7 +21771,7 @@ async function readTask(graph, args) {
21520
21771
  return {
21521
21772
  concept: found.document,
21522
21773
  line: found.line,
21523
- text: task.text,
21774
+ text: bulletLabel(line),
21524
21775
  status: taskStatus(task.done, task),
21525
21776
  priority: task.priority,
21526
21777
  due: task.due,
@@ -22619,6 +22870,7 @@ function accessEndedError(graph, cmd) {
22619
22870
  return loss.kind === "membership" ? new ToolError("access_removed", `This account no longer has access to the graph: it left, was removed by the owner, or the graph was deleted. Run ${cmd} graphs to see the graphs it can reach.`) : new ToolError("token_revoked", `The Sync Server no longer accepts this computer's access token: it was revoked or has expired, or the account's password was reset. Run ${cmd} login again.`);
22620
22871
  }
22621
22872
  var concept = z.string().min(1).describe("A page title, one of its aliases, a journal day as YYYY-MM-DD, or \"today\".");
22873
+ var readOffset = z.number().int().min(0).optional().describe("Where to start reading: the nextOffset a cut answer gave. 0 (the start) by default.");
22622
22874
  var offset = z.number().int().nonnegative().optional().describe("Skip this many results (paging).");
22623
22875
  /** A frontmatter value as JSON carries it; the writer turns it into YAML. */
22624
22876
  var frontmatterValue = z.union([
@@ -22666,8 +22918,8 @@ function createMcpServer(source, info) {
22666
22918
  "search has two kinds of matching: mode \"text\" (default) matches words and quoted phrases, and mode \"semantic\" finds passages about what a question or description means even when no words match. Use semantic for questions and descriptions, text for names, identifiers and exact phrases. \"hybrid\" returns both groups. When you answer from a search result, cite the document and where in it (its breadcrumb or lines). Semantic mode needs a one-time \"semantic setup\" on this computer - if it is not set up, search says so and names the command.",
22667
22919
  "graph_insights says what the links show across the whole graph (the most-linked concepts, pages many documents ask for that do not exist yet, pages linked to nothing, groups of related concepts and the concepts bridging them), and graph_path finds how two concepts are connected. Use them to answer questions about the shape of the graph, or to suggest pages to write or link.",
22668
22920
  "Start with graph_info to see what you are connected to. read_documents reads several documents in one call. tasks lists tasks and set_task changes one (status, priority, due and scheduled dates) by document and line.",
22669
- "An agent instruction is how a person hands you one task: a few lines naming the graph, the task's words and a task reference, etherpk:/g/<graph>/d/<document>#task=<line>-<fingerprint> (an earlier version wrote a web address ending in the same #task=). The reference is not a web address: never fetch it. Pass the whole text to read_task for the task and its detail, to set_task (as reference) to change it, and to add_task_note to write what you did as a task comment (a bullet under the \"- Comments\" bullet nested directly under the task). Leave its status as it is unless the user asks you to change it. Tasks nested under a task are its subtasks: read_task lists them in subtasks, and you may tick off or change each one with set_task as you work through it, using its reference. A Kanban board shows a subtask only through its parent's card when the parent is on the same board. The detail can hold images and files (its assets list): read each with read_asset and look at it before you start, as it is part of the task. A reference finds the task after lines are added above it or its tags change; if its words were edited, or the edit has not reached this computer yet, it answers task_not_found, and you should ask the user for a fresh one.",
22670
- "An agent instruction can also hand you a whole lane of a Kanban board, to work through every task in it or to triage them: a few lines naming the graph, the board and the lane, and a lane reference, etherpk:/g/<graph>/k/<concept>#lane=<status> (etherpk:/g/<graph>/kanban#lane=<status> for the Graph Kanban, which holds every task in the graph). It is not a web address either. Pass the whole text to tasks as reference to list the lane's tasks as the board shows them now; each comes with its own task reference for read_task, set_task and add_task_note.",
22921
+ "An agent instruction is how a person hands you one task: a few lines naming the graph, the task's words and a task reference, etherpk:/graph/sync/<graph id>/d/<document>#task=<line>-<fingerprint> (etherpk:/graph/folder/<folder name>/d/… for a graph folder; an earlier version wrote etherpk:/g/<graph>/d/…, which is still read). The reference is not a web address: never fetch it. Pass the whole text to read_task for the task and its detail, to set_task (as reference) to change it, and to add_task_note to write what you did as a task comment (a bullet under the \"- Comments\" bullet nested directly under the task). Leave its status as it is unless the user asks you to change it. Tasks nested under a task are its subtasks: read_task lists them in subtasks, and you may tick off or change each one with set_task as you work through it, using its reference. A Kanban board shows a subtask only through its parent's card when the parent is on the same board. The detail can hold images and files (its assets list): read each with read_asset and look at it before you start, as it is part of the task. A reference finds the task after lines are added above it or its tags change; if its words were edited, or the edit has not reached this computer yet, it answers task_not_found, and you should ask the user for a fresh one.",
22922
+ "An agent instruction can also hand you a whole lane of a Kanban board, to work through every task in it or to triage them: a few lines naming the graph, the board and the lane, and a lane reference, etherpk:/graph/sync/<graph id>/k/<concept>#lane=<status> (ending /kanban#lane=<status> for the Graph Kanban, which holds every task in the graph). It is not a web address either. Pass the whole text to tasks as reference to list the lane's tasks as the board shows them now; each comes with its own task reference for read_task, set_task and add_task_note.",
22671
22923
  "Publishing: list_publications shows the publications this graph defines (a publication is a page whose frontmatter defines it - its outline is the site navigation) and the public documents none takes. A document is on a site when its frontmatter has public: true and names the publication in publications. create_publication and update_publication change the settings, and publish writes the site into the publish folder the user set for it on this machine with the etherpk-mcp publish command (the tool cannot choose a folder) and returns the report. publish with dryRun: true renders and reports without writing and needs no folder: run it after editing a publication's pages and fix what it names. Diagrams need a browser the user installs once with \"diagrams setup\".",
22672
22924
  "Themes: a publication's look is a theme - Mustache templates, a stylesheet, a script and a manifest. list_themes shows the bundled ones (read-only) and the graph's own. read_theme writes a theme's files to a folder on this machine to read and edit. customise_publication_theme copies a publication's bundled theme into the graph and points the publication at the copy (create_theme copies any theme). write_theme_file, delete_theme_file and import_theme_folder change a graph theme. preview_theme renders a theme to a folder (with screenshots when a browser is set up) to check before publish. For a snippet such as an analytics script, an include slot (update_publication includes, e.g. head) filled by a page may be lighter than a theme copy.",
22673
22925
  "Images and files are assets: upload_asset adds a file from this machine and returns the markdown to paste into a document. To put an image in a drawing, add a line to its excalidraw.drawing fence with the reference, width and height upload_asset returns: {\"type\":\"image\",\"customData\":{\"asset\":\"<reference>\"},\"x\":0,\"y\":0,\"width\":<width>,\"height\":<height>}. A shape added after it draws above it. Add lines only, and never edit or reorder the lines there. read_asset writes an asset to a local file you can open, and list_assets shows the assets documents reference. An asset is available only where a document you can read references it (or you uploaded it this session). read_asset, read_theme and preview_theme write under the graph's downloads directory and return the path - name a folder relative to it, never elsewhere.",
@@ -22687,9 +22939,12 @@ function createMcpServer(source, info) {
22687
22939
  }, async (args) => run((graph) => listDocuments(graph, args)));
22688
22940
  server.registerTool("read_document", {
22689
22941
  title: "Read a document",
22690
- description: "One document: its body as \"text\" (the markdown after any frontmatter block) and its frontmatter as the \"frontmatter\" object, minus title and aliases (its identity) and any publication definition. A protected document answers not_found, as a name nothing has. Long documents are cut and marked truncated: true.",
22691
- inputSchema: { concept }
22692
- }, async (args) => run((graph) => readDocument(graph, args.concept)));
22942
+ description: `One document: its body as "text" (the markdown after any frontmatter block) and its frontmatter as the "frontmatter" object, minus title and aliases (its identity) and any publication definition. A protected document answers not_found, as a name nothing has. A body longer than ${READ_TEXT_CAP.toLocaleString("en-GB")} characters comes in parts: an answer cut short says truncated: true and gives nextOffset - read again with offset set to it for the next part, until truncated is false. startLine is the line the text starts on, so line numbers from search and tasks still apply.`,
22943
+ inputSchema: {
22944
+ concept,
22945
+ offset: readOffset
22946
+ }
22947
+ }, async (args) => run((graph) => readDocument(graph, args.concept, { offset: args.offset })));
22693
22948
  server.registerTool("list_versions", {
22694
22949
  title: "List a document's versions",
22695
22950
  description: "A synced document's earlier versions, newest first, each with when it was made and what made it (\"Edited\", \"Before a rename\", \"Before an agent's edit\"), and how many days the graph keeps them. Your first edit to a document in a session is preceded by a version of it. You cannot restore a version: tell the person, who restores it from the document's Version history in EtherPK.",
@@ -22697,15 +22952,16 @@ function createMcpServer(source, info) {
22697
22952
  }, async (args) => run((graph) => listVersions(graph, args.concept)));
22698
22953
  server.registerTool("read_version", {
22699
22954
  title: "Read a document version",
22700
- description: "The whole text a synced document held at one earlier version (list_versions names them), frontmatter included, and the name it had then. Read-only: a person restores a version in EtherPK.",
22955
+ description: "The whole text a synced document held at one earlier version (list_versions names them), frontmatter included, and the name it had then. A long text comes in parts, as read_document gives them: truncated: true with nextOffset to pass as offset. Read-only: a person restores a version in EtherPK.",
22701
22956
  inputSchema: {
22702
22957
  concept,
22703
- version: z.string().uuid().describe("A version id from list_versions.")
22958
+ version: z.string().uuid().describe("A version id from list_versions."),
22959
+ offset: readOffset
22704
22960
  }
22705
- }, async (args) => run((graph) => readVersion(graph, args.concept, args.version)));
22961
+ }, async (args) => run((graph) => readVersion(graph, args.concept, args.version, { offset: args.offset })));
22706
22962
  server.registerTool("read_documents", {
22707
22963
  title: "Read several documents",
22708
- description: `Up to 20 documents in one call, each as read_document returns it. A protected or unknown document is reported in its place as not_found rather than failing the call. Long texts are cut and marked truncated.`,
22964
+ description: `Up to 20 documents in one call, each as read_document returns it. A protected or unknown document is reported in its place as not_found rather than failing the call. Long texts are cut and marked truncated, with the nextOffset to read the rest from with read_document.`,
22709
22965
  inputSchema: { concepts: z.array(concept).min(1).max(20) }
22710
22966
  }, async (args) => run((graph) => readDocuments(graph, args)));
22711
22967
  server.registerTool("search", {
@@ -29361,7 +29617,7 @@ async function openHeadlessGraph(deps) {
29361
29617
  }
29362
29618
  // src/headless-folder.ts
29363
29619
  /**
29364
- * A local graph folder, open in a process with no editor: the client's filesystem store over a
29620
+ * A graph folder, open in a process with no editor: the client's filesystem store over a
29365
29621
  * directory adapter, with the same derived index, persistence and semantic search a synced
29366
29622
  * graph gets from `assembleHeadlessGraph` ([[2026-09-18 Headless Client Serves A Local Folder]]).
29367
29623
  *
@@ -30272,7 +30528,7 @@ var SUBDIRS = [
30272
30528
  * A {@link DirectoryAdapter} over a real directory through `node:fs`: the third adapter behind
30273
30529
  * the seam the filesystem store reads and writes through (the browser's `web-fs-adapter.ts`
30274
30530
  * and the tests' `memory-adapter.ts` are the other two), so `createFilesystemDocumentStore`
30275
- * runs unchanged in the [[Headless Client]] over a local graph folder.
30531
+ * runs unchanged in the [[Headless Client]] over a graph folder.
30276
30532
  *
30277
30533
  * The contract it keeps, because the store's external-change detection depends on it: a
30278
30534
  * listing reports each file's mtime in epoch milliseconds and its size in bytes, a write
@@ -30490,7 +30746,7 @@ var USAGE = `etherpk-mcp - EtherPK Headless Client (an MCP server over one synce
30490
30746
  background process, which holds the graph open, and every serve passes its agent's
30491
30747
  session to that process.
30492
30748
  ${CMD} serve --folder <path> [--no-semantic]
30493
- Serve a local graph folder the same way: no sign-in, no server. The agent gets search,
30749
+ Serve a graph folder the same way: no sign-in, no server. The agent gets search,
30494
30750
  backlinks, tasks and format-safe edits over the folder's markdown, alongside the files
30495
30751
  themselves. Edits made in an editor or by the agent directly are picked up as they land.
30496
30752
  The folder must already be a graph, with pages/ and journals/ folders in it (EtherPK
@@ -31108,7 +31364,7 @@ function graphRequest(command, args) {
31108
31364
  const folder = args.folder?.trim();
31109
31365
  const wanted = args.graph?.trim();
31110
31366
  if (folder && (wanted || args["sync-server"])) fail(`${command} takes either --folder <path> or --graph <id or name> (with an optional --sync-server), not both.`);
31111
- if (!folder && !wanted) fail(`${command} needs --graph <id or name>, or --folder <path> for a local graph folder.`);
31367
+ if (!folder && !wanted) fail(`${command} needs --graph <id or name>, or --folder <path> for a graph folder.`);
31112
31368
  return folder ? {
31113
31369
  kind: "folder",
31114
31370
  path: resolve(folder)
@@ -31349,7 +31605,7 @@ async function hostCommand(args) {
31349
31605
  });
31350
31606
  }
31351
31607
  /**
31352
- * A local graph folder: no sign-in and no server ([[2026-09-18 Headless Client Serves A Local
31608
+ * A graph folder: no sign-in and no server ([[2026-09-18 Headless Client Serves A Local
31353
31609
  * Folder]]). The folder is what it is; the CLI never creates a skeleton in whatever directory
31354
31610
  * was mistyped. The index lives under the cache root, keyed by the folder's path.
31355
31611
  */