@aparte/core 0.32.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +12 -0
  4. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  5. package/dist/components/composer/aparte-composer-send.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 +7 -6
  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 +1236 -122
  31. package/dist/{defer-hydration-ggxlbvL9.js → defer-hydration-Dw5D80FC.js} +831 -68
  32. package/dist/defer-hydration-Dw5D80FC.js.map +1 -0
  33. package/dist/elicitation/panel.d.ts.map +1 -1
  34. package/dist/generated/element-attributes.d.ts +1 -3
  35. package/dist/generated/element-attributes.d.ts.map +1 -1
  36. package/dist/index.css +1 -1
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +473 -122
  40. package/dist/index.js.map +1 -1
  41. package/dist/index.node.d.ts +2 -2
  42. package/dist/index.node.d.ts.map +1 -1
  43. package/dist/index.node.js +1 -1
  44. package/dist/index.node.js.map +1 -1
  45. package/dist/interop/dialog-triggers.d.ts.map +1 -1
  46. package/dist/interop/image-holds.d.ts +20 -0
  47. package/dist/interop/image-holds.d.ts.map +1 -0
  48. package/dist/renderers/citations.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-ggxlbvL9.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;
@@ -2152,6 +2388,8 @@ function openCard(chip) {
2152
2388
  const el2 = document.createElement("div");
2153
2389
  el2.className = "aparte-citation-card aparte-popover";
2154
2390
  el2.id = `aparte-citation-card-${++cards}`;
2391
+ const transcript = chip.closest(".aparte-viewport-container, aparte-chat-viewport") ?? chip.ownerDocument.documentElement;
2392
+ el2.dir = getComputedStyle(transcript).direction === "rtl" ? "rtl" : "ltr";
2155
2393
  el2.setAttribute("role", "dialog");
2156
2394
  el2.setAttribute("aria-label", config.getLocale().sourcesCard ?? "Sources");
2157
2395
  const body = document.createElement("div");
@@ -2293,6 +2531,7 @@ function drawCard() {
2293
2531
  link.rel = "noopener noreferrer";
2294
2532
  link.dataset.aparteCardPart = "link";
2295
2533
  link.textContent = title;
2534
+ link.dir = "auto";
2296
2535
  const hint = document.createElement("span");
2297
2536
  hint.className = "aparte-sr-only";
2298
2537
  hint.textContent = ` ${locale.opensInNewTab ?? "(opens in a new tab)"}`;
@@ -2302,6 +2541,7 @@ function drawCard() {
2302
2541
  const plain = document.createElement("p");
2303
2542
  plain.className = "aparte-citation-card__title";
2304
2543
  plain.textContent = title;
2544
+ plain.dir = "auto";
2305
2545
  body.append(plain);
2306
2546
  }
2307
2547
  const domain = sourceDomain(source);
@@ -2309,12 +2549,14 @@ function drawCard() {
2309
2549
  const p = document.createElement("p");
2310
2550
  p.className = "aparte-citation-card__domain";
2311
2551
  p.textContent = domain;
2552
+ p.dir = "auto";
2312
2553
  body.append(p);
2313
2554
  }
2314
2555
  if (source.snippet) {
2315
2556
  const p = document.createElement("p");
2316
2557
  p.className = "aparte-citation-card__snippet";
2317
2558
  p.textContent = source.snippet;
2559
+ p.dir = "auto";
2318
2560
  body.append(p);
2319
2561
  }
2320
2562
  if (sources2.length > 1) {
@@ -2385,18 +2627,20 @@ function renderSourceList(container, after, sources2, config) {
2385
2627
  link.target = "_blank";
2386
2628
  link.rel = "noopener noreferrer";
2387
2629
  link.textContent = title;
2630
+ link.dir = "auto";
2388
2631
  const hint = document.createElement("span");
2389
2632
  hint.className = "aparte-sr-only";
2390
2633
  hint.textContent = ` ${hintText}`;
2391
2634
  link.append(hint);
2392
2635
  item.append(link);
2393
2636
  } else {
2394
- item.append(title);
2637
+ item.append(Object.assign(document.createElement("span"), { textContent: title, dir: "auto" }));
2395
2638
  }
2396
2639
  if (domain && domain !== title) {
2397
2640
  const d = document.createElement("span");
2398
2641
  d.className = "aparte-sources__domain";
2399
2642
  d.textContent = domain;
2643
+ d.dir = "auto";
2400
2644
  item.append(" ", d);
2401
2645
  }
2402
2646
  items.append(item);
@@ -3808,7 +4052,9 @@ function toBase64Url(bytes) {
3808
4052
  function fromBase64Url(text) {
3809
4053
  if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
3810
4054
  const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
3811
- return Uint8Array.from(binary, (c) => c.charCodeAt(0));
4055
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
4056
+ if (toBase64Url(bytes) !== text) throw new Error("not canonical base64url");
4057
+ return bytes;
3812
4058
  }
3813
4059
  function hmacKey(secret, subtle) {
3814
4060
  return subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
@@ -3865,6 +4111,8 @@ function createAparteAgentHandler(options) {
3865
4111
  const transport = options.transport ?? new AparteDirectTransport({ byok: true });
3866
4112
  const maxAge = options.ticketMaxAgeMs ?? DEFAULT_TICKET_MAX_AGE_MS;
3867
4113
  return async function handler(req) {
4114
+ const unsafe = refuseUnsafeRequest(req, options.allowedOrigins);
4115
+ if (unsafe) return unsafe;
3868
4116
  const verdict = await options.authorize(req);
3869
4117
  if (verdict instanceof Response) return verdict;
3870
4118
  if (!verdict) return jsonError(401, "Unauthorized.");
@@ -3909,6 +4157,7 @@ function createAparteAgentHandler(options) {
3909
4157
  tools: [...[...tools.values()].map((t) => t.tool), ...clientTools]
3910
4158
  };
3911
4159
  if (options.prepareRequest) request = await options.prepareRequest(request, req);
4160
+ const offered = new Set((request.tools ?? []).map((t) => t.name));
3912
4161
  const tail = unansweredTail(request.messages);
3913
4162
  if (!body.resume && tail.length > 0) {
3914
4163
  return jsonError(400, "The history ends on unanswered tool calls: a resume needs its ticket.");
@@ -3981,10 +4230,11 @@ function createAparteAgentHandler(options) {
3981
4230
  return typeof response === "string" ? response : readableToAsyncIterable(response, run.signal);
3982
4231
  },
3983
4232
  toolLookup: (name) => {
3984
- const t = tools.get(name);
4233
+ const t = offered.has(name) ? tools.get(name) : void 0;
3985
4234
  return t ? (call, signal) => t.handler(call, signal, { request: req }) : void 0;
3986
4235
  },
3987
4236
  toolConfigLookup: (name) => {
4237
+ if (!offered.has(name)) return void 0;
3988
4238
  if (external.has(name)) return { external: true };
3989
4239
  const t = tools.get(name);
3990
4240
  if (!t) return void 0;
@@ -4051,6 +4301,366 @@ function jsonError(status, message) {
4051
4301
  headers: { "Content-Type": "application/json" }
4052
4302
  });
4053
4303
  }
4304
+ function resolveImageAddress(address) {
4305
+ const base = typeof document === "undefined" ? void 0 : document.baseURI;
4306
+ try {
4307
+ return base ? new URL(address, base) : new URL(address);
4308
+ } catch {
4309
+ return null;
4310
+ }
4311
+ }
4312
+ function pageOrigin() {
4313
+ const origin = typeof location === "undefined" ? null : location.origin;
4314
+ return origin && origin !== "null" ? origin : null;
4315
+ }
4316
+ function originOf(entry) {
4317
+ try {
4318
+ const url = new URL(entry);
4319
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : null;
4320
+ } catch {
4321
+ return null;
4322
+ }
4323
+ }
4324
+ function sameImagePolicy(a, b) {
4325
+ if (a === b) return true;
4326
+ if (typeof a === "function" || typeof b === "function") return false;
4327
+ return a.length === b.length && a.every((entry, i) => entry === b[i]);
4328
+ }
4329
+ const threw = /* @__PURE__ */ new WeakSet();
4330
+ function compileImagePolicy(policy) {
4331
+ if (typeof policy === "function") {
4332
+ return (address, url) => {
4333
+ try {
4334
+ const answer = policy(url ? url.href : address);
4335
+ return answer === "load" || answer === "drop" ? answer : "hold";
4336
+ } catch (error) {
4337
+ if (!threw.has(policy)) {
4338
+ threw.add(policy);
4339
+ console.warn("[aparte] The image policy threw, so the pictures it was asked about are held.", error);
4340
+ }
4341
+ return "hold";
4342
+ }
4343
+ };
4344
+ }
4345
+ let every = false;
4346
+ let self = false;
4347
+ const origins = /* @__PURE__ */ new Set();
4348
+ for (const entry of policy) {
4349
+ const word = typeof entry === "string" ? entry.trim() : "";
4350
+ if (word === "*") every = true;
4351
+ else if (word === "self" || word === "'self'") self = true;
4352
+ else {
4353
+ const origin = originOf(word);
4354
+ if (origin) origins.add(origin);
4355
+ else console.warn(`[aparte] setImagePolicy: ${JSON.stringify(entry)} is not 'self', '*' or an http(s) origin, so it allows nothing.`);
4356
+ }
4357
+ }
4358
+ return (_address, url) => {
4359
+ if (every) return "load";
4360
+ if (!url) return "hold";
4361
+ if (origins.has(url.origin)) return "load";
4362
+ return self && url.origin === pageOrigin() ? "load" : "hold";
4363
+ };
4364
+ }
4365
+ const NO_ADDRESS = /^[\u0000- ]*$/;
4366
+ function decideImageAddress(decide, address, shown2) {
4367
+ if (NO_ADDRESS.test(address)) return "load";
4368
+ const url = resolveImageAddress(address);
4369
+ if (url) {
4370
+ if (url.protocol === "data:" || url.protocol === "blob:") return "load";
4371
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "drop";
4372
+ }
4373
+ const decision = decide(address, url);
4374
+ return decision === "hold" && url !== null && shown2?.has(url.href) ? "load" : decision;
4375
+ }
4376
+ const shownImages = /* @__PURE__ */ new WeakMap();
4377
+ function rememberShownImage(owner, address) {
4378
+ const url = resolveImageAddress(address);
4379
+ if (!url) return;
4380
+ let shown2 = shownImages.get(owner);
4381
+ if (!shown2) shownImages.set(owner, shown2 = /* @__PURE__ */ new Set());
4382
+ shown2.add(url.href);
4383
+ }
4384
+ function shownImagesOf(owner) {
4385
+ return shownImages.get(owner);
4386
+ }
4387
+ function forgetShownImages(owner) {
4388
+ shownImages.delete(owner);
4389
+ }
4390
+ const ASCII_WHITESPACE = /[\t\n\f\r ]/;
4391
+ const DESCRIPTOR = /^(?:|\d+w(?: \d+h)?|(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?x)$/;
4392
+ function parseSrcset(value) {
4393
+ const candidates = [];
4394
+ const n = value.length;
4395
+ let i = 0;
4396
+ while (i < n) {
4397
+ while (i < n && (ASCII_WHITESPACE.test(value[i]) || value[i] === ",")) i++;
4398
+ if (i >= n) break;
4399
+ const from = i;
4400
+ while (i < n && !ASCII_WHITESPACE.test(value[i])) i++;
4401
+ let url = value.slice(from, i);
4402
+ const descriptors = [];
4403
+ if (url.endsWith(",")) {
4404
+ url = url.replace(/,+$/, "");
4405
+ } else {
4406
+ let current = "";
4407
+ let state = "in";
4408
+ for (; ; ) {
4409
+ const c = value[i];
4410
+ if (state === "in") {
4411
+ if (c === void 0) {
4412
+ if (current) descriptors.push(current);
4413
+ break;
4414
+ }
4415
+ if (c === ",") {
4416
+ i++;
4417
+ if (current) descriptors.push(current);
4418
+ break;
4419
+ }
4420
+ if (ASCII_WHITESPACE.test(c)) {
4421
+ if (current) descriptors.push(current);
4422
+ current = "";
4423
+ state = "after";
4424
+ } else {
4425
+ current += c;
4426
+ if (c === "(") state = "parens";
4427
+ }
4428
+ } else if (state === "parens") {
4429
+ if (c === void 0) {
4430
+ descriptors.push(current);
4431
+ break;
4432
+ }
4433
+ current += c;
4434
+ if (c === ")") state = "in";
4435
+ } else {
4436
+ if (c === void 0) break;
4437
+ if (!ASCII_WHITESPACE.test(c)) {
4438
+ state = "in";
4439
+ continue;
4440
+ }
4441
+ }
4442
+ i++;
4443
+ }
4444
+ }
4445
+ const descriptor = descriptors.join(" ");
4446
+ if (url && DESCRIPTOR.test(descriptor)) candidates.push({ url, descriptor });
4447
+ }
4448
+ return candidates;
4449
+ }
4450
+ function writeSrcset(candidates) {
4451
+ return candidates.map((c) => c.descriptor ? `${c.url} ${c.descriptor}` : c.url).join(", ");
4452
+ }
4453
+ function imageHost(address) {
4454
+ const url = resolveImageAddress(address);
4455
+ if (url?.hostname) return url.hostname;
4456
+ const bare = address.trim();
4457
+ return bare.length > 48 ? `${bare.slice(0, 47)}…` : bare;
4458
+ }
4459
+ function heldImageHtml(address, alt, words, inLink = false) {
4460
+ const host2 = imageHost(address);
4461
+ const name = alt ? words.named(host2, alt) : words.load(host2);
4462
+ const icon = words.icon;
4463
+ 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"`;
4464
+ 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>"}`;
4465
+ }
4466
+ function loadedImageHtml(address, alt) {
4467
+ return `<img src="${escapeAttr(address)}" alt="${escapeAttr(alt)}" referrerpolicy="no-referrer">`;
4468
+ }
4469
+ const MAY_HOLD = /<(?:img|source)\b|data-aparte-image/i;
4470
+ const HELD = "a[data-aparte-image], span[data-aparte-image]";
4471
+ function applyImagePolicy(html, decide, words) {
4472
+ if (!html || !MAY_HOLD.test(html)) return html;
4473
+ return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate(html, decide, words);
4474
+ }
4475
+ function judgeImage(src, srcset, decide) {
4476
+ const candidates = srcset === void 0 ? [] : parseSrcset(srcset);
4477
+ const address = NO_ADDRESS.test(src) ? candidates[0]?.url : src;
4478
+ if (address === void 0) return null;
4479
+ const decision = decide(address);
4480
+ if (decision !== "load") return { decision, address, srcset: null };
4481
+ const kept = candidates.filter((c) => decide(c.url) === "load");
4482
+ return { decision, address, srcset: kept.length ? writeSrcset(kept) : null };
4483
+ }
4484
+ function judgeSource(src, srcset, decide) {
4485
+ if (!NO_ADDRESS.test(src) && decide(src) !== "load") return false;
4486
+ if (srcset === void 0) return NO_ADDRESS.test(src) ? false : null;
4487
+ const kept = parseSrcset(srcset).filter((c) => decide(c.url) === "load");
4488
+ if (kept.length) return writeSrcset(kept);
4489
+ return NO_ADDRESS.test(src) ? false : null;
4490
+ }
4491
+ function applyInTemplate(html, decide, words) {
4492
+ const template = document.createElement("template");
4493
+ template.innerHTML = html;
4494
+ const root = template.content;
4495
+ let held;
4496
+ let changed = false;
4497
+ const fragment = (markup) => {
4498
+ const holder = document.createElement("template");
4499
+ holder.innerHTML = markup;
4500
+ return holder.content;
4501
+ };
4502
+ for (const chip of Array.from(root.querySelectorAll(HELD))) {
4503
+ const address = chip.getAttribute("data-aparte-image") ?? "";
4504
+ const alt = chip.getAttribute("data-aparte-image-alt") ?? "";
4505
+ const decision = NO_ADDRESS.test(address) ? "drop" : decide(address);
4506
+ changed = true;
4507
+ if (decision === "drop") chip.remove();
4508
+ else chip.replaceWith(fragment(decision === "load" ? loadedImageHtml(address, alt) : heldImageHtml(address, alt, held ??= words(), !!chip.parentElement?.closest("a"))));
4509
+ }
4510
+ for (const source of Array.from(root.querySelectorAll("source"))) {
4511
+ const kept = judgeSource(source.getAttribute("src") ?? "", source.getAttribute("srcset") ?? void 0, decide);
4512
+ if (kept === false) {
4513
+ source.remove();
4514
+ changed = true;
4515
+ continue;
4516
+ }
4517
+ if (kept === null) {
4518
+ if (source.hasAttribute("srcset")) {
4519
+ source.removeAttribute("srcset");
4520
+ changed = true;
4521
+ }
4522
+ } else if (kept !== source.getAttribute("srcset")) {
4523
+ source.setAttribute("srcset", kept);
4524
+ changed = true;
4525
+ }
4526
+ }
4527
+ for (const img of Array.from(root.querySelectorAll("img"))) {
4528
+ const judged = judgeImage(img.getAttribute("src") ?? "", img.getAttribute("srcset") ?? void 0, decide);
4529
+ if (!judged) {
4530
+ if (img.hasAttribute("srcset")) {
4531
+ img.removeAttribute("srcset");
4532
+ changed = true;
4533
+ }
4534
+ if (img.parentElement?.localName === "picture" && img.getAttribute("referrerpolicy") !== "no-referrer") {
4535
+ img.setAttribute("referrerpolicy", "no-referrer");
4536
+ changed = true;
4537
+ }
4538
+ continue;
4539
+ }
4540
+ changed = true;
4541
+ if (judged.decision === "drop") {
4542
+ img.remove();
4543
+ continue;
4544
+ }
4545
+ if (judged.decision === "hold") {
4546
+ img.replaceWith(fragment(heldImageHtml(judged.address, img.getAttribute("alt") ?? "", held ??= words(), !!img.closest("a"))));
4547
+ continue;
4548
+ }
4549
+ if (judged.srcset === null) img.removeAttribute("srcset");
4550
+ else img.setAttribute("srcset", judged.srcset);
4551
+ img.setAttribute("referrerpolicy", "no-referrer");
4552
+ }
4553
+ return changed ? template.innerHTML : html;
4554
+ }
4555
+ const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4556
+ const VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
4557
+ const ASCII_LETTER = /[A-Za-z]/;
4558
+ const SAFE_NAME = /^[a-z][a-z0-9_.:-]*$/;
4559
+ function writeTag(tag, attrs, replace) {
4560
+ const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME.test(name));
4561
+ const added = Object.entries(replace).filter((entry) => entry[1] !== null);
4562
+ return `<${tag}${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
4563
+ }
4564
+ function endOf(lower, tag, from) {
4565
+ const tags = new RegExp(`<(/?)${tag}(?=[\\s/>])`, "g");
4566
+ tags.lastIndex = from;
4567
+ let depth = 1;
4568
+ for (let m = tags.exec(lower); m; m = tags.exec(lower)) {
4569
+ depth += m[1] ? -1 : 1;
4570
+ if (depth === 0) {
4571
+ const close = lower.indexOf(">", m.index);
4572
+ return close < 0 ? lower.length : close + 1;
4573
+ }
4574
+ }
4575
+ return -1;
4576
+ }
4577
+ function applyImagePolicyWithoutDom(html, decide, words) {
4578
+ if (!html || !MAY_HOLD.test(html)) return html;
4579
+ const lower = html.toLowerCase();
4580
+ const n = html.length;
4581
+ let held;
4582
+ let out = "";
4583
+ let i = 0;
4584
+ let links = 0;
4585
+ const open = [];
4586
+ while (i < n) {
4587
+ const lt = html.indexOf("<", i);
4588
+ if (lt < 0) {
4589
+ out += html.slice(i);
4590
+ break;
4591
+ }
4592
+ out += html.slice(i, lt);
4593
+ if (html.startsWith("<!--", lt)) {
4594
+ const close = html.indexOf("-->", lt + 4);
4595
+ const stop = close < 0 ? n : close + 3;
4596
+ out += html.slice(lt, stop);
4597
+ i = stop;
4598
+ continue;
4599
+ }
4600
+ const closing = html[lt + 1] === "/";
4601
+ const nameAt = lt + (closing ? 2 : 1);
4602
+ if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
4603
+ out += "<";
4604
+ i = lt + 1;
4605
+ continue;
4606
+ }
4607
+ const { tag, attrs, end } = readTag(html, nameAt);
4608
+ if (end < 0) {
4609
+ out += html.slice(lt);
4610
+ break;
4611
+ }
4612
+ i = end;
4613
+ const written = html.slice(lt, end);
4614
+ if (closing) {
4615
+ if (tag === "a") links = Math.max(0, links - 1);
4616
+ const at = open.lastIndexOf(tag);
4617
+ if (at >= 0) open.length = at;
4618
+ out += written;
4619
+ continue;
4620
+ }
4621
+ const attr = (name) => attrs.find(([key]) => key === name)?.[1];
4622
+ if (RAW_TEXT.has(tag)) {
4623
+ const close = lower.indexOf(`</${tag}`, end);
4624
+ const stop = close < 0 ? n : close;
4625
+ out += written + html.slice(end, stop);
4626
+ i = stop;
4627
+ continue;
4628
+ }
4629
+ if ((tag === "a" || tag === "span") && attr("data-aparte-image") !== void 0) {
4630
+ const stop = endOf(lower, tag, end);
4631
+ if (stop >= 0) i = stop;
4632
+ else if (tag === "a") links += 1;
4633
+ const address = attr("data-aparte-image") ?? "";
4634
+ const alt = attr("data-aparte-image-alt") ?? "";
4635
+ const decision = NO_ADDRESS.test(address) ? "drop" : decide(address);
4636
+ if (decision === "load") out += loadedImageHtml(address, alt);
4637
+ else if (decision === "hold") out += heldImageHtml(address, alt, held ??= words(), links > 0);
4638
+ continue;
4639
+ }
4640
+ if (tag === "a") links += 1;
4641
+ if (tag === "source") {
4642
+ const kept = judgeSource(attr("src") ?? "", attr("srcset"), decide);
4643
+ if (kept === false) continue;
4644
+ out += kept === (attr("srcset") ?? null) ? written : writeTag(tag, attrs, { srcset: kept });
4645
+ continue;
4646
+ }
4647
+ if (tag === "img") {
4648
+ const judged = judgeImage(attr("src") ?? "", attr("srcset"), decide);
4649
+ if (!judged) {
4650
+ const inPicture = open[open.length - 1] === "picture";
4651
+ if (attr("srcset") === void 0 && (!inPicture || attr("referrerpolicy") === "no-referrer")) out += written;
4652
+ else out += writeTag(tag, attrs, { srcset: null, ...inPicture ? { referrerpolicy: "no-referrer" } : {} });
4653
+ continue;
4654
+ }
4655
+ if (judged.decision === "hold") out += heldImageHtml(judged.address, attr("alt") ?? "", held ??= words(), links > 0);
4656
+ else if (judged.decision === "load") out += writeTag(tag, attrs, { srcset: judged.srcset, referrerpolicy: "no-referrer" });
4657
+ continue;
4658
+ }
4659
+ if (!VOID.has(tag) && !written.endsWith("/>")) open.push(tag);
4660
+ out += written;
4661
+ }
4662
+ return out;
4663
+ }
4054
4664
  class AparteElicitationAbortError extends DOMException {
4055
4665
  /**
4056
4666
  * Which of the two ways it ended.
@@ -4131,6 +4741,7 @@ class ToolTable {
4131
4741
  this.any = void 0;
4132
4742
  }
4133
4743
  }
4744
+ let heldImageNoted = false;
4134
4745
  const APARTE_DEFAULT_BUBBLE_ACTIONS = {
4135
4746
  copy: false,
4136
4747
  retry: false,
@@ -4201,6 +4812,12 @@ class AparteConfig {
4201
4812
  // LLM-authored) before it is injected via innerHTML. Default = built-in
4202
4813
  // zero-dep allowlist sanitizer; `null` disables it (trusted content only).
4203
4814
  _sanitizer = defaultSanitizer;
4815
+ // Which pictures a model or a tool chose load without a click (`image-policy.ts`): by
4816
+ // default only `data:` and `blob:`, which make no request.
4817
+ _imagePolicy = [];
4818
+ _imageDecider = compileImagePolicy([]);
4819
+ /** Whether the app named an image policy, the default included; see `decideImage`. */
4820
+ _imagePolicyNamed = false;
4204
4821
  _systemPromptTemplate;
4205
4822
  _systemPromptVarsProvider;
4206
4823
  _statusRenderer;
@@ -4495,13 +5112,86 @@ class AparteConfig {
4495
5112
  this._notify();
4496
5113
  }
4497
5114
  /**
4498
- * Run the active sanitizer over provider-produced HTML. Public so a
4499
- * streaming-markdown provider (which appends DOM directly, bypassing
4500
- * `renderMarkdown`) can apply the same policy. Returns the input unchanged
4501
- * only when sanitization was disabled via `setHtmlSanitizer(null)`.
5115
+ * Run the active sanitizer over provider-produced HTML, then the image policy
5116
+ * ({@link AparteConfig.setImagePolicy | setImagePolicy}): a picture the policy does not let
5117
+ * load comes back as a link that loads it on a click. Public so a streaming-markdown
5118
+ * provider (which appends DOM directly, bypassing `renderMarkdown`) can apply the same
5119
+ * rules. The image policy runs whichever sanitizer is set, none included, so replacing it
5120
+ * does not turn a reply's pictures back into requests the reader never made.
4502
5121
  */
4503
5122
  sanitizeHtml(html) {
4504
- return this._sanitizer ? this._sanitizer(html) : html;
5123
+ const clean = this._sanitizer ? this._sanitizer(html) : html;
5124
+ return applyImagePolicy(clean, (url) => this.decideImage(url), () => this._heldImageWords());
5125
+ }
5126
+ /**
5127
+ * Which pictures a model or a tool chose load before the reader asks — in a reply's
5128
+ * Markdown, in a card, in a tool's details. By default only `data:` and `blob:` pictures,
5129
+ * which make no request: any other is held, drawn as a small link that says where it would
5130
+ * load from, and loads in place when the reader clicks it.
5131
+ *
5132
+ * The reason is that a picture fetches its address the moment it is shown, and a
5133
+ * prompt-injected model can write the conversation into that address. Name what you trust:
5134
+ *
5135
+ * - a list — `'self'` for the page's own origin, an origin (`'https://cdn.example.com'`),
5136
+ * or `'*'` for every picture;
5137
+ * - a function, which gets the picture's address (resolved against the page) and answers
5138
+ * `'load'`, `'hold'` or `'drop'`.
5139
+ *
5140
+ * Every picture that loads goes with `referrerpolicy="no-referrer"`. What is on screen is
5141
+ * drawn again under the new policy. A CSP `img-src` is the stronger rule beside this one:
5142
+ * it also checks where a redirect leads, which no script on the page can see.
5143
+ *
5144
+ * @example aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
5145
+ * @example aparteGlobalConfig.setImagePolicy((url) => url.startsWith('https://images.example.com/') ? 'load' : 'hold');
5146
+ */
5147
+ setImagePolicy(policy) {
5148
+ this._imagePolicyNamed = true;
5149
+ if (sameImagePolicy(policy, this._imagePolicy)) return;
5150
+ this._imagePolicy = typeof policy === "function" ? policy : [...policy];
5151
+ this._imageDecider = compileImagePolicy(policy);
5152
+ bumpRenderingVersion(this);
5153
+ this._notify();
5154
+ }
5155
+ /**
5156
+ * What the picture at `url` does under this config's image policy: `'load'`, `'hold'`
5157
+ * (shown as a link that loads it on a click) or `'drop'`. For a plugin that draws pictures
5158
+ * itself, as `@aparte/plugin-cards` does: ask before setting a `src`, because setting it is
5159
+ * the request.
5160
+ */
5161
+ decideImage(url) {
5162
+ const decision = decideImageAddress(this._imageDecider, url, shownImagesOf(this));
5163
+ if (decision === "hold") this._noteHeldImage(url);
5164
+ return decision;
5165
+ }
5166
+ /**
5167
+ * The first picture the default policy holds, said once to the developer. A picture that
5168
+ * waits for a click with nothing in the console reads as a broken image to whoever wrote
5169
+ * the app, and the line that changes it cannot be guessed. Silent once the app names a
5170
+ * policy, whatever it is: `setImagePolicy([])` keeps the default and the silence.
5171
+ */
5172
+ _noteHeldImage(url) {
5173
+ if (this._imagePolicyNamed || heldImageNoted) return;
5174
+ heldImageNoted = true;
5175
+ console.warn(
5176
+ `[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`
5177
+ );
5178
+ }
5179
+ /**
5180
+ * The reader chose to see the picture at `url`: from now on it loads wherever this
5181
+ * config's image policy would only have held it (a picture the policy drops stays
5182
+ * dropped). Core calls it when a held picture's link is clicked; a plugin calls it from
5183
+ * its own "Show images", then draws again. Nothing on screen is redrawn by this call.
5184
+ */
5185
+ showImage(url) {
5186
+ rememberShownImage(this, url);
5187
+ }
5188
+ /** What a held picture says, in this config's language. */
5189
+ _heldImageWords() {
5190
+ return {
5191
+ load: (host2) => this.t("imageLoad").replace("{host}", () => host2),
5192
+ named: (host2, alt) => this.t("imageLoadNamed").replace("{host}", () => host2).replace("{alt}", () => alt),
5193
+ icon: this.getIcon("image")
5194
+ };
4505
5195
  }
4506
5196
  /**
4507
5197
  * Set the system prompt template. Supports `{{key}}` placeholders resolved via setSystemPromptVarsProvider.
@@ -5662,6 +6352,10 @@ class AparteConfig {
5662
6352
  this._locale = APARTE_DEFAULT_LOCALE;
5663
6353
  this._actions = [];
5664
6354
  this._sanitizer = defaultSanitizer;
6355
+ this._imagePolicy = [];
6356
+ this._imageDecider = compileImagePolicy([]);
6357
+ this._imagePolicyNamed = false;
6358
+ forgetShownImages(this);
5665
6359
  this._aiProviders.clear();
5666
6360
  this._fetchedModels.clear();
5667
6361
  this._tools.clear();
@@ -5717,6 +6411,55 @@ function subscribeConfigChange(el2, handler) {
5717
6411
  return () => window.removeEventListener(APARTE_CONFIG_CHANGE, listener);
5718
6412
  }
5719
6413
  const SUGGESTIONS_BLOCK_LANGUAGE = "suggestions";
6414
+ const SPACES = /[\p{Z}\s]+/gu;
6415
+ const DRAWS_NOTHING = /[\p{Cc}\p{Co}\p{Cn}\p{Cs}\u2800]|(?!(?:\u200C|\u200D|\uFE0E|\uFE0F))\p{Default_Ignorable_Code_Point}/u;
6416
+ 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;
6417
+ const OVERPRINTS = /(?:^| )\p{M}|\p{Mn}{5,}/u;
6418
+ const JOINERS = /* @__PURE__ */ new Set(["‌", "‍", "︎", "️"]);
6419
+ const KEYCAP_BASE = /^[0-9#*]$/;
6420
+ const EMOJI = /^\p{Emoji}$/u;
6421
+ const PICTOGRAPH = /^\p{Extended_Pictographic}$/u;
6422
+ const EMOJI_MODIFIER = /^\p{Emoji_Modifier}$/u;
6423
+ 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;
6424
+ const VIRAMA = /^[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D4D\u0DCA\u1039\u17D2]$/;
6425
+ function joinersBelong(label) {
6426
+ const cps = Array.from(label);
6427
+ for (let i = 0; i < cps.length; i++) {
6428
+ const c = cps[i];
6429
+ if (!JOINERS.has(c)) continue;
6430
+ const prev = cps[i - 1] ?? "";
6431
+ const next = cps[i + 1] ?? "";
6432
+ if (c === "︎" || c === "️") {
6433
+ if (KEYCAP_BASE.test(prev)) {
6434
+ if (c !== "️" || next !== "⃣") return false;
6435
+ } else if (!EMOJI.test(prev)) return false;
6436
+ continue;
6437
+ }
6438
+ if (c === "‍") {
6439
+ const base = prev === "️" ? cps[i - 2] ?? "" : prev;
6440
+ if ((PICTOGRAPH.test(base) || EMOJI_MODIFIER.test(base)) && PICTOGRAPH.test(next)) continue;
6441
+ }
6442
+ if (SHAPES_WITH_JOINERS.test(prev) && (SHAPES_WITH_JOINERS.test(next) || VIRAMA.test(prev) && (next === "" || next === " "))) continue;
6443
+ return false;
6444
+ }
6445
+ return true;
6446
+ }
6447
+ const MAX_LABEL = 100;
6448
+ function visibleReply(reply) {
6449
+ const label = (typeof reply === "string" ? reply : reply.label).replace(SPACES, " ").trim();
6450
+ if (!label || label.length > MAX_LABEL) return null;
6451
+ const drawn2 = label.replace(SUBDIVISION_FLAG, "🏴");
6452
+ if (DRAWS_NOTHING.test(drawn2)) return null;
6453
+ if (OVERPRINTS.test(drawn2) || !joinersBelong(drawn2)) return null;
6454
+ return label;
6455
+ }
6456
+ const told = /* @__PURE__ */ new Set();
6457
+ function tellDropped(source, dropped) {
6458
+ if (dropped.length === 0 || told.has(source)) return;
6459
+ if (told.size >= 50) told.clear();
6460
+ told.add(source);
6461
+ 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).`);
6462
+ }
5720
6463
  function readReplies(source) {
5721
6464
  let parsed;
5722
6465
  try {
@@ -5725,7 +6468,15 @@ function readReplies(source) {
5725
6468
  return null;
5726
6469
  }
5727
6470
  if (!Array.isArray(parsed)) return null;
5728
- const replies = parsed.filter((r) => typeof r === "string" && r.trim() !== "" || typeof r === "object" && r !== null && typeof r.label === "string");
6471
+ const asked2 = parsed.filter((r) => typeof r === "string" || typeof r === "object" && r !== null && typeof r.label === "string");
6472
+ const replies = [];
6473
+ const dropped = [];
6474
+ for (const r of asked2) {
6475
+ const shown2 = visibleReply(r);
6476
+ if (shown2 !== null) replies.push(shown2);
6477
+ else if ((typeof r === "string" ? r : r.label).trim()) dropped.push(typeof r === "string" ? r : r.label);
6478
+ }
6479
+ tellDropped(source, dropped);
5729
6480
  return replies.length ? replies : null;
5730
6481
  }
5731
6482
  function setupSuggestionBlocks(config = aparteGlobalConfig) {
@@ -6944,7 +7695,7 @@ class CheckpointStateWatcher {
6944
7695
  }
6945
7696
  }
6946
7697
  const MAX_SIBLING_RETRIES = 6;
6947
- const TREE_OWNED_FIELDS = /* @__PURE__ */ new Set(["id", "branches", "activeBranchIndex", "isStreaming"]);
7698
+ const TREE_OWNED_FIELDS = /* @__PURE__ */ new Set(["id", "isStreaming"]);
6948
7699
  const ALWAYS_PRESENT_FIELDS = /* @__PURE__ */ new Set(["content", "segments", "status"]);
6949
7700
  function sameValue(a, b) {
6950
7701
  if (a === b) return true;
@@ -7982,6 +8733,7 @@ function el$1(tag, className, text) {
7982
8733
  function optionBody(label, description, recommended) {
7983
8734
  const body = el$1("span", "aparte-elic-option-body");
7984
8735
  const title = el$1("span", "aparte-elic-option-title", label);
8736
+ title.dir = "auto";
7985
8737
  if (recommended) {
7986
8738
  const badge = el$1(
7987
8739
  "span",
@@ -7991,7 +8743,7 @@ function optionBody(label, description, recommended) {
7991
8743
  title.append(" ", badge);
7992
8744
  }
7993
8745
  body.appendChild(title);
7994
- if (description) body.appendChild(el$1("span", "aparte-elic-option-desc", description));
8746
+ if (description) body.appendChild(Object.assign(el$1("span", "aparte-elic-option-desc", description), { dir: "auto" }));
7995
8747
  return body;
7996
8748
  }
7997
8749
  function commandOption(label, description, recommended) {
@@ -8004,11 +8756,12 @@ function fieldHeader(parent, field, skipTitle) {
8004
8756
  let titleId;
8005
8757
  if (field.title && field.title.trim() !== skipTitle?.trim()) {
8006
8758
  const title = el$1("p", "aparte-elic-title", field.title);
8759
+ title.dir = "auto";
8007
8760
  titleId = `elic-title-${uuid()}`;
8008
8761
  title.id = titleId;
8009
8762
  parent.appendChild(title);
8010
8763
  }
8011
- if (field.description) parent.appendChild(el$1("p", "aparte-elic-desc", field.description));
8764
+ if (field.description) parent.appendChild(Object.assign(el$1("p", "aparte-elic-desc", field.description), { dir: "auto" }));
8012
8765
  return titleId;
8013
8766
  }
8014
8767
  function labelGroup(list, opts) {
@@ -8187,6 +8940,7 @@ function buildBooleanField(field, onChange, fallbackLabel, settle) {
8187
8940
  if (field.default != null && String(field.default) === val) control.checked = true;
8188
8941
  const body = el$1("span", "aparte-elic-option-body");
8189
8942
  const title = el$1("span", "aparte-elic-option-title", label);
8943
+ title.dir = "auto";
8190
8944
  if (defaulted) onRelabel(() => {
8191
8945
  title.textContent = contextConfig().t(defaulted);
8192
8946
  });
@@ -8274,7 +9028,7 @@ function buildElicitationPanel(message, schema, onChange) {
8274
9028
  function buildPanel(message, schema, onChange) {
8275
9029
  const panel = el$1("div", "aparte-elic-panel");
8276
9030
  const asked2 = typeof message === "function" ? message() : message;
8277
- if (asked2) panel.appendChild(el$1("p", "aparte-elic-message", asked2));
9031
+ if (asked2) panel.appendChild(Object.assign(el$1("p", "aparte-elic-message", asked2), { dir: "auto" }));
8278
9032
  let settleCb = null;
8279
9033
  let settled2 = false;
8280
9034
  const settle = (content) => {
@@ -8309,7 +9063,7 @@ function buildPanel(message, schema, onChange) {
8309
9063
  const fields = entries.map(([key, field2]) => {
8310
9064
  const built = buildField(field2, notify, void 0, key);
8311
9065
  if (!field2.title && !built.el.querySelector(".aparte-elic-title")) {
8312
- built.el.insertBefore(el$1("p", "aparte-elic-title", key), built.el.firstChild);
9066
+ built.el.insertBefore(Object.assign(el$1("p", "aparte-elic-title", key), { dir: "auto" }), built.el.firstChild);
8313
9067
  }
8314
9068
  body.appendChild(built.el);
8315
9069
  return { key, field: built, required: requiredKeys.has(key), header: field2.header };
@@ -8342,6 +9096,7 @@ function buildPanel(message, schema, onChange) {
8342
9096
  chip.type = "button";
8343
9097
  chip.setAttribute("role", "tab");
8344
9098
  chip.textContent = f.header?.trim() || String(i + 1);
9099
+ chip.dir = "auto";
8345
9100
  chip.addEventListener("click", () => {
8346
9101
  show(i);
8347
9102
  f.field.focus();
@@ -8352,7 +9107,9 @@ function buildPanel(message, schema, onChange) {
8352
9107
  f.field.el.setAttribute("aria-labelledby", chip.id);
8353
9108
  chip.setAttribute("aria-controls", f.field.el.id);
8354
9109
  chip.addEventListener("keydown", (e) => {
8355
- const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
9110
+ const forward = getComputedStyle(steps).direction === "rtl" ? "ArrowLeft" : "ArrowRight";
9111
+ const back = forward === "ArrowRight" ? "ArrowLeft" : "ArrowRight";
9112
+ const step = e.key === forward ? 1 : e.key === back ? -1 : 0;
8356
9113
  let next = -1;
8357
9114
  if (step) next = (i + step + fields.length) % fields.length;
8358
9115
  else if (e.key === "Home") next = 0;
@@ -8419,7 +9176,7 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
8419
9176
  const body = el("div", "aparte-elic-body");
8420
9177
  panel.appendChild(body);
8421
9178
  const askText = () => typeof message === "function" ? message() : message;
8422
- const ask = askText() ? el("p", "aparte-elic-message", askText()) : null;
9179
+ const ask = askText() ? Object.assign(el("p", "aparte-elic-message", askText()), { dir: "auto" }) : null;
8423
9180
  if (ask) body.appendChild(ask);
8424
9181
  let argsLabel = null;
8425
9182
  if (details) {
@@ -9924,7 +10681,7 @@ function createAgentStreamRunner(options) {
9924
10681
  };
9925
10682
  const response = await doFetch(options.endpoint, {
9926
10683
  method: "POST",
9927
- headers: { "Content-Type": "application/json", ...headers },
10684
+ headers: jsonHeaders(headers),
9928
10685
  body: JSON.stringify(body),
9929
10686
  signal: opts.signal,
9930
10687
  ...options.credentials ? { credentials: options.credentials } : {}
@@ -10305,6 +11062,10 @@ function isAwaitingReply(message) {
10305
11062
  if (message.status === "streaming" || message.status === "pending") return true;
10306
11063
  return message.status === void 0 && message.role === "assistant" && !message.content?.trim() && !message.segments?.length;
10307
11064
  }
11065
+ const RENDERED_CONTENT = ".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";
11066
+ function inRenderedContent(el2) {
11067
+ return !!el2?.closest?.(RENDERED_CONTENT);
11068
+ }
10308
11069
  const INSTALLED = Symbol.for("aparte.dialogTriggers");
10309
11070
  let pressTarget = null;
10310
11071
  let releaseTarget = null;
@@ -10319,7 +11080,7 @@ function onClick(event) {
10319
11080
  const target = event.target;
10320
11081
  if (!target?.closest) return;
10321
11082
  const opener = target.closest("[data-aparte-dialog-open]");
10322
- if (opener) {
11083
+ if (opener && !inRenderedContent(opener)) {
10323
11084
  const id = opener.getAttribute("data-aparte-dialog-open");
10324
11085
  const dialog = id ? document.getElementById(id) : null;
10325
11086
  if (dialog instanceof HTMLDialogElement && !dialog.open) {
@@ -10329,7 +11090,7 @@ function onClick(event) {
10329
11090
  return;
10330
11091
  }
10331
11092
  const closer = target.closest("[data-aparte-dialog-close]");
10332
- if (closer) {
11093
+ if (closer && !inRenderedContent(closer)) {
10333
11094
  const dialog = closer.closest("dialog");
10334
11095
  if (dialog instanceof HTMLDialogElement && dialog.open) {
10335
11096
  event.preventDefault();
@@ -10495,8 +11256,10 @@ export {
10495
11256
  rememberConversationStatus as aN,
10496
11257
  tellConversationStatus as aO,
10497
11258
  conversationStatusOf as aP,
10498
- usageTokens as aQ,
10499
- rootOf as aR,
11259
+ visibleReply as aQ,
11260
+ usageTokens as aR,
11261
+ rootOf as aS,
11262
+ inRenderedContent as aT,
10500
11263
  renderCitations as aa,
10501
11264
  renderCodeLanguages as ab,
10502
11265
  requestUserInput as ac,
@@ -10549,4 +11312,4 @@ export {
10549
11312
  collectRendererStyles as y,
10550
11313
  contentToText as z
10551
11314
  };
10552
- //# sourceMappingURL=defer-hydration-ggxlbvL9.js.map
11315
+ //# sourceMappingURL=defer-hydration-Dw5D80FC.js.map