@aparte/core 0.32.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +30 -19
  2. package/dist/client/agent-runner.d.ts.map +1 -1
  3. package/dist/components/bubble/aparte-chat-bubble.d.ts +33 -0
  4. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  5. package/dist/components/bubble/bubble-sync.d.ts.map +1 -1
  6. package/dist/components/context/aparte-context.d.ts +4 -11
  7. package/dist/components/context/aparte-context.d.ts.map +1 -1
  8. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  9. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +77 -5
  10. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  11. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  12. package/dist/components/split/aparte-split.d.ts.map +1 -1
  13. package/dist/components/suggestions/aparte-suggestions.d.ts +15 -1
  14. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  15. package/dist/components/suggestions/suggestion-blocks.d.ts +21 -1
  16. package/dist/components/suggestions/suggestion-blocks.d.ts.map +1 -1
  17. package/dist/components/viewport/aparte-chat-viewport.d.ts +2 -5
  18. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  19. package/dist/config/aparte-config.d.ts +56 -4
  20. package/dist/config/aparte-config.d.ts.map +1 -1
  21. package/dist/config/config-context.d.ts.map +1 -1
  22. package/dist/config/image-policy.d.ts +104 -0
  23. package/dist/config/image-policy.d.ts.map +1 -0
  24. package/dist/config/index.d.ts +1 -0
  25. package/dist/config/index.d.ts.map +1 -1
  26. package/dist/config/locale.d.ts +8 -10
  27. package/dist/config/locale.d.ts.map +1 -1
  28. package/dist/config/sanitize.d.ts +36 -0
  29. package/dist/config/sanitize.d.ts.map +1 -1
  30. package/dist/custom-elements.json +1226 -82
  31. package/dist/{defer-hydration-DQKULLmH.js → defer-hydration-_SZv5PeY.js} +827 -65
  32. package/dist/defer-hydration-_SZv5PeY.js.map +1 -0
  33. package/dist/generated/element-attributes.d.ts +1 -3
  34. package/dist/generated/element-attributes.d.ts.map +1 -1
  35. package/dist/index.css +1 -1
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +497 -124
  39. package/dist/index.js.map +1 -1
  40. package/dist/index.node.d.ts +2 -2
  41. package/dist/index.node.d.ts.map +1 -1
  42. package/dist/index.node.js +1 -1
  43. package/dist/index.node.js.map +1 -1
  44. package/dist/interop/dialog-triggers.d.ts.map +1 -1
  45. package/dist/interop/image-holds.d.ts +20 -0
  46. package/dist/interop/image-holds.d.ts.map +1 -0
  47. package/dist/renderers/segments/text.d.ts.map +1 -1
  48. package/dist/renderers/segments/thinking.d.ts.map +1 -1
  49. package/dist/transport/agent-handler.d.ts +10 -0
  50. package/dist/transport/agent-handler.d.ts.map +1 -1
  51. package/dist/transport/agent-ticket.d.ts.map +1 -1
  52. package/dist/transport/backend-handler.d.ts +8 -0
  53. package/dist/transport/backend-handler.d.ts.map +1 -1
  54. package/dist/transport/backend-transport.d.ts.map +1 -1
  55. package/dist/transport/json-headers.d.ts +10 -0
  56. package/dist/transport/json-headers.d.ts.map +1 -0
  57. package/dist/transport/request-guard.d.ts +14 -0
  58. package/dist/transport/request-guard.d.ts.map +1 -0
  59. package/dist/types/events.d.ts +6 -13
  60. package/dist/types/events.d.ts.map +1 -1
  61. package/dist/types/index.d.ts +1 -1
  62. package/dist/types/index.d.ts.map +1 -1
  63. package/dist/types/models.d.ts +0 -34
  64. package/dist/types/models.d.ts.map +1 -1
  65. package/dist/types/segments.d.ts +0 -11
  66. package/dist/types/segments.d.ts.map +1 -1
  67. package/dist/utils/rendered-content.d.ts +3 -0
  68. package/dist/utils/rendered-content.d.ts.map +1 -0
  69. package/llms.txt +13 -0
  70. package/package.json +11 -4
  71. package/dist/defer-hydration-DQKULLmH.js.map +0 -1
@@ -119,7 +119,6 @@ const APARTE_DEFAULT_LOCALE = {
119
119
  contextTotal: "Total",
120
120
  contextReclaim: "Compacting now would free ~{n} tokens",
121
121
  contextCompactNow: "Compact now",
122
- compactionSummaryTitle: "Conversation summary",
123
122
  checkpointCount: "{n} messages summarised for the model",
124
123
  checkpointCountOne: "1 message summarised for the model",
125
124
  checkpointLegacy: "Earlier messages were summarised",
@@ -152,6 +151,8 @@ const APARTE_DEFAULT_LOCALE = {
152
151
  sourceNext: "Next source",
153
152
  sourcePosition: "Source {i} of {n}",
154
153
  opensInNewTab: "(opens in a new tab)",
154
+ imageLoad: "Load the image from {host}",
155
+ imageLoadNamed: "Load the image “{alt}” from {host}",
155
156
  questionDeclined: "You declined to answer.",
156
157
  artifactNotCreated: "Not created",
157
158
  thoughtFor: "Thought for {duration}",
@@ -863,6 +864,14 @@ function parseAparteEventStream(stream) {
863
864
  }
864
865
  });
865
866
  }
867
+ function jsonHeaders(extra) {
868
+ const headers = {};
869
+ for (const [name, value] of Object.entries(extra ?? {})) {
870
+ if (name.toLowerCase() !== "content-type") headers[name] = value;
871
+ }
872
+ headers["Content-Type"] = "application/json";
873
+ return headers;
874
+ }
866
875
  class AparteBackendTransport {
867
876
  constructor(options) {
868
877
  this.options = options;
@@ -871,7 +880,7 @@ class AparteBackendTransport {
871
880
  const body = this.options.buildBody ? this.options.buildBody(request, ctx.providerId) : { providerId: ctx.providerId, request };
872
881
  const response = await fetch(this.options.endpoint, {
873
882
  method: "POST",
874
- headers: { "Content-Type": "application/json", ...this.options.headers },
883
+ headers: jsonHeaders(this.options.headers),
875
884
  body: JSON.stringify(body),
876
885
  signal: ctx.signal
877
886
  });
@@ -891,9 +900,30 @@ class AparteBackendTransport {
891
900
  return parseAparteEventStream(response.body);
892
901
  }
893
902
  }
903
+ function refuseUnsafeRequest(req, allowedOrigins) {
904
+ const type = (req.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
905
+ if (type !== "application/json") {
906
+ return guardError(415, "Send the body as application/json.");
907
+ }
908
+ if (allowedOrigins) {
909
+ const origin = req.headers.get("origin");
910
+ if (origin !== null && !allowedOrigins.includes(origin)) {
911
+ return guardError(403, "This origin is not allowed.");
912
+ }
913
+ }
914
+ return null;
915
+ }
916
+ function guardError(status, message) {
917
+ return new Response(JSON.stringify({ error: { message } }), {
918
+ status,
919
+ headers: { "Content-Type": "application/json" }
920
+ });
921
+ }
894
922
  function createAparteChatHandler(options) {
895
923
  const doFetch = options.fetchImpl ?? fetch;
896
924
  return async function handler(req) {
925
+ const unsafe = refuseUnsafeRequest(req, options.allowedOrigins);
926
+ if (unsafe) return unsafe;
897
927
  const verdict = await options.authorize(req);
898
928
  if (verdict instanceof Response) return verdict;
899
929
  if (!verdict) return jsonError$1(401, "Unauthorized.");
@@ -1161,7 +1191,9 @@ function detachConfig(el2) {
1161
1191
  if (previous) notifyConfigChanged(el2, resolveConfig(el2.parentElement), previous);
1162
1192
  }
1163
1193
  function resolveConfig(el2) {
1164
- const host2 = el2?.closest?.(`[${APARTE_HOST_ATTR}]`);
1194
+ const selector = `[${APARTE_HOST_ATTR}]`;
1195
+ let host2 = el2?.closest?.(selector);
1196
+ while (host2 && !host2[CONFIG_SLOT]) host2 = host2.parentElement?.closest(selector);
1165
1197
  return host2?.[CONFIG_SLOT] ?? aparteGlobalConfig;
1166
1198
  }
1167
1199
  let _renderConfig = null;
@@ -1701,7 +1733,7 @@ const ALLOWED_TAGS = /* @__PURE__ */ new Set([
1701
1733
  "picture",
1702
1734
  "source",
1703
1735
  "input",
1704
- // GFM task-list checkboxes only — `copyAttributes` refuses every other `type`
1736
+ // GFM task-list checkboxes only — `sanitizeChildren` drops every other `type`, and disables these
1705
1737
  "abbr",
1706
1738
  "details",
1707
1739
  "summary",
@@ -1745,12 +1777,65 @@ const SAFE_URL = /^(?:https?:|mailto:|tel:|ftp:|sms:)/i;
1745
1777
  const RELATIVE_URL = /^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i;
1746
1778
  const SAFE_DATA_IMG = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i;
1747
1779
  const CONTROL_WS = /[\u0000-\u0020]+/g;
1748
- const EXTERNAL_URL = /^(?:https?:)?[/\\]{2}|^https?:[/\\]/i;
1780
+ const EXTERNAL_URL = /^(?:https?:)?[/\\]{2}|^https?:/i;
1749
1781
  const APARTE_CLASS = /^aparte-/i;
1782
+ const RESERVED_ATTRIBUTES = /* @__PURE__ */ new Set([
1783
+ "data-aparte-chat",
1784
+ "data-aparte-host",
1785
+ "data-aparte-theme",
1786
+ "data-aparte-split-pane",
1787
+ "data-aparte-launcher-close",
1788
+ "data-aparte-suggestions",
1789
+ "data-aparte-bubble",
1790
+ "data-aparte-empty",
1791
+ "data-aparte-panel",
1792
+ "data-aparte-panel-host",
1793
+ "data-aparte-card-part",
1794
+ "data-segment-id",
1795
+ "data-action"
1796
+ ]);
1797
+ const RESERVED_ATTRIBUTE_PREFIXES = ["data-aparte-dialog-", "data-aparte-sidebar-", "data-checkpoint-"];
1798
+ function isReservedAttribute(name) {
1799
+ return RESERVED_ATTRIBUTES.has(name) || RESERVED_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix));
1800
+ }
1801
+ const WIDGET_ROLES = /* @__PURE__ */ new Set([
1802
+ "button",
1803
+ "link",
1804
+ "checkbox",
1805
+ "textbox",
1806
+ "searchbox",
1807
+ "combobox",
1808
+ "switch",
1809
+ "tab",
1810
+ "menuitem",
1811
+ "menuitemcheckbox",
1812
+ "menuitemradio",
1813
+ "option",
1814
+ "radio",
1815
+ "slider",
1816
+ "spinbutton",
1817
+ "scrollbar",
1818
+ "treeitem",
1819
+ "gridcell",
1820
+ "listbox",
1821
+ "menu",
1822
+ "menubar",
1823
+ "radiogroup",
1824
+ "tablist",
1825
+ "tree",
1826
+ "treegrid",
1827
+ "grid",
1828
+ "dialog",
1829
+ "alertdialog",
1830
+ "application",
1831
+ "toolbar",
1832
+ "progressbar",
1833
+ "tabpanel"
1834
+ ]);
1750
1835
  function isSafeSrcset(value, tag) {
1751
1836
  const urlTag = tag === "source" ? "img" : tag;
1752
- for (const m of value.matchAll(/[a-z][a-z0-9+.-]*:[^\s,]*/gi)) {
1753
- if (!isSafeUrl(m[0], urlTag)) return false;
1837
+ for (const m of value.matchAll(/(?:^|[^a-z0-9+.-])([a-z][a-z0-9+.-]*:[^\s,]*)/gi)) {
1838
+ if (!isSafeUrl(m[1], urlTag)) return false;
1754
1839
  }
1755
1840
  return true;
1756
1841
  }
@@ -1797,39 +1882,36 @@ function scrubStyle(value) {
1797
1882
  }
1798
1883
  return kept.length ? kept.join("; ") : null;
1799
1884
  }
1800
- function copyAttributes(src, dest, tag) {
1885
+ function keepAttribute(tag, name, value) {
1801
1886
  const extra = TAG_ATTRS[tag];
1887
+ if (name.startsWith("on") || name.startsWith("formaction")) return null;
1888
+ if (!name.startsWith("data-") && !GLOBAL_ATTRS.has(name) && !(extra && extra.has(name))) return null;
1889
+ if (isReservedAttribute(name)) return null;
1890
+ if (name === "role" && value.trim().toLowerCase().split(/\s+/).some((role) => WIDGET_ROLES.has(role))) return null;
1891
+ if (URL_ATTRS.has(name) && !isSafeUrl(value, tag)) return null;
1892
+ if (name === "srcset" && !isSafeSrcset(value, tag)) return null;
1893
+ if (name === "style") return scrubStyle(value);
1894
+ if (name === "class") {
1895
+ const kept = value.split(/\s+/).filter((token) => token && !APARTE_CLASS.test(token));
1896
+ return kept.length ? kept.join(" ") : null;
1897
+ }
1898
+ return value;
1899
+ }
1900
+ function linkAttributes(href, targetWish) {
1901
+ const target = href.replace(CONTROL_WS, "");
1902
+ const wish = targetWish.trim().toLowerCase();
1903
+ if (wish === "_self" && !EXTERNAL_URL.test(target)) return [["target", "_self"]];
1904
+ if (wish || EXTERNAL_URL.test(target)) return [["target", "_blank"], ["rel", "noopener noreferrer"]];
1905
+ return [];
1906
+ }
1907
+ function copyAttributes(src, dest, tag) {
1802
1908
  for (const attr of Array.from(src.attributes)) {
1803
1909
  const name = attr.name.toLowerCase();
1804
- const value = attr.value;
1805
- if (name.startsWith("on") || name.startsWith("formaction")) continue;
1806
- if (!name.startsWith("data-") && !GLOBAL_ATTRS.has(name) && !(extra && extra.has(name))) continue;
1807
- if (URL_ATTRS.has(name) && !isSafeUrl(value, tag)) continue;
1808
- if (tag === "input" && name === "type" && value.toLowerCase() !== "checkbox") continue;
1809
- if (name === "srcset" && !isSafeSrcset(value, tag)) continue;
1810
- if (name === "style") {
1811
- const scrubbed = scrubStyle(value);
1812
- if (scrubbed === null) continue;
1813
- dest.setAttribute("style", scrubbed);
1814
- continue;
1815
- }
1816
- if (name === "class") {
1817
- const kept = value.split(/\s+/).filter((token) => token && !APARTE_CLASS.test(token));
1818
- if (!kept.length) continue;
1819
- dest.setAttribute("class", kept.join(" "));
1820
- continue;
1821
- }
1822
- dest.setAttribute(name, value);
1910
+ const kept = keepAttribute(tag, name, attr.value);
1911
+ if (kept !== null) dest.setAttribute(name, kept);
1823
1912
  }
1824
1913
  if (tag === "a") {
1825
- const href = (dest.getAttribute("href") ?? "").replace(CONTROL_WS, "");
1826
- const wish = (src.getAttribute("target") ?? "").trim().toLowerCase();
1827
- if (wish === "_self" && !EXTERNAL_URL.test(href)) {
1828
- dest.setAttribute("target", "_self");
1829
- } else if (wish || EXTERNAL_URL.test(href)) {
1830
- dest.setAttribute("target", "_blank");
1831
- dest.setAttribute("rel", "noopener noreferrer");
1832
- }
1914
+ for (const [name, value] of linkAttributes(dest.getAttribute("href") ?? "", src.getAttribute("target") ?? "")) dest.setAttribute(name, value);
1833
1915
  }
1834
1916
  }
1835
1917
  function sanitizeChildren(src, dest, doc) {
@@ -1846,25 +1928,179 @@ function sanitizeChildren(src, dest, doc) {
1846
1928
  sanitizeChildren(el2, dest, doc);
1847
1929
  continue;
1848
1930
  }
1931
+ const isInput = tag === "input";
1932
+ if (isInput && (el2.getAttribute("type") ?? "").trim().toLowerCase() !== "checkbox") continue;
1849
1933
  const clean = doc.createElement(tag);
1850
1934
  copyAttributes(el2, clean, tag);
1935
+ if (isInput) {
1936
+ clean.setAttribute("type", "checkbox");
1937
+ clean.setAttribute("disabled", "");
1938
+ }
1851
1939
  sanitizeChildren(el2, clean, doc);
1852
1940
  dest.appendChild(clean);
1853
1941
  }
1854
1942
  }
1855
1943
  const UNWRAPPED_TAGS = /* @__PURE__ */ new Set(["html", "head", "body"]);
1856
- const DANGEROUS_ALT = Array.from(DANGEROUS_TAGS).join("|");
1857
- const DANGEROUS_PAIRED_ALT = Array.from(DANGEROUS_TAGS).filter((t) => !UNWRAPPED_TAGS.has(t)).join("|");
1858
- const PAIRED_DANGEROUS = new RegExp(`<\\s*(${DANGEROUS_PAIRED_ALT})\\b[\\s\\S]*?<\\s*\\/\\s*\\1\\s*>`, "gi");
1859
- const LONE_DANGEROUS = new RegExp(`<\\s*\\/?\\s*(?:${DANGEROUS_ALT})\\b[^>]*>`, "gi");
1860
- const INLINE_HANDLER = /["'/\s]on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi;
1861
- const UNSAFE_SCHEME_ATTR = /(?:href|src|xlink:href)\s*=\s*(?:"\s*(?:javascript|vbscript|data):[^"]*"|'\s*(?:javascript|vbscript|data):[^']*'|(?:javascript|vbscript|data):[^\s>]*)/gi;
1862
- function fallbackScrub(html) {
1863
- let out = html.replace(PAIRED_DANGEROUS, "").replace(LONE_DANGEROUS, "");
1864
- for (let next = out.replace(INLINE_HANDLER, " "); next !== out; next = out.replace(INLINE_HANDLER, " ")) {
1865
- out = next;
1944
+ const VOID_DANGEROUS = /* @__PURE__ */ new Set(["link", "meta", "base", "embed", "frame"]);
1945
+ const END_TAGS = /* @__PURE__ */ new Map();
1946
+ function endTag(tag) {
1947
+ let re = END_TAGS.get(tag);
1948
+ if (!re) {
1949
+ re = new RegExp(`<\\s*\\/\\s*${tag}\\s*>`, "gi");
1950
+ END_TAGS.set(tag, re);
1951
+ }
1952
+ return re;
1953
+ }
1954
+ const COMMENT_END = /--!?>/g;
1955
+ const ASCII_LETTER$1 = /[A-Za-z]/;
1956
+ const SPACE = /\s/;
1957
+ const NAME_END = /[\s/>]/;
1958
+ const ATTR_NAME_END = /[\s/>=]/;
1959
+ const SAFE_ATTR_NAME = /^[a-z][a-z0-9_.:-]*$/;
1960
+ const NAMED_ENTITY = {
1961
+ amp: "&",
1962
+ lt: "<",
1963
+ gt: ">",
1964
+ quot: '"',
1965
+ apos: "'",
1966
+ colon: ":",
1967
+ lpar: "(",
1968
+ rpar: ")",
1969
+ sol: "/",
1970
+ bsol: "\\",
1971
+ period: ".",
1972
+ comma: ",",
1973
+ semi: ";",
1974
+ num: "#",
1975
+ excl: "!",
1976
+ quest: "?",
1977
+ tab: " ",
1978
+ newline: "\n"
1979
+ };
1980
+ function decodeEntities(value) {
1981
+ if (!value.includes("&")) return value;
1982
+ return value.replace(/&(?:#x([0-9a-f]+)|#([0-9]+)|([a-z]+));?/gi, (whole, hex, dec, named) => {
1983
+ if (named !== void 0) return NAMED_ENTITY[named.toLowerCase()] ?? whole;
1984
+ const code = hex !== void 0 ? parseInt(hex, 16) : parseInt(dec ?? "", 10);
1985
+ return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
1986
+ });
1987
+ }
1988
+ const escapeValue = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1989
+ function rebuildTag(tag, attrs) {
1990
+ if (!ALLOWED_TAGS.has(tag)) return "";
1991
+ const isInput = tag === "input";
1992
+ const attr = (name) => attrs.find(([n]) => n === name)?.[1];
1993
+ if (isInput && (attr("type") ?? "").trim().toLowerCase() !== "checkbox") return "";
1994
+ const written = [];
1995
+ if (isInput) {
1996
+ written.push('type="checkbox"');
1997
+ if (attr("checked") !== void 0) written.push("checked");
1998
+ written.push("disabled");
1999
+ }
2000
+ for (const [name, value] of attrs) {
2001
+ if (!SAFE_ATTR_NAME.test(name) || isInput && (name === "type" || name === "checked" || name === "disabled")) continue;
2002
+ const kept = keepAttribute(tag, name, value);
2003
+ if (kept !== null) written.push(`${name}="${escapeValue(kept)}"`);
1866
2004
  }
1867
- return out.replace(UNSAFE_SCHEME_ATTR, " ");
2005
+ if (tag === "a") {
2006
+ const href = attrs.find(([n]) => n === "href");
2007
+ const kept = href ? keepAttribute("a", "href", href[1]) : null;
2008
+ for (const [name, value] of linkAttributes(kept ?? "", attr("target") ?? "")) written.push(`${name}="${value}"`);
2009
+ }
2010
+ return `<${tag}${written.length ? " " + written.join(" ") : ""}>`;
2011
+ }
2012
+ function readTag(html, nameAt) {
2013
+ const n = html.length;
2014
+ let j = nameAt;
2015
+ while (j < n && !NAME_END.test(html[j])) j++;
2016
+ const tag = html.slice(nameAt, j).toLowerCase();
2017
+ const attrs = [];
2018
+ const seen2 = /* @__PURE__ */ new Set();
2019
+ while (j < n) {
2020
+ while (j < n && (SPACE.test(html[j]) || html[j] === "/")) j++;
2021
+ if (j >= n) break;
2022
+ if (html[j] === ">") return { tag, attrs, end: j + 1 };
2023
+ const nameStart = j++;
2024
+ while (j < n && !ATTR_NAME_END.test(html[j])) j++;
2025
+ const name = html.slice(nameStart, j).toLowerCase();
2026
+ let k = j;
2027
+ while (k < n && SPACE.test(html[k])) k++;
2028
+ let value = "";
2029
+ if (html[k] === "=") {
2030
+ k++;
2031
+ while (k < n && SPACE.test(html[k])) k++;
2032
+ const quote = html[k];
2033
+ if (quote === '"' || quote === "'") {
2034
+ const end = html.indexOf(quote, k + 1);
2035
+ if (end < 0) break;
2036
+ value = html.slice(k + 1, end);
2037
+ j = end + 1;
2038
+ } else {
2039
+ const valueStart = k;
2040
+ while (k < n && !SPACE.test(html[k]) && html[k] !== ">") k++;
2041
+ value = html.slice(valueStart, k);
2042
+ j = k;
2043
+ }
2044
+ }
2045
+ if (!seen2.has(name)) {
2046
+ seen2.add(name);
2047
+ attrs.push([name, decodeEntities(value)]);
2048
+ }
2049
+ }
2050
+ return { tag, attrs, end: -1 };
2051
+ }
2052
+ function rewriteTags(html) {
2053
+ const n = html.length;
2054
+ let out = "";
2055
+ let i = 0;
2056
+ while (i < n) {
2057
+ const lt = html.indexOf("<", i);
2058
+ if (lt < 0) {
2059
+ out += html.slice(i);
2060
+ break;
2061
+ }
2062
+ out += html.slice(i, lt);
2063
+ if (html.startsWith("<!--", lt)) {
2064
+ const at = lt + 4;
2065
+ if (html[at] === ">") i = at + 1;
2066
+ else if (html.startsWith("->", at)) i = at + 2;
2067
+ else {
2068
+ COMMENT_END.lastIndex = at;
2069
+ const m = COMMENT_END.exec(html);
2070
+ if (!m) break;
2071
+ i = m.index + m[0].length;
2072
+ }
2073
+ continue;
2074
+ }
2075
+ const closing = html[lt + 1] === "/";
2076
+ const nameAt = lt + (closing ? 2 : 1);
2077
+ if (!ASCII_LETTER$1.test(html[nameAt] ?? "")) {
2078
+ if (html[lt + 1] === "!" || html[lt + 1] === "?" || closing) {
2079
+ const end2 = html.indexOf(">", lt + 1);
2080
+ i = end2 < 0 ? n : end2 + 1;
2081
+ } else {
2082
+ out += "&lt;";
2083
+ i = lt + 1;
2084
+ }
2085
+ continue;
2086
+ }
2087
+ const { tag, attrs, end } = readTag(html, nameAt);
2088
+ if (end < 0) break;
2089
+ i = end;
2090
+ if (closing) {
2091
+ if (ALLOWED_TAGS.has(tag)) out += `</${tag}>`;
2092
+ } else if (DANGEROUS_TAGS.has(tag) && !UNWRAPPED_TAGS.has(tag) && !VOID_DANGEROUS.has(tag)) {
2093
+ const re = endTag(tag);
2094
+ re.lastIndex = end;
2095
+ const m = re.exec(html);
2096
+ if (!m) break;
2097
+ i = m.index + m[0].length;
2098
+ } else out += rebuildTag(tag, attrs);
2099
+ }
2100
+ return out;
2101
+ }
2102
+ function fallbackScrub(html) {
2103
+ return rewriteTags(html);
1868
2104
  }
1869
2105
  const defaultSanitizer = (html) => {
1870
2106
  if (!html) return html;
@@ -2502,8 +2738,12 @@ const textRenderer = {
2502
2738
  setup: (el2, segment) => {
2503
2739
  const contentEl = el2.querySelector(".aparte-segment-content");
2504
2740
  if (!contentEl) return;
2505
- renderCodeLanguages(contentEl, { streaming: segment.isStreaming === true });
2506
- if (segment.isStreaming !== true) highlightMarkdownFences(contentEl);
2741
+ if (segment.isStreaming === true) {
2742
+ writeStreamedMarkdown(el2, contentEl, segment.content, true);
2743
+ } else {
2744
+ renderCodeLanguages(contentEl, { streaming: false });
2745
+ highlightMarkdownFences(contentEl);
2746
+ }
2507
2747
  renderCitations(contentEl, segment);
2508
2748
  },
2509
2749
  update: (el2, segment) => {
@@ -2590,7 +2830,9 @@ const thinkingRenderer = {
2590
2830
  /** A block restored from storage is drawn here: `update` only runs on one that changes. */
2591
2831
  setup: (el2, segment) => {
2592
2832
  const contentEl = el2.querySelector(".aparte-thinking-content");
2593
- if (contentEl) renderCodeLanguages(contentEl, { streaming: arriving(segment) });
2833
+ if (!contentEl) return;
2834
+ if (arriving(segment)) writeStreamedMarkdown(el2, contentEl, segment.content, true);
2835
+ else renderCodeLanguages(contentEl, { streaming: false });
2594
2836
  },
2595
2837
  update: (el2, segment) => {
2596
2838
  setLabel(el2, segment);
@@ -3816,7 +4058,9 @@ function toBase64Url(bytes) {
3816
4058
  function fromBase64Url(text) {
3817
4059
  if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
3818
4060
  const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
3819
- return Uint8Array.from(binary, (c) => c.charCodeAt(0));
4061
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
4062
+ if (toBase64Url(bytes) !== text) throw new Error("not canonical base64url");
4063
+ return bytes;
3820
4064
  }
3821
4065
  function hmacKey(secret, subtle) {
3822
4066
  return subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
@@ -3873,6 +4117,8 @@ function createAparteAgentHandler(options) {
3873
4117
  const transport = options.transport ?? new AparteDirectTransport({ byok: true });
3874
4118
  const maxAge = options.ticketMaxAgeMs ?? DEFAULT_TICKET_MAX_AGE_MS;
3875
4119
  return async function handler(req) {
4120
+ const unsafe = refuseUnsafeRequest(req, options.allowedOrigins);
4121
+ if (unsafe) return unsafe;
3876
4122
  const verdict = await options.authorize(req);
3877
4123
  if (verdict instanceof Response) return verdict;
3878
4124
  if (!verdict) return jsonError(401, "Unauthorized.");
@@ -3917,6 +4163,7 @@ function createAparteAgentHandler(options) {
3917
4163
  tools: [...[...tools.values()].map((t) => t.tool), ...clientTools]
3918
4164
  };
3919
4165
  if (options.prepareRequest) request = await options.prepareRequest(request, req);
4166
+ const offered = new Set((request.tools ?? []).map((t) => t.name));
3920
4167
  const tail = unansweredTail(request.messages);
3921
4168
  if (!body.resume && tail.length > 0) {
3922
4169
  return jsonError(400, "The history ends on unanswered tool calls: a resume needs its ticket.");
@@ -3989,10 +4236,11 @@ function createAparteAgentHandler(options) {
3989
4236
  return typeof response === "string" ? response : readableToAsyncIterable(response, run.signal);
3990
4237
  },
3991
4238
  toolLookup: (name) => {
3992
- const t = tools.get(name);
4239
+ const t = offered.has(name) ? tools.get(name) : void 0;
3993
4240
  return t ? (call, signal) => t.handler(call, signal, { request: req }) : void 0;
3994
4241
  },
3995
4242
  toolConfigLookup: (name) => {
4243
+ if (!offered.has(name)) return void 0;
3996
4244
  if (external.has(name)) return { external: true };
3997
4245
  const t = tools.get(name);
3998
4246
  if (!t) return void 0;
@@ -4059,6 +4307,366 @@ function jsonError(status, message) {
4059
4307
  headers: { "Content-Type": "application/json" }
4060
4308
  });
4061
4309
  }
4310
+ function resolveImageAddress(address) {
4311
+ const base = typeof document === "undefined" ? void 0 : document.baseURI;
4312
+ try {
4313
+ return base ? new URL(address, base) : new URL(address);
4314
+ } catch {
4315
+ return null;
4316
+ }
4317
+ }
4318
+ function pageOrigin() {
4319
+ const origin = typeof location === "undefined" ? null : location.origin;
4320
+ return origin && origin !== "null" ? origin : null;
4321
+ }
4322
+ function originOf(entry) {
4323
+ try {
4324
+ const url = new URL(entry);
4325
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : null;
4326
+ } catch {
4327
+ return null;
4328
+ }
4329
+ }
4330
+ function sameImagePolicy(a, b) {
4331
+ if (a === b) return true;
4332
+ if (typeof a === "function" || typeof b === "function") return false;
4333
+ return a.length === b.length && a.every((entry, i) => entry === b[i]);
4334
+ }
4335
+ const threw = /* @__PURE__ */ new WeakSet();
4336
+ function compileImagePolicy(policy) {
4337
+ if (typeof policy === "function") {
4338
+ return (address, url) => {
4339
+ try {
4340
+ const answer = policy(url ? url.href : address);
4341
+ return answer === "load" || answer === "drop" ? answer : "hold";
4342
+ } catch (error) {
4343
+ if (!threw.has(policy)) {
4344
+ threw.add(policy);
4345
+ console.warn("[aparte] The image policy threw, so the pictures it was asked about are held.", error);
4346
+ }
4347
+ return "hold";
4348
+ }
4349
+ };
4350
+ }
4351
+ let every = false;
4352
+ let self = false;
4353
+ const origins = /* @__PURE__ */ new Set();
4354
+ for (const entry of policy) {
4355
+ const word = typeof entry === "string" ? entry.trim() : "";
4356
+ if (word === "*") every = true;
4357
+ else if (word === "self" || word === "'self'") self = true;
4358
+ else {
4359
+ const origin = originOf(word);
4360
+ if (origin) origins.add(origin);
4361
+ else console.warn(`[aparte] setImagePolicy: ${JSON.stringify(entry)} is not 'self', '*' or an http(s) origin, so it allows nothing.`);
4362
+ }
4363
+ }
4364
+ return (_address, url) => {
4365
+ if (every) return "load";
4366
+ if (!url) return "hold";
4367
+ if (origins.has(url.origin)) return "load";
4368
+ return self && url.origin === pageOrigin() ? "load" : "hold";
4369
+ };
4370
+ }
4371
+ const NO_ADDRESS = /^[\u0000- ]*$/;
4372
+ function decideImageAddress(decide, address, shown2) {
4373
+ if (NO_ADDRESS.test(address)) return "load";
4374
+ const url = resolveImageAddress(address);
4375
+ if (url) {
4376
+ if (url.protocol === "data:" || url.protocol === "blob:") return "load";
4377
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "drop";
4378
+ }
4379
+ const decision = decide(address, url);
4380
+ return decision === "hold" && url !== null && shown2?.has(url.href) ? "load" : decision;
4381
+ }
4382
+ const shownImages = /* @__PURE__ */ new WeakMap();
4383
+ function rememberShownImage(owner, address) {
4384
+ const url = resolveImageAddress(address);
4385
+ if (!url) return;
4386
+ let shown2 = shownImages.get(owner);
4387
+ if (!shown2) shownImages.set(owner, shown2 = /* @__PURE__ */ new Set());
4388
+ shown2.add(url.href);
4389
+ }
4390
+ function shownImagesOf(owner) {
4391
+ return shownImages.get(owner);
4392
+ }
4393
+ function forgetShownImages(owner) {
4394
+ shownImages.delete(owner);
4395
+ }
4396
+ const ASCII_WHITESPACE = /[\t\n\f\r ]/;
4397
+ const DESCRIPTOR = /^(?:|\d+w(?: \d+h)?|(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?x)$/;
4398
+ function parseSrcset(value) {
4399
+ const candidates = [];
4400
+ const n = value.length;
4401
+ let i = 0;
4402
+ while (i < n) {
4403
+ while (i < n && (ASCII_WHITESPACE.test(value[i]) || value[i] === ",")) i++;
4404
+ if (i >= n) break;
4405
+ const from = i;
4406
+ while (i < n && !ASCII_WHITESPACE.test(value[i])) i++;
4407
+ let url = value.slice(from, i);
4408
+ const descriptors = [];
4409
+ if (url.endsWith(",")) {
4410
+ url = url.replace(/,+$/, "");
4411
+ } else {
4412
+ let current = "";
4413
+ let state = "in";
4414
+ for (; ; ) {
4415
+ const c = value[i];
4416
+ if (state === "in") {
4417
+ if (c === void 0) {
4418
+ if (current) descriptors.push(current);
4419
+ break;
4420
+ }
4421
+ if (c === ",") {
4422
+ i++;
4423
+ if (current) descriptors.push(current);
4424
+ break;
4425
+ }
4426
+ if (ASCII_WHITESPACE.test(c)) {
4427
+ if (current) descriptors.push(current);
4428
+ current = "";
4429
+ state = "after";
4430
+ } else {
4431
+ current += c;
4432
+ if (c === "(") state = "parens";
4433
+ }
4434
+ } else if (state === "parens") {
4435
+ if (c === void 0) {
4436
+ descriptors.push(current);
4437
+ break;
4438
+ }
4439
+ current += c;
4440
+ if (c === ")") state = "in";
4441
+ } else {
4442
+ if (c === void 0) break;
4443
+ if (!ASCII_WHITESPACE.test(c)) {
4444
+ state = "in";
4445
+ continue;
4446
+ }
4447
+ }
4448
+ i++;
4449
+ }
4450
+ }
4451
+ const descriptor = descriptors.join(" ");
4452
+ if (url && DESCRIPTOR.test(descriptor)) candidates.push({ url, descriptor });
4453
+ }
4454
+ return candidates;
4455
+ }
4456
+ function writeSrcset(candidates) {
4457
+ return candidates.map((c) => c.descriptor ? `${c.url} ${c.descriptor}` : c.url).join(", ");
4458
+ }
4459
+ function imageHost(address) {
4460
+ const url = resolveImageAddress(address);
4461
+ if (url?.hostname) return url.hostname;
4462
+ const bare = address.trim();
4463
+ return bare.length > 48 ? `${bare.slice(0, 47)}…` : bare;
4464
+ }
4465
+ function heldImageHtml(address, alt, words, inLink = false) {
4466
+ const host2 = imageHost(address);
4467
+ const name = alt ? words.named(host2, alt) : words.load(host2);
4468
+ const icon = words.icon;
4469
+ const opening = inLink ? '<span class="aparte-tag aparte-image-held" role="button" tabindex="0"' : `<a class="aparte-tag aparte-image-held" href="${escapeAttr(address)}" target="_blank" rel="noopener noreferrer"`;
4470
+ return `${opening} data-aparte-image="${escapeAttr(address)}"${alt ? ` data-aparte-image-alt="${escapeAttr(alt)}"` : ""} title="${escapeAttr(words.load(host2))}" aria-label="${escapeAttr(name)}"><span class="aparte-image-held__icon" aria-hidden="true">${icon}</span>` + (alt ? `<span class="aparte-tag__label aparte-image-held__alt">${escapeHtml(alt)}</span>` : "") + `<span class="aparte-image-held__host">${escapeHtml(host2)}</span>${inLink ? "</span>" : "</a>"}`;
4471
+ }
4472
+ function loadedImageHtml(address, alt) {
4473
+ return `<img src="${escapeAttr(address)}" alt="${escapeAttr(alt)}" referrerpolicy="no-referrer">`;
4474
+ }
4475
+ const MAY_HOLD = /<(?:img|source)\b|data-aparte-image/i;
4476
+ const HELD = "a[data-aparte-image], span[data-aparte-image]";
4477
+ function applyImagePolicy(html, decide, words) {
4478
+ if (!html || !MAY_HOLD.test(html)) return html;
4479
+ return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate(html, decide, words);
4480
+ }
4481
+ function judgeImage(src, srcset, decide) {
4482
+ const candidates = srcset === void 0 ? [] : parseSrcset(srcset);
4483
+ const address = NO_ADDRESS.test(src) ? candidates[0]?.url : src;
4484
+ if (address === void 0) return null;
4485
+ const decision = decide(address);
4486
+ if (decision !== "load") return { decision, address, srcset: null };
4487
+ const kept = candidates.filter((c) => decide(c.url) === "load");
4488
+ return { decision, address, srcset: kept.length ? writeSrcset(kept) : null };
4489
+ }
4490
+ function judgeSource(src, srcset, decide) {
4491
+ if (!NO_ADDRESS.test(src) && decide(src) !== "load") return false;
4492
+ if (srcset === void 0) return NO_ADDRESS.test(src) ? false : null;
4493
+ const kept = parseSrcset(srcset).filter((c) => decide(c.url) === "load");
4494
+ if (kept.length) return writeSrcset(kept);
4495
+ return NO_ADDRESS.test(src) ? false : null;
4496
+ }
4497
+ function applyInTemplate(html, decide, words) {
4498
+ const template = document.createElement("template");
4499
+ template.innerHTML = html;
4500
+ const root = template.content;
4501
+ let held;
4502
+ let changed = false;
4503
+ const fragment = (markup) => {
4504
+ const holder = document.createElement("template");
4505
+ holder.innerHTML = markup;
4506
+ return holder.content;
4507
+ };
4508
+ for (const chip of Array.from(root.querySelectorAll(HELD))) {
4509
+ const address = chip.getAttribute("data-aparte-image") ?? "";
4510
+ const alt = chip.getAttribute("data-aparte-image-alt") ?? "";
4511
+ const decision = NO_ADDRESS.test(address) ? "drop" : decide(address);
4512
+ changed = true;
4513
+ if (decision === "drop") chip.remove();
4514
+ else chip.replaceWith(fragment(decision === "load" ? loadedImageHtml(address, alt) : heldImageHtml(address, alt, held ??= words(), !!chip.parentElement?.closest("a"))));
4515
+ }
4516
+ for (const source of Array.from(root.querySelectorAll("source"))) {
4517
+ const kept = judgeSource(source.getAttribute("src") ?? "", source.getAttribute("srcset") ?? void 0, decide);
4518
+ if (kept === false) {
4519
+ source.remove();
4520
+ changed = true;
4521
+ continue;
4522
+ }
4523
+ if (kept === null) {
4524
+ if (source.hasAttribute("srcset")) {
4525
+ source.removeAttribute("srcset");
4526
+ changed = true;
4527
+ }
4528
+ } else if (kept !== source.getAttribute("srcset")) {
4529
+ source.setAttribute("srcset", kept);
4530
+ changed = true;
4531
+ }
4532
+ }
4533
+ for (const img of Array.from(root.querySelectorAll("img"))) {
4534
+ const judged = judgeImage(img.getAttribute("src") ?? "", img.getAttribute("srcset") ?? void 0, decide);
4535
+ if (!judged) {
4536
+ if (img.hasAttribute("srcset")) {
4537
+ img.removeAttribute("srcset");
4538
+ changed = true;
4539
+ }
4540
+ if (img.parentElement?.localName === "picture" && img.getAttribute("referrerpolicy") !== "no-referrer") {
4541
+ img.setAttribute("referrerpolicy", "no-referrer");
4542
+ changed = true;
4543
+ }
4544
+ continue;
4545
+ }
4546
+ changed = true;
4547
+ if (judged.decision === "drop") {
4548
+ img.remove();
4549
+ continue;
4550
+ }
4551
+ if (judged.decision === "hold") {
4552
+ img.replaceWith(fragment(heldImageHtml(judged.address, img.getAttribute("alt") ?? "", held ??= words(), !!img.closest("a"))));
4553
+ continue;
4554
+ }
4555
+ if (judged.srcset === null) img.removeAttribute("srcset");
4556
+ else img.setAttribute("srcset", judged.srcset);
4557
+ img.setAttribute("referrerpolicy", "no-referrer");
4558
+ }
4559
+ return changed ? template.innerHTML : html;
4560
+ }
4561
+ const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4562
+ const VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
4563
+ const ASCII_LETTER = /[A-Za-z]/;
4564
+ const SAFE_NAME = /^[a-z][a-z0-9_.:-]*$/;
4565
+ function writeTag(tag, attrs, replace) {
4566
+ const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME.test(name));
4567
+ const added = Object.entries(replace).filter((entry) => entry[1] !== null);
4568
+ return `<${tag}${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
4569
+ }
4570
+ function endOf(lower, tag, from) {
4571
+ const tags = new RegExp(`<(/?)${tag}(?=[\\s/>])`, "g");
4572
+ tags.lastIndex = from;
4573
+ let depth = 1;
4574
+ for (let m = tags.exec(lower); m; m = tags.exec(lower)) {
4575
+ depth += m[1] ? -1 : 1;
4576
+ if (depth === 0) {
4577
+ const close = lower.indexOf(">", m.index);
4578
+ return close < 0 ? lower.length : close + 1;
4579
+ }
4580
+ }
4581
+ return -1;
4582
+ }
4583
+ function applyImagePolicyWithoutDom(html, decide, words) {
4584
+ if (!html || !MAY_HOLD.test(html)) return html;
4585
+ const lower = html.toLowerCase();
4586
+ const n = html.length;
4587
+ let held;
4588
+ let out = "";
4589
+ let i = 0;
4590
+ let links = 0;
4591
+ const open = [];
4592
+ while (i < n) {
4593
+ const lt = html.indexOf("<", i);
4594
+ if (lt < 0) {
4595
+ out += html.slice(i);
4596
+ break;
4597
+ }
4598
+ out += html.slice(i, lt);
4599
+ if (html.startsWith("<!--", lt)) {
4600
+ const close = html.indexOf("-->", lt + 4);
4601
+ const stop = close < 0 ? n : close + 3;
4602
+ out += html.slice(lt, stop);
4603
+ i = stop;
4604
+ continue;
4605
+ }
4606
+ const closing = html[lt + 1] === "/";
4607
+ const nameAt = lt + (closing ? 2 : 1);
4608
+ if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
4609
+ out += "<";
4610
+ i = lt + 1;
4611
+ continue;
4612
+ }
4613
+ const { tag, attrs, end } = readTag(html, nameAt);
4614
+ if (end < 0) {
4615
+ out += html.slice(lt);
4616
+ break;
4617
+ }
4618
+ i = end;
4619
+ const written = html.slice(lt, end);
4620
+ if (closing) {
4621
+ if (tag === "a") links = Math.max(0, links - 1);
4622
+ const at = open.lastIndexOf(tag);
4623
+ if (at >= 0) open.length = at;
4624
+ out += written;
4625
+ continue;
4626
+ }
4627
+ const attr = (name) => attrs.find(([key]) => key === name)?.[1];
4628
+ if (RAW_TEXT.has(tag)) {
4629
+ const close = lower.indexOf(`</${tag}`, end);
4630
+ const stop = close < 0 ? n : close;
4631
+ out += written + html.slice(end, stop);
4632
+ i = stop;
4633
+ continue;
4634
+ }
4635
+ if ((tag === "a" || tag === "span") && attr("data-aparte-image") !== void 0) {
4636
+ const stop = endOf(lower, tag, end);
4637
+ if (stop >= 0) i = stop;
4638
+ else if (tag === "a") links += 1;
4639
+ const address = attr("data-aparte-image") ?? "";
4640
+ const alt = attr("data-aparte-image-alt") ?? "";
4641
+ const decision = NO_ADDRESS.test(address) ? "drop" : decide(address);
4642
+ if (decision === "load") out += loadedImageHtml(address, alt);
4643
+ else if (decision === "hold") out += heldImageHtml(address, alt, held ??= words(), links > 0);
4644
+ continue;
4645
+ }
4646
+ if (tag === "a") links += 1;
4647
+ if (tag === "source") {
4648
+ const kept = judgeSource(attr("src") ?? "", attr("srcset"), decide);
4649
+ if (kept === false) continue;
4650
+ out += kept === (attr("srcset") ?? null) ? written : writeTag(tag, attrs, { srcset: kept });
4651
+ continue;
4652
+ }
4653
+ if (tag === "img") {
4654
+ const judged = judgeImage(attr("src") ?? "", attr("srcset"), decide);
4655
+ if (!judged) {
4656
+ const inPicture = open[open.length - 1] === "picture";
4657
+ if (attr("srcset") === void 0 && (!inPicture || attr("referrerpolicy") === "no-referrer")) out += written;
4658
+ else out += writeTag(tag, attrs, { srcset: null, ...inPicture ? { referrerpolicy: "no-referrer" } : {} });
4659
+ continue;
4660
+ }
4661
+ if (judged.decision === "hold") out += heldImageHtml(judged.address, attr("alt") ?? "", held ??= words(), links > 0);
4662
+ else if (judged.decision === "load") out += writeTag(tag, attrs, { srcset: judged.srcset, referrerpolicy: "no-referrer" });
4663
+ continue;
4664
+ }
4665
+ if (!VOID.has(tag) && !written.endsWith("/>")) open.push(tag);
4666
+ out += written;
4667
+ }
4668
+ return out;
4669
+ }
4062
4670
  class AparteElicitationAbortError extends DOMException {
4063
4671
  /**
4064
4672
  * Which of the two ways it ended.
@@ -4139,6 +4747,7 @@ class ToolTable {
4139
4747
  this.any = void 0;
4140
4748
  }
4141
4749
  }
4750
+ let heldImageNoted = false;
4142
4751
  const APARTE_DEFAULT_BUBBLE_ACTIONS = {
4143
4752
  copy: false,
4144
4753
  retry: false,
@@ -4209,6 +4818,12 @@ class AparteConfig {
4209
4818
  // LLM-authored) before it is injected via innerHTML. Default = built-in
4210
4819
  // zero-dep allowlist sanitizer; `null` disables it (trusted content only).
4211
4820
  _sanitizer = defaultSanitizer;
4821
+ // Which pictures a model or a tool chose load without a click (`image-policy.ts`): by
4822
+ // default only `data:` and `blob:`, which make no request.
4823
+ _imagePolicy = [];
4824
+ _imageDecider = compileImagePolicy([]);
4825
+ /** Whether the app named an image policy, the default included; see `decideImage`. */
4826
+ _imagePolicyNamed = false;
4212
4827
  _systemPromptTemplate;
4213
4828
  _systemPromptVarsProvider;
4214
4829
  _statusRenderer;
@@ -4503,13 +5118,86 @@ class AparteConfig {
4503
5118
  this._notify();
4504
5119
  }
4505
5120
  /**
4506
- * Run the active sanitizer over provider-produced HTML. Public so a
4507
- * streaming-markdown provider (which appends DOM directly, bypassing
4508
- * `renderMarkdown`) can apply the same policy. Returns the input unchanged
4509
- * only when sanitization was disabled via `setHtmlSanitizer(null)`.
5121
+ * Run the active sanitizer over provider-produced HTML, then the image policy
5122
+ * ({@link AparteConfig.setImagePolicy | setImagePolicy}): a picture the policy does not let
5123
+ * load comes back as a link that loads it on a click. Public so a streaming-markdown
5124
+ * provider (which appends DOM directly, bypassing `renderMarkdown`) can apply the same
5125
+ * rules. The image policy runs whichever sanitizer is set, none included, so replacing it
5126
+ * does not turn a reply's pictures back into requests the reader never made.
4510
5127
  */
4511
5128
  sanitizeHtml(html) {
4512
- return this._sanitizer ? this._sanitizer(html) : html;
5129
+ const clean = this._sanitizer ? this._sanitizer(html) : html;
5130
+ return applyImagePolicy(clean, (url) => this.decideImage(url), () => this._heldImageWords());
5131
+ }
5132
+ /**
5133
+ * Which pictures a model or a tool chose load before the reader asks — in a reply's
5134
+ * Markdown, in a card, in a tool's details. By default only `data:` and `blob:` pictures,
5135
+ * which make no request: any other is held, drawn as a small link that says where it would
5136
+ * load from, and loads in place when the reader clicks it.
5137
+ *
5138
+ * The reason is that a picture fetches its address the moment it is shown, and a
5139
+ * prompt-injected model can write the conversation into that address. Name what you trust:
5140
+ *
5141
+ * - a list — `'self'` for the page's own origin, an origin (`'https://cdn.example.com'`),
5142
+ * or `'*'` for every picture;
5143
+ * - a function, which gets the picture's address (resolved against the page) and answers
5144
+ * `'load'`, `'hold'` or `'drop'`.
5145
+ *
5146
+ * Every picture that loads goes with `referrerpolicy="no-referrer"`. What is on screen is
5147
+ * drawn again under the new policy. A CSP `img-src` is the stronger rule beside this one:
5148
+ * it also checks where a redirect leads, which no script on the page can see.
5149
+ *
5150
+ * @example aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
5151
+ * @example aparteGlobalConfig.setImagePolicy((url) => url.startsWith('https://images.example.com/') ? 'load' : 'hold');
5152
+ */
5153
+ setImagePolicy(policy) {
5154
+ this._imagePolicyNamed = true;
5155
+ if (sameImagePolicy(policy, this._imagePolicy)) return;
5156
+ this._imagePolicy = typeof policy === "function" ? policy : [...policy];
5157
+ this._imageDecider = compileImagePolicy(policy);
5158
+ bumpRenderingVersion(this);
5159
+ this._notify();
5160
+ }
5161
+ /**
5162
+ * What the picture at `url` does under this config's image policy: `'load'`, `'hold'`
5163
+ * (shown as a link that loads it on a click) or `'drop'`. For a plugin that draws pictures
5164
+ * itself, as `@aparte/plugin-cards` does: ask before setting a `src`, because setting it is
5165
+ * the request.
5166
+ */
5167
+ decideImage(url) {
5168
+ const decision = decideImageAddress(this._imageDecider, url, shownImagesOf(this));
5169
+ if (decision === "hold") this._noteHeldImage(url);
5170
+ return decision;
5171
+ }
5172
+ /**
5173
+ * The first picture the default policy holds, said once to the developer. A picture that
5174
+ * waits for a click with nothing in the console reads as a broken image to whoever wrote
5175
+ * the app, and the line that changes it cannot be guessed. Silent once the app names a
5176
+ * policy, whatever it is: `setImagePolicy([])` keeps the default and the silence.
5177
+ */
5178
+ _noteHeldImage(url) {
5179
+ if (this._imagePolicyNamed || heldImageNoted) return;
5180
+ heldImageNoted = true;
5181
+ console.warn(
5182
+ `[aparte] A picture from ${imageHost(url)} waits for the reader's click: pictures a model or a tool chose load only from the sources the app allows. To load yours, call aparteGlobalConfig.setImagePolicy(['https://cdn.example.com']); to keep holding them without this note, setImagePolicy([]). Why: https://apartejs.dev/guides/markdown/#pictures-a-reply-can-load`
5183
+ );
5184
+ }
5185
+ /**
5186
+ * The reader chose to see the picture at `url`: from now on it loads wherever this
5187
+ * config's image policy would only have held it (a picture the policy drops stays
5188
+ * dropped). Core calls it when a held picture's link is clicked; a plugin calls it from
5189
+ * its own "Show images", then draws again. Nothing on screen is redrawn by this call.
5190
+ */
5191
+ showImage(url) {
5192
+ rememberShownImage(this, url);
5193
+ }
5194
+ /** What a held picture says, in this config's language. */
5195
+ _heldImageWords() {
5196
+ return {
5197
+ load: (host2) => this.t("imageLoad").replace("{host}", () => host2),
5198
+ named: (host2, alt) => this.t("imageLoadNamed").replace("{host}", () => host2).replace("{alt}", () => alt),
5199
+ icon: this.getIcon("image")
5200
+ };
4513
5201
  }
4514
5202
  /**
4515
5203
  * Set the system prompt template. Supports `{{key}}` placeholders resolved via setSystemPromptVarsProvider.
@@ -5670,6 +6358,10 @@ class AparteConfig {
5670
6358
  this._locale = APARTE_DEFAULT_LOCALE;
5671
6359
  this._actions = [];
5672
6360
  this._sanitizer = defaultSanitizer;
6361
+ this._imagePolicy = [];
6362
+ this._imageDecider = compileImagePolicy([]);
6363
+ this._imagePolicyNamed = false;
6364
+ forgetShownImages(this);
5673
6365
  this._aiProviders.clear();
5674
6366
  this._fetchedModels.clear();
5675
6367
  this._tools.clear();
@@ -5725,6 +6417,55 @@ function subscribeConfigChange(el2, handler) {
5725
6417
  return () => window.removeEventListener(APARTE_CONFIG_CHANGE, listener);
5726
6418
  }
5727
6419
  const SUGGESTIONS_BLOCK_LANGUAGE = "suggestions";
6420
+ const SPACES = /[\p{Z}\s]+/gu;
6421
+ const DRAWS_NOTHING = /[\p{Cc}\p{Co}\p{Cn}\p{Cs}\u2800]|(?!(?:\u200C|\u200D|\uFE0E|\uFE0F))\p{Default_Ignorable_Code_Point}/u;
6422
+ const SUBDIVISION_FLAG = /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}/gu;
6423
+ const OVERPRINTS = /(?:^| )\p{M}|\p{Mn}{5,}/u;
6424
+ const JOINERS = /* @__PURE__ */ new Set(["‌", "‍", "︎", "️"]);
6425
+ const KEYCAP_BASE = /^[0-9#*]$/;
6426
+ const EMOJI = /^\p{Emoji}$/u;
6427
+ const PICTOGRAPH = /^\p{Extended_Pictographic}$/u;
6428
+ const EMOJI_MODIFIER = /^\p{Emoji_Modifier}$/u;
6429
+ const SHAPES_WITH_JOINERS = /^[\p{scx=Arab}\p{scx=Syrc}\p{scx=Thaa}\p{scx=Nkoo}\p{scx=Adlm}\p{scx=Rohg}\p{scx=Mong}\p{scx=Deva}\p{scx=Beng}\p{scx=Guru}\p{scx=Gujr}\p{scx=Orya}\p{scx=Taml}\p{scx=Telu}\p{scx=Knda}\p{scx=Mlym}\p{scx=Sinh}\p{scx=Mymr}\p{scx=Khmr}]$/u;
6430
+ const VIRAMA = /^[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D4D\u0DCA\u1039\u17D2]$/;
6431
+ function joinersBelong(label) {
6432
+ const cps = Array.from(label);
6433
+ for (let i = 0; i < cps.length; i++) {
6434
+ const c = cps[i];
6435
+ if (!JOINERS.has(c)) continue;
6436
+ const prev = cps[i - 1] ?? "";
6437
+ const next = cps[i + 1] ?? "";
6438
+ if (c === "︎" || c === "️") {
6439
+ if (KEYCAP_BASE.test(prev)) {
6440
+ if (c !== "️" || next !== "⃣") return false;
6441
+ } else if (!EMOJI.test(prev)) return false;
6442
+ continue;
6443
+ }
6444
+ if (c === "‍") {
6445
+ const base = prev === "️" ? cps[i - 2] ?? "" : prev;
6446
+ if ((PICTOGRAPH.test(base) || EMOJI_MODIFIER.test(base)) && PICTOGRAPH.test(next)) continue;
6447
+ }
6448
+ if (SHAPES_WITH_JOINERS.test(prev) && (SHAPES_WITH_JOINERS.test(next) || VIRAMA.test(prev) && (next === "" || next === " "))) continue;
6449
+ return false;
6450
+ }
6451
+ return true;
6452
+ }
6453
+ const MAX_LABEL = 100;
6454
+ function visibleReply(reply) {
6455
+ const label = (typeof reply === "string" ? reply : reply.label).replace(SPACES, " ").trim();
6456
+ if (!label || label.length > MAX_LABEL) return null;
6457
+ const drawn2 = label.replace(SUBDIVISION_FLAG, "🏴");
6458
+ if (DRAWS_NOTHING.test(drawn2)) return null;
6459
+ if (OVERPRINTS.test(drawn2) || !joinersBelong(drawn2)) return null;
6460
+ return label;
6461
+ }
6462
+ const told = /* @__PURE__ */ new Set();
6463
+ function tellDropped(source, dropped) {
6464
+ if (dropped.length === 0 || told.has(source)) return;
6465
+ if (told.size >= 50) told.clear();
6466
+ told.add(source);
6467
+ console.warn(`[aparte-suggestions] ${dropped.length} reply(ies) of a suggestions block not offered, since a chip sends exactly what it shows: ${dropped.map((d) => JSON.stringify(d)).join(", ")}. A reply must be 1 to ${MAX_LABEL} characters and hold nothing invisible (zero-width, bidi or tag characters, stray joiners).`);
6468
+ }
5728
6469
  function readReplies(source) {
5729
6470
  let parsed;
5730
6471
  try {
@@ -5733,7 +6474,15 @@ function readReplies(source) {
5733
6474
  return null;
5734
6475
  }
5735
6476
  if (!Array.isArray(parsed)) return null;
5736
- const replies = parsed.filter((r) => typeof r === "string" && r.trim() !== "" || typeof r === "object" && r !== null && typeof r.label === "string");
6477
+ const asked2 = parsed.filter((r) => typeof r === "string" || typeof r === "object" && r !== null && typeof r.label === "string");
6478
+ const replies = [];
6479
+ const dropped = [];
6480
+ for (const r of asked2) {
6481
+ const shown2 = visibleReply(r);
6482
+ if (shown2 !== null) replies.push(shown2);
6483
+ else if ((typeof r === "string" ? r : r.label).trim()) dropped.push(typeof r === "string" ? r : r.label);
6484
+ }
6485
+ tellDropped(source, dropped);
5737
6486
  return replies.length ? replies : null;
5738
6487
  }
5739
6488
  function setupSuggestionBlocks(config = aparteGlobalConfig) {
@@ -5814,6 +6563,13 @@ function defineMountedSegmentRenderer(type, mount) {
5814
6563
  mountedRenderers.add(renderer);
5815
6564
  return renderer;
5816
6565
  }
6566
+ function withLastArriving(message) {
6567
+ const segments = message.segments;
6568
+ const last = segments[segments.length - 1];
6569
+ if (message.status !== "streaming" || !last || last.isStreaming !== void 0) return segments;
6570
+ if (last.type !== "text" && last.type !== "thinking") return segments;
6571
+ return [...segments.slice(0, -1), { ...last, isStreaming: true }];
6572
+ }
5817
6573
  function populateBubbleFromMessage(bubble, message, siblingInfo) {
5818
6574
  if (message.segments && message.segments.length > 0) {
5819
6575
  const existing = bubble.getSegments?.() ?? [];
@@ -5829,7 +6585,7 @@ function populateBubbleFromMessage(bubble, message, siblingInfo) {
5829
6585
  }
5830
6586
  }
5831
6587
  } else {
5832
- bubble.setSegments?.(message.segments);
6588
+ bubble.setSegments?.(withLastArriving(message));
5833
6589
  }
5834
6590
  } else if (message.content !== void 0) {
5835
6591
  bubble.setContent?.(message.content);
@@ -6952,7 +7708,7 @@ class CheckpointStateWatcher {
6952
7708
  }
6953
7709
  }
6954
7710
  const MAX_SIBLING_RETRIES = 6;
6955
- const TREE_OWNED_FIELDS = /* @__PURE__ */ new Set(["id", "branches", "activeBranchIndex", "isStreaming"]);
7711
+ const TREE_OWNED_FIELDS = /* @__PURE__ */ new Set(["id", "isStreaming"]);
6956
7712
  const ALWAYS_PRESENT_FIELDS = /* @__PURE__ */ new Set(["content", "segments", "status"]);
6957
7713
  function sameValue(a, b) {
6958
7714
  if (a === b) return true;
@@ -9938,7 +10694,7 @@ function createAgentStreamRunner(options) {
9938
10694
  };
9939
10695
  const response = await doFetch(options.endpoint, {
9940
10696
  method: "POST",
9941
- headers: { "Content-Type": "application/json", ...headers },
10697
+ headers: jsonHeaders(headers),
9942
10698
  body: JSON.stringify(body),
9943
10699
  signal: opts.signal,
9944
10700
  ...options.credentials ? { credentials: options.credentials } : {}
@@ -10319,6 +11075,10 @@ function isAwaitingReply(message) {
10319
11075
  if (message.status === "streaming" || message.status === "pending") return true;
10320
11076
  return message.status === void 0 && message.role === "assistant" && !message.content?.trim() && !message.segments?.length;
10321
11077
  }
11078
+ const RENDERED_CONTENT = ".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";
11079
+ function inRenderedContent(el2) {
11080
+ return !!el2?.closest?.(RENDERED_CONTENT);
11081
+ }
10322
11082
  const INSTALLED = Symbol.for("aparte.dialogTriggers");
10323
11083
  let pressTarget = null;
10324
11084
  let releaseTarget = null;
@@ -10333,7 +11093,7 @@ function onClick(event) {
10333
11093
  const target = event.target;
10334
11094
  if (!target?.closest) return;
10335
11095
  const opener = target.closest("[data-aparte-dialog-open]");
10336
- if (opener) {
11096
+ if (opener && !inRenderedContent(opener)) {
10337
11097
  const id = opener.getAttribute("data-aparte-dialog-open");
10338
11098
  const dialog = id ? document.getElementById(id) : null;
10339
11099
  if (dialog instanceof HTMLDialogElement && !dialog.open) {
@@ -10343,7 +11103,7 @@ function onClick(event) {
10343
11103
  return;
10344
11104
  }
10345
11105
  const closer = target.closest("[data-aparte-dialog-close]");
10346
- if (closer) {
11106
+ if (closer && !inRenderedContent(closer)) {
10347
11107
  const dialog = closer.closest("dialog");
10348
11108
  if (dialog instanceof HTMLDialogElement && dialog.open) {
10349
11109
  event.preventDefault();
@@ -10509,8 +11269,10 @@ export {
10509
11269
  rememberConversationStatus as aN,
10510
11270
  tellConversationStatus as aO,
10511
11271
  conversationStatusOf as aP,
10512
- usageTokens as aQ,
10513
- rootOf as aR,
11272
+ visibleReply as aQ,
11273
+ usageTokens as aR,
11274
+ rootOf as aS,
11275
+ inRenderedContent as aT,
10514
11276
  renderCitations as aa,
10515
11277
  renderCodeLanguages as ab,
10516
11278
  requestUserInput as ac,
@@ -10563,4 +11325,4 @@ export {
10563
11325
  collectRendererStyles as y,
10564
11326
  contentToText as z
10565
11327
  };
10566
- //# sourceMappingURL=defer-hydration-DQKULLmH.js.map
11328
+ //# sourceMappingURL=defer-hydration-_SZv5PeY.js.map