@vectoriox/iox-ui 5.113.0 → 5.114.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.
@@ -1,4 +1,4 @@
1
- import { AiStep, STRICT_SCHEMA_BUDGET, strictSchemaComplexity, jsonText, jsonListOf, jsonOneOf, jsonClosedObject, jsonAnyOf } from '@vectoriox/iox-ui/generation-core';
1
+ import { AiStep, STRICT_SCHEMA_BUDGET, strictSchemaComplexity, jsonText, jsonListOf, jsonOneOf, jsonClosedObject, jsonAnyOf, PlanWordIssueCode, factIssues, walkSerialized } from '@vectoriox/iox-ui/generation-core';
2
2
 
3
3
  /**
4
4
  * The surfaces AI Assist runs on (ai-assist-plan §2, §4): each screen that offers a prompt registers ONE spec — what it
@@ -92,14 +92,16 @@ const spec = (s) => ({
92
92
  ...s,
93
93
  });
94
94
  const SURFACES = {
95
+ // S1 offers only the families the server answers (the route can never pick one it cannot): Words first (AI2a);
96
+ // Style, Sections and Look & motion join as each slice ships (ai-assist-plan §6, AI2).
95
97
  [AssistSurface.BuilderPage]: spec({
96
98
  surface: AssistSurface.BuilderPage,
97
- families: [EditFamily.Words, EditFamily.Sections, EditFamily.Style, EditFamily.Look],
99
+ families: [EditFamily.Words],
98
100
  commit: CommitKind.BuilderStep,
99
101
  steps: [AssistStep.AssistRoute, AssistStep.AssistEdit],
100
102
  permissions: [AssistPermission.PageUpdate],
101
103
  scopes: [AssistScope.Node, AssistScope.Section, AssistScope.Page],
102
- status: SurfaceStatus.Planned,
104
+ status: SurfaceStatus.Built,
103
105
  }),
104
106
  [AssistSurface.ContentItem]: spec({
105
107
  surface: AssistSurface.ContentItem,
@@ -249,6 +251,10 @@ var AssistIssueCode;
249
251
  AssistIssueCode["SentenceTooLong"] = "sentenceTooLong";
250
252
  AssistIssueCode["MissingHandles"] = "missingHandles";
251
253
  AssistIssueCode["MissingValues"] = "missingValues";
254
+ /** Looks like an e-mail, phone, price or time nobody gave (generation-core `factIssues`, R-H2). */
255
+ AssistIssueCode["InventedFact"] = "inventedFact";
256
+ /** A word this site must not use. */
257
+ AssistIssueCode["AvoidWord"] = "avoidWord";
252
258
  })(AssistIssueCode || (AssistIssueCode = {}));
253
259
  /** A caller's mistake building a brief (a focus that is not on the screen) — never a model answer. */
254
260
  class AssistBriefError extends Error {
@@ -485,6 +491,8 @@ function richTextParagraphs(value) {
485
491
  .map(p => p.replace(/\s+/g, ' ').trim())
486
492
  .filter(Boolean);
487
493
  }
494
+ /** One line of plain text as stored HTML: every character escaped (a heading's or a button's words). */
495
+ const escapeText = (text) => escape(text);
488
496
  /** Paragraphs as the editor's HTML: one `<p>` each, escaped. */
489
497
  function paragraphsToRichText(paragraphs) {
490
498
  return paragraphs.map(p => `<p>${escape(p.trim())}</p>`).join('');
@@ -713,7 +721,7 @@ function chosen(all, wanted) {
713
721
  }).filter(isWritable);
714
722
  }
715
723
  /** Splits n fields into the fewest parts that fit, as even as they come. */
716
- function split(list, max) {
724
+ function split$1(list, max) {
717
725
  if (!list.length)
718
726
  return [];
719
727
  const count = Math.ceil(list.length / max);
@@ -729,19 +737,19 @@ function partSchema(fields, locale, part, of) {
729
737
  }, Object.values(FieldsAnswerKey));
730
738
  }
731
739
  function fieldsJsonSchema(schema, options) {
732
- const groups = split(chosen(assistFields(schema), options.fields), FIELDS_PER_PART);
740
+ const groups = split$1(chosen(assistFields(schema), options.fields), FIELDS_PER_PART);
733
741
  const parts = groups.map((g, i) => partSchema(g, options.locale, i, groups.length));
734
742
  parts.forEach((p, i) => assertAssistBudget(`fields ${schema.name} part ${i + 1}`, [p]));
735
743
  return { parts, handles: groups.map(g => g.map(f => f.handle)) };
736
744
  }
737
- const isLeave = (v) => v === null || v === undefined || v === NONE_TEXT || (Array.isArray(v) && v.length === 0);
745
+ const isLeave$1 = (v) => v === null || v === undefined || v === NONE_TEXT || (Array.isArray(v) && v.length === 0);
738
746
  /** The parts' answers → the edits they make (every leave value dropped). */
739
747
  function decodeFieldsAnswers(answers) {
740
748
  return answers.flatMap(answer => {
741
749
  const fields = answer && typeof answer === 'object' ? answer[FieldsAnswerKey.Fields] : undefined;
742
750
  if (!fields || typeof fields !== 'object' || Array.isArray(fields))
743
751
  return [];
744
- return Object.entries(fields).filter(([, v]) => !isLeave(v)).map(([handle, value]) => ({ handle, value }));
752
+ return Object.entries(fields).filter(([, v]) => !isLeave$1(v)).map(([handle, value]) => ({ handle, value }));
745
753
  });
746
754
  }
747
755
 
@@ -778,6 +786,20 @@ function readRoute(surface, answer) {
778
786
  return { ok: !issues.length, families: cannot ? [] : families, cannot, reply: text(a[RouteAnswerKey.Reply]), issues };
779
787
  }
780
788
 
789
+ const CODES = {
790
+ [PlanWordIssueCode.InventedFact]: AssistIssueCode.InventedFact,
791
+ [PlanWordIssueCode.AvoidWord]: AssistIssueCode.AvoidWord,
792
+ };
793
+ function assistFactIssues(written, ctx) {
794
+ if (!written.length)
795
+ return [];
796
+ return factIssues(written.map(w => ({ path: w.handle, text: w.text })), {
797
+ avoidWords: ctx.words?.avoidWords ?? [],
798
+ facts: ctx.words?.facts ?? {},
799
+ known: [...(ctx.words?.known ?? []), ...(ctx.sentence ? [ctx.sentence] : []), ...ctx.existing],
800
+ }).map(f => ({ code: CODES[f.code] ?? AssistIssueCode.InventedFact, handle: f.path, message: f.message }));
801
+ }
802
+
781
803
  const refuse = (code, message) => ({ ok: false, code, message });
782
804
  const wrongType = (what) => refuse(AssistIssueCode.WrongType, `expected ${what}`);
783
805
  const fine = (stored, readable = stored) => ({ ok: true, stored, readable });
@@ -863,6 +885,16 @@ function plan(field, handle, values, coerced, locale) {
863
885
  };
864
886
  return { field, stored, change };
865
887
  }
888
+ /** The words in a value (a text, paragraphs, a list, a multiLang record) — what the fact gate reads. */
889
+ function wordsOf(value) {
890
+ if (typeof value === 'string')
891
+ return value.trim() ? [value] : [];
892
+ if (Array.isArray(value))
893
+ return value.flatMap(wordsOf);
894
+ if (isPlainRecord(value))
895
+ return Object.values(value).flatMap(wordsOf);
896
+ return [];
897
+ }
866
898
  function applyFieldEdits(values, edits, ctx) {
867
899
  const fields = assistFields(ctx.schema);
868
900
  const issues = [];
@@ -902,6 +934,9 @@ function applyFieldEdits(values, edits, ctx) {
902
934
  if (p)
903
935
  planned.push(p);
904
936
  }
937
+ issues.push(...assistFactIssues(planned.flatMap(p => wordsOf(p.change.after).map(text => ({ handle: p.change.handle, text }))), {
938
+ words: ctx.words, sentence: ctx.sentence, existing: Object.values(values).flatMap(wordsOf),
939
+ }));
905
940
  if (issues.length)
906
941
  return { ok: false, result: { ...values }, changes: [], kept: [], issues };
907
942
  const edited = names(ctx.ownerEdited, fields);
@@ -914,6 +949,436 @@ function applyFieldEdits(values, edits, ctx) {
914
949
  return { ok: true, result, changes: applied.map(p => p.change), kept: planned.filter(isKept).map(p => p.change), issues: [] };
915
950
  }
916
951
 
952
+ /**
953
+ * The ONE locale a content-item turn writes in (plan §3c rule 8, trap T5) — decided the same way by the server and the
954
+ * client: a multiLang field gets this key and no other. The sentence decides when it names a language ("translate the
955
+ * summary to English", "תרגם לאנגלית") — matched against the runtime's own language names (`Intl.DisplayNames`) in the
956
+ * languages the admin speaks, never a hand-kept list; the last one named wins. Otherwise the item's own language: the
957
+ * locale most of its multiLang fields are filled in (schema order breaks a tie); else the admin's; else the first.
958
+ */
959
+ /** The languages whose names a sentence may use — the admin's two UI languages. */
960
+ const LOCALE_NAME_LANGUAGES = ['en', 'he'];
961
+ const DISPLAY_TYPE_LANGUAGE = 'language';
962
+ /** Every locale the type's multiLang fields hold, in schema order. */
963
+ function itemLocales(fields) {
964
+ return [...new Set(fields.flatMap(f => f.locales ?? []))];
965
+ }
966
+ function displayName(locale, inLanguage) {
967
+ try {
968
+ const name = new Intl.DisplayNames([inLanguage], { type: DISPLAY_TYPE_LANGUAGE }).of(locale);
969
+ return name && name !== locale ? name : null;
970
+ }
971
+ catch {
972
+ return null;
973
+ }
974
+ }
975
+ function languageNames(locale, languages) {
976
+ return languages.flatMap(lang => {
977
+ const name = displayName(locale, lang);
978
+ return name ? [name.toLowerCase()] : [];
979
+ });
980
+ }
981
+ /** The last position a locale's name appears at in the sentence, or -1. */
982
+ function lastMention(sentence, locale, languages) {
983
+ const s = sentence.toLowerCase();
984
+ return Math.max(-1, ...languageNames(locale, languages).map(n => s.lastIndexOf(n)));
985
+ }
986
+ /** The locale the sentence names; the last one named wins ("the Hebrew summary to English" → en). */
987
+ function namedLocale(sentence, locales, languages = LOCALE_NAME_LANGUAGES) {
988
+ const named = locales
989
+ .map(locale => ({ locale, at: lastMention(sentence, locale, languages) }))
990
+ .filter(m => m.at >= 0)
991
+ .sort((a, b) => b.at - a.at);
992
+ return named[0]?.locale ?? null;
993
+ }
994
+ /** The locale most of the item's multiLang fields are filled in (schema order breaks a tie); else the UI's; else the first. */
995
+ function primaryLocale(fields, values, uiLang) {
996
+ const locales = itemLocales(fields);
997
+ if (!locales.length)
998
+ return uiLang;
999
+ const filled = (locale) => fields.filter(f => {
1000
+ const v = values[f.key];
1001
+ return f.locales?.includes(locale) && isPlainRecord(v) && !isEmptyFieldValue(v[locale]);
1002
+ }).length;
1003
+ const best = locales.reduce((a, b) => (filled(b) > filled(a) ? b : a));
1004
+ if (filled(best) > 0)
1005
+ return best;
1006
+ return locales.includes(uiLang) ? uiLang : locales[0];
1007
+ }
1008
+ /** The write locale of a content-item turn. */
1009
+ function turnLocale(sentence, fields, values, uiLang) {
1010
+ return namedLocale(sentence, itemLocales(fields)) ?? primaryLocale(fields, values, uiLang);
1011
+ }
1012
+ /** The language's own name in the admin's language (`en` → "English" / "אנגלית"). */
1013
+ const languageName = (locale, uiLang) => displayName(locale, uiLang) ?? locale;
1014
+
1015
+ /**
1016
+ * Surface S1 (the builder, this page), family `words` (ai-assist-plan §4, ai-session-panel-plan §3b–§3d): the page as
1017
+ * the model sees it — sections in order, each a handle (`s0`), the parts that carry words as handles (`s0.heading1`,
1018
+ * `s2.button1`) with their kind and words — never a node id, a style value or the tree. The SAME pure functions run on
1019
+ * the server (the brief it trusts, the check on a copy) and in the builder (the trial on the canvas):
1020
+ * - `summarizePage` — the brief + the handle map (handle → node id + prop), sized by distance from the selection;
1021
+ * - `wordsJsonSchema` — the strict format, one property per writable handle of the focus, ≤ 40 a request;
1022
+ * - `applyWordEdits` — all or none on a COPY: unknown or bound handles, markup, an empty text, a word to avoid or a fact
1023
+ * nobody gave are refused (re-asked once by the server, never repaired here).
1024
+ */
1025
+ /** What a part is, as the owner and the model call it. */
1026
+ var PagePartKind;
1027
+ (function (PagePartKind) {
1028
+ PagePartKind["Heading"] = "heading";
1029
+ PagePartKind["Text"] = "text";
1030
+ PagePartKind["Button"] = "button";
1031
+ PagePartKind["Link"] = "link";
1032
+ PagePartKind["Image"] = "image";
1033
+ PagePartKind["Field"] = "field";
1034
+ PagePartKind["Slide"] = "slide";
1035
+ PagePartKind["Video"] = "video";
1036
+ })(PagePartKind || (PagePartKind = {}));
1037
+ /** Which saved prop holds a type's words (node baselines). One table — ARIA labels are left to the author. */
1038
+ const PAGE_WORD_SLOTS = {
1039
+ Heading: [{ prop: 'content', kind: PagePartKind.Heading, says: 'a heading' }],
1040
+ Text: [{ prop: 'content', kind: PagePartKind.Text, says: 'text' }],
1041
+ Button: [{ prop: 'label', kind: PagePartKind.Button, says: 'a button\'s words' }],
1042
+ SubmitButton: [{ prop: 'label', kind: PagePartKind.Button, says: 'a form\'s send button' }],
1043
+ Link: [{ prop: 'label', kind: PagePartKind.Link, says: 'a link\'s words' }],
1044
+ Field: [
1045
+ { prop: 'label', kind: PagePartKind.Field, says: 'a form field\'s label' },
1046
+ { prop: 'placeholder', kind: PagePartKind.Field, suffix: 'placeholder', says: 'the hint inside an empty form field' },
1047
+ ],
1048
+ Image: [{ prop: 'alt', kind: PagePartKind.Image, says: 'a picture\'s description for people who cannot see it' }],
1049
+ SliderSlide: [{ prop: 'caption', kind: PagePartKind.Slide, says: 'a slide\'s caption' }],
1050
+ Video: [{ prop: 'title', kind: PagePartKind.Video, says: 'a video\'s title' }],
1051
+ };
1052
+ /** A Text wearing this element style is a ButtonBlock's words — a button to the owner. */
1053
+ const BUTTON_LABEL_STYLE = 'button-label';
1054
+ /** Focus words are sent whole up to this; Around words are summaries (`AROUND_TEXT_CHARS`). */
1055
+ const FOCUS_TEXT_CHARS = 1200;
1056
+ const BLOCK_MARKUP = /<(p|div|h[1-6]|li|blockquote|br)\b/i;
1057
+ /** A stored words value written as paragraphs (rich) or one plain line. */
1058
+ const isRich = (value) => typeof value === 'string' && BLOCK_MARKUP.test(value);
1059
+ /** A stored words value as the owner reads it. */
1060
+ function readableWords(value) {
1061
+ return richTextParagraphs(value).join('\n');
1062
+ }
1063
+ const sectionHandle = (index) => `s${index}`;
1064
+ const capitalise = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1065
+ /** "Hero · ground" → "Hero"; a composed section's id label ("hero-1") reads as words. */
1066
+ function sectionLabel(node, index) {
1067
+ const own = (node.label ?? '').split(' · ')[0].trim();
1068
+ return own ? capitalise(own.replace(/[-_]+/g, ' ')) : `Section ${index + 1}`;
1069
+ }
1070
+ function boundLabel(node, prop) {
1071
+ const b = (node.bindings ?? []).find(x => x.prop === prop);
1072
+ return b ? [b.source, b.path].filter(Boolean).join(' ▸ ') : undefined;
1073
+ }
1074
+ function slotsOf(node) {
1075
+ const slots = PAGE_WORD_SLOTS[node.type] ?? [];
1076
+ if (node.type === 'Text' && node.elementStyle === BUTTON_LABEL_STYLE)
1077
+ return slots.map(s => ({ ...s, kind: PagePartKind.Button, says: 'a button\'s words' }));
1078
+ return slots;
1079
+ }
1080
+ /** Every words part of the page, in reading order, with its handle. */
1081
+ function walkParts(layout) {
1082
+ const out = [];
1083
+ layout.forEach((root, index) => {
1084
+ const counts = new Map();
1085
+ const visit = (node, lineage) => {
1086
+ for (const slot of slotsOf(node)) {
1087
+ if (!slot.suffix)
1088
+ counts.set(slot.kind, (counts.get(slot.kind) ?? 0) + 1);
1089
+ const n = counts.get(slot.kind) ?? 1;
1090
+ const base = `${sectionHandle(index)}.${slot.kind}${n}`;
1091
+ const value = node.props?.[slot.prop];
1092
+ const bound = boundLabel(node, slot.prop);
1093
+ const part = {
1094
+ handle: slot.suffix ? `${base}.${slot.suffix}` : base,
1095
+ kind: slot.kind,
1096
+ label: `${capitalise(slot.kind)} ${n}${slot.suffix ? ` · ${slot.suffix}` : ''}`,
1097
+ words: readableWords(value),
1098
+ ...(isRich(value) ? { paragraphs: true } : {}),
1099
+ ...(bound ? { bound } : {}),
1100
+ ...(node.elementStyle ? { style: node.elementStyle } : {}),
1101
+ ...(node.role ? { role: node.role } : {}),
1102
+ };
1103
+ out.push({ part, section: index, nodeId: node.id, prop: slot.prop, lineage: [...lineage, node.id] });
1104
+ }
1105
+ for (const child of node.children ?? [])
1106
+ visit(child, [...lineage, node.id]);
1107
+ };
1108
+ visit(root, []);
1109
+ });
1110
+ return out;
1111
+ }
1112
+ const WIDENS = {
1113
+ [AssistScope.Node]: [AssistScope.Section, AssistScope.Page],
1114
+ [AssistScope.Section]: [AssistScope.Page],
1115
+ [AssistScope.Page]: [],
1116
+ };
1117
+ /** The section a node is in (its index), or -1. */
1118
+ function sectionOf(layout, id) {
1119
+ let found = -1;
1120
+ layout.forEach((root, index) => walkSerialized([root], n => { if (n.id === id)
1121
+ found = index; }));
1122
+ return found;
1123
+ }
1124
+ /**
1125
+ * The page as the model sees it. The selection decides the focus: a node → its section in full, its own parts as
1126
+ * "this"; a section → that section; nothing (or the page rung) → every section. The other sections are one line each.
1127
+ */
1128
+ function summarizePage(layout, ctx) {
1129
+ const walked = walkParts(layout);
1130
+ const selectedSection = ctx.selectedId ? sectionOf(layout, ctx.selectedId) : -1;
1131
+ const isSectionRoot = selectedSection >= 0 && layout[selectedSection].id === ctx.selectedId;
1132
+ const asked = ctx.scope ?? (selectedSection < 0 ? AssistScope.Page : isSectionRoot ? AssistScope.Section : AssistScope.Node);
1133
+ const scope = selectedSection < 0 ? AssistScope.Page : asked;
1134
+ const inFocus = (w) => scope === AssistScope.Page || w.section === selectedSection;
1135
+ const selectedParts = scope === AssistScope.Node ? walked.filter(w => w.lineage.includes(ctx.selectedId)) : [];
1136
+ const sections = layout
1137
+ .map((root, index) => ({ root, index }))
1138
+ .filter(({ index }) => scope === AssistScope.Page || index === selectedSection)
1139
+ .map(({ root, index }) => ({
1140
+ handle: sectionHandle(index),
1141
+ label: sectionLabel(root, index),
1142
+ parts: walked.filter(w => w.section === index).map(w => ({ ...w.part, words: clipText(w.part.words, FOCUS_TEXT_CHARS) })),
1143
+ }));
1144
+ const around = layout
1145
+ .map((root, index) => ({ root, index }))
1146
+ .filter(({ index }) => scope !== AssistScope.Page && index !== selectedSection)
1147
+ .map(({ root, index }) => {
1148
+ const first = walked.find(w => w.section === index && w.part.words && (w.part.kind === PagePartKind.Heading || w.part.kind === PagePartKind.Text));
1149
+ return { handle: sectionHandle(index), label: sectionLabel(root, index), headline: clipText(first?.part.words ?? '') };
1150
+ });
1151
+ const handles = {};
1152
+ const nodes = {};
1153
+ for (const w of walked) {
1154
+ nodes[w.part.handle] = w.nodeId;
1155
+ if (!w.part.bound)
1156
+ handles[w.part.handle] = { key: w.prop, path: [], id: w.nodeId };
1157
+ }
1158
+ layout.forEach((root, index) => { nodes[sectionHandle(index)] = root.id; });
1159
+ const focusWalked = scope === AssistScope.Node && selectedParts.length ? selectedParts : walked.filter(inFocus);
1160
+ const never = focusWalked.filter(w => w.part.bound)
1161
+ .map(w => ({ handle: w.part.handle, label: w.part.label, reason: `its words come from ${w.part.bound} — change them in that item` }));
1162
+ const rules = {
1163
+ families: SURFACES[AssistSurface.BuilderPage].families,
1164
+ locale: ctx.locale,
1165
+ never,
1166
+ scope,
1167
+ widensTo: WIDENS[scope] ?? [],
1168
+ };
1169
+ const selectedNode = selectedParts[0];
1170
+ const focus = {
1171
+ scope,
1172
+ page: ctx.page,
1173
+ sections,
1174
+ selected: selectedParts.map(w => w.part.handle),
1175
+ ...(selectedNode ? { selectedLabel: `${sections[0]?.label ?? ''} ▸ ${selectedNode.part.label}` } : {}),
1176
+ };
1177
+ return {
1178
+ brief: {
1179
+ surface: AssistSurface.BuilderPage,
1180
+ focus,
1181
+ around: { sections: around, pages: [...(ctx.pages ?? [])] },
1182
+ owner: ctx.owner ?? null,
1183
+ rules,
1184
+ memory: [...(ctx.memory ?? [])],
1185
+ },
1186
+ handles,
1187
+ focusHandles: focusWalked.filter(w => !w.part.bound).map(w => w.part.handle),
1188
+ nodes,
1189
+ };
1190
+ }
1191
+ var WordsAnswerKey;
1192
+ (function (WordsAnswerKey) {
1193
+ WordsAnswerKey["Words"] = "words";
1194
+ WordsAnswerKey["Note"] = "note";
1195
+ })(WordsAnswerKey || (WordsAnswerKey = {}));
1196
+ /** How many words handles one request carries. */
1197
+ const WORDS_PER_PART = MAX_ASSIST_PROPERTIES - Object.keys(WordsAnswerKey).length;
1198
+ function split(list, max) {
1199
+ if (!list.length)
1200
+ return [];
1201
+ const count = Math.ceil(list.length / max);
1202
+ const size = Math.ceil(list.length / count);
1203
+ return Array.from({ length: count }, (_, i) => list.slice(i * size, (i + 1) * size));
1204
+ }
1205
+ function partSlot(part, locale) {
1206
+ const where = `${part.label}${part.style ? ` (${part.style})` : ''}`;
1207
+ if (part.paragraphs) {
1208
+ return { ...jsonListOf(jsonText()), description: `${where} — paragraphs of plain text in ${locale}; [] leaves it as it is.` };
1209
+ }
1210
+ return { ...jsonText(), description: `${where} — one line of plain text in ${locale}; '' leaves it as it is.` };
1211
+ }
1212
+ /** The strict format of family `words` for the focus: every writable handle answered (new words, or its leave value). */
1213
+ function wordsJsonSchema(summary) {
1214
+ const byHandle = new Map(summary.brief.focus.sections.flatMap(s => s.parts).map(p => [p.handle, p]));
1215
+ const writable = summary.focusHandles.map(h => byHandle.get(h)).filter((p) => !!p);
1216
+ const groups = split(writable, WORDS_PER_PART);
1217
+ const parts = groups.map((g, i) => {
1218
+ const which = groups.length > 1 ? ` (part ${i + 1} of ${groups.length})` : '';
1219
+ return jsonClosedObject({
1220
+ [WordsAnswerKey.Words]: jsonClosedObject(Object.fromEntries(g.map(p => [p.handle, partSlot(p, summary.brief.rules.locale)])), g.map(p => p.handle), `Per part${which}: its new words, or its leave value.`),
1221
+ [WordsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner on what changed, or what needs them.' },
1222
+ }, Object.values(WordsAnswerKey));
1223
+ });
1224
+ parts.forEach((p, i) => assertAssistBudget(`words part ${i + 1}`, [p]));
1225
+ return { parts, handles: groups.map(g => g.map(p => p.handle)) };
1226
+ }
1227
+ const isLeave = (v) => v === null || v === undefined || v === '' || (Array.isArray(v) && v.length === 0);
1228
+ /** The parts' answers → the edits they make (every leave value dropped). */
1229
+ function decodeWordsAnswers(answers) {
1230
+ return answers.flatMap(answer => {
1231
+ const words = answer && typeof answer === 'object' ? answer[WordsAnswerKey.Words] : undefined;
1232
+ if (!words || typeof words !== 'object' || Array.isArray(words))
1233
+ return [];
1234
+ return Object.entries(words).filter(([, v]) => !isLeave(v))
1235
+ .map(([handle, value]) => ({ handle, value: value }));
1236
+ });
1237
+ }
1238
+ /** Every words value already on the page — its facts are the owner's (R-H2). */
1239
+ function pageTexts(layout) {
1240
+ const out = [];
1241
+ walkSerialized(layout, node => {
1242
+ for (const slot of slotsOf(node)) {
1243
+ const text = readableWords(node.props?.[slot.prop]);
1244
+ if (text)
1245
+ out.push(text);
1246
+ }
1247
+ });
1248
+ return out;
1249
+ }
1250
+ function partLabel(node, prop, handle) {
1251
+ const slot = slotsOf(node).find(s => s.prop === prop);
1252
+ const kind = slot?.kind ?? PagePartKind.Text;
1253
+ const tail = handle.split('.').slice(1).join(' ').replace(/^([a-z]+)(\d+)/, (_, k, n) => `${capitalise(k)} ${n}`);
1254
+ return { kind, label: tail || capitalise(kind) };
1255
+ }
1256
+ /**
1257
+ * Family `words`, applied — the SAME check on the server (before a turn is shown) and in the builder (the trial). All
1258
+ * or none; never mutates its input. A part written as paragraphs takes paragraphs (stored as escaped `<p>`), a line
1259
+ * takes one line (stored escaped). An edit that changes nothing is dropped.
1260
+ */
1261
+ function applyWordEdits(layout, edits, ctx) {
1262
+ const result = JSON.parse(JSON.stringify(layout));
1263
+ const byId = new Map();
1264
+ walkSerialized(result, n => byId.set(n.id, n));
1265
+ const never = new Map((ctx.never ?? []).map(n => [n.handle, n]));
1266
+ const issues = [];
1267
+ const changes = [];
1268
+ const seen = new Set();
1269
+ const written = [];
1270
+ for (const edit of edits) {
1271
+ const refuse = (code, message) => issues.push({ code, handle: edit.handle, message });
1272
+ if (seen.has(edit.handle)) {
1273
+ refuse(AssistIssueCode.Duplicate, `"${edit.handle}" is answered twice`);
1274
+ continue;
1275
+ }
1276
+ seen.add(edit.handle);
1277
+ const kept = never.get(edit.handle);
1278
+ if (kept) {
1279
+ refuse(AssistIssueCode.NeverWrite, `${kept.label}: ${kept.reason}`);
1280
+ continue;
1281
+ }
1282
+ const resolved = resolveHandle(ctx.handles, edit.handle);
1283
+ if ('issue' in resolved) {
1284
+ issues.push(resolved.issue);
1285
+ continue;
1286
+ }
1287
+ const node = resolved.target.id ? byId.get(resolved.target.id) : undefined;
1288
+ if (!node) {
1289
+ refuse(AssistIssueCode.UnknownHandle, `"${edit.handle}" is no longer on the page`);
1290
+ continue;
1291
+ }
1292
+ const prop = resolved.target.key;
1293
+ const before = node.props?.[prop];
1294
+ const rich = isRich(before);
1295
+ const lines = typeof edit.value === 'string' ? [edit.value] : Array.isArray(edit.value) ? [...edit.value] : null;
1296
+ if (!lines || lines.some(l => typeof l !== 'string')) {
1297
+ refuse(AssistIssueCode.WrongType, rich ? 'expected paragraphs of text' : 'expected one line of text');
1298
+ continue;
1299
+ }
1300
+ const clean = lines.map(l => l.replace(/\s+/g, ' ').trim()).filter(Boolean);
1301
+ if (!clean.length) {
1302
+ refuse(AssistIssueCode.WrongType, 'expected words — leave a part as it is with its leave value');
1303
+ continue;
1304
+ }
1305
+ if (clean.some(containsHtml)) {
1306
+ refuse(AssistIssueCode.HtmlNotAllowed, 'markup is not written by Assist');
1307
+ continue;
1308
+ }
1309
+ if (!rich && clean.length > 1) {
1310
+ refuse(AssistIssueCode.WrongType, 'this part is one line');
1311
+ continue;
1312
+ }
1313
+ const stored = rich ? paragraphsToRichText(clean) : escapeText(clean[0]);
1314
+ const readable = clean.join('\n');
1315
+ if (readable === readableWords(before))
1316
+ continue;
1317
+ written.push({ handle: edit.handle, text: readable });
1318
+ node.props = { ...(node.props ?? {}), [prop]: stored };
1319
+ changes.push({ handle: edit.handle, nodeId: node.id, ...partLabel(node, prop, edit.handle), before: readableWords(before), after: readable });
1320
+ }
1321
+ issues.push(...assistFactIssues(written, { words: ctx.words, sentence: ctx.sentence, existing: pageTexts(layout) }));
1322
+ if (issues.length)
1323
+ return { ok: false, result: JSON.parse(JSON.stringify(layout)), changes: [], issues };
1324
+ return { ok: true, result, changes, issues: [] };
1325
+ }
1326
+ var PageSuggestionKind;
1327
+ (function (PageSuggestionKind) {
1328
+ /** The selection's words, rewritten as the owner asks. */
1329
+ PageSuggestionKind["Rewrite"] = "rewrite";
1330
+ PageSuggestionKind["Shorten"] = "shorten";
1331
+ PageSuggestionKind["FillEmpty"] = "fillEmpty";
1332
+ /** Pictures with no description for people who cannot see them. */
1333
+ PageSuggestionKind["DescribePictures"] = "describePictures";
1334
+ })(PageSuggestionKind || (PageSuggestionKind = {}));
1335
+ /** A heading this long, or a text this long, is worth a "Shorten". */
1336
+ const SHORTEN_HEADING_FROM_CHARS = 60;
1337
+ const SHORTEN_TEXT_FROM_CHARS = 280;
1338
+ const tooLong = (p) => p.words.length >= (p.kind === PagePartKind.Heading ? SHORTEN_HEADING_FROM_CHARS : SHORTEN_TEXT_FROM_CHARS);
1339
+ /** S1's quick actions — each only when it applies to the focus. */
1340
+ function pageSuggestions(summary) {
1341
+ const writable = new Set(summary.focusHandles);
1342
+ const parts = summary.brief.focus.sections.flatMap(s => s.parts).filter(p => writable.has(p.handle));
1343
+ const pick = (test) => parts.filter(test).map(p => p.handle);
1344
+ const selected = summary.brief.focus.selected.filter(h => writable.has(h));
1345
+ const long = pick(p => p.kind !== PagePartKind.Image && tooLong(p));
1346
+ const empty = pick(p => p.kind !== PagePartKind.Image && !p.words);
1347
+ const pictures = pick(p => p.kind === PagePartKind.Image && !p.words);
1348
+ return [
1349
+ ...(selected.length ? [{ kind: PageSuggestionKind.Rewrite, handles: selected }] : []),
1350
+ ...(long.length ? [{ kind: PageSuggestionKind.Shorten, handles: long }] : []),
1351
+ ...(empty.length ? [{ kind: PageSuggestionKind.FillEmpty, handles: empty }] : []),
1352
+ ...(pictures.length ? [{ kind: PageSuggestionKind.DescribePictures, handles: pictures }] : []),
1353
+ ];
1354
+ }
1355
+ const HEBREW_LETTER = /[֐-׿]/g;
1356
+ const LATIN_LETTER = /[A-Za-zÀ-ɏ]/g;
1357
+ const LOCALE_SHAPE = /^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$/;
1358
+ const HEBREW = 'he';
1359
+ const ENGLISH = 'en';
1360
+ /**
1361
+ * The ONE locale a page turn writes in (ai-session-panel-plan §3h) — the server's and the builder's: a language the
1362
+ * sentence names ("translate this to English") → the page's own locale → the script its words are written in (a Hebrew
1363
+ * page edited in English still gets Hebrew words) → the admin's language.
1364
+ */
1365
+ function pageWriteLocale(layout, ctx) {
1366
+ const stored = ctx.stored && LOCALE_SHAPE.test(ctx.stored) ? ctx.stored : null;
1367
+ const named = namedLocale(ctx.sentence, [...new Set([...(stored ? [stored] : []), ENGLISH, HEBREW])]);
1368
+ if (named)
1369
+ return named;
1370
+ if (stored)
1371
+ return stored;
1372
+ const words = pageTexts(layout).join(' ');
1373
+ const hebrew = (words.match(HEBREW_LETTER) ?? []).length;
1374
+ const latin = (words.match(LATIN_LETTER) ?? []).length;
1375
+ if (hebrew > latin)
1376
+ return HEBREW;
1377
+ if (latin > hebrew)
1378
+ return ctx.uiLang === HEBREW ? ENGLISH : ctx.uiLang;
1379
+ return ctx.uiLang;
1380
+ }
1381
+
917
1382
  /**
918
1383
  * The turn wire (plan §3d) — what cms-client posts and polls and iox-cms stores and answers, ONE definition both sides
919
1384
  * import (generation-core `ai-run.ts` is the precedent for generations). A turn is a document on the jobs runner:
@@ -998,7 +1463,7 @@ function assistSessionKey(surface, target = {}) {
998
1463
  }
999
1464
  const SENTENCE_IN_MEMORY_CHARS = 80;
1000
1465
  function outcome(turn) {
1001
- const named = (list) => (list ?? []).map(c => (c.locale ? `${c.label} (${c.locale})` : c.label)).join(', ');
1466
+ const named = (list) => (list ?? []).map(c => ('locale' in c && c.locale ? `${c.label} (${c.locale})` : c.label)).join(', ');
1002
1467
  switch (turn.status) {
1003
1468
  case AssistTurnStatus.Refused: return `refused: ${turn.refusal?.message ?? ''}`.trim();
1004
1469
  case AssistTurnStatus.Failed: return 'failed';
@@ -1055,90 +1520,30 @@ function validateTurnRequest(req) {
1055
1520
  ...(!isObject(brief) || brief['surface'] !== surface ? [issue(AssistIssueCode.BadRequest, `the brief is not a ${surface} brief`)] : []),
1056
1521
  ...(!isObject(req['handles']) || !Object.keys(req['handles']).length ? [issue(AssistIssueCode.MissingHandles, 'the brief\'s handles are missing')] : []),
1057
1522
  ...(spec.commit === CommitKind.FormFill && !isObject(req['values']) ? [issue(AssistIssueCode.MissingValues, 'a form-fill turn carries the form\'s values')] : []),
1523
+ ...(spec.commit === CommitKind.BuilderStep && (!Array.isArray(req['layout']) || !req['layout'].length || !req['layout'].every(isObject))
1524
+ ? [issue(AssistIssueCode.MissingValues, 'a builder turn carries the page\'s layout')] : []),
1525
+ ...(spec.commit === CommitKind.BuilderStep && !nonEmpty(req['pageId']) ? [issue(AssistIssueCode.BadRequest, `${surface} names its page`)] : []),
1058
1526
  ...(!isOwnerEdited(req['ownerEdited']) ? [issue(AssistIssueCode.BadRequest, 'ownerEdited is a list of field keys')] : []),
1059
1527
  ...(spec.perContentType && !nonEmpty(req['contentType']) ? [issue(AssistIssueCode.BadRequest, `${surface} names its content type`)] : []),
1060
1528
  ];
1061
1529
  }
1062
1530
 
1063
- /**
1064
- * The ONE locale a content-item turn writes in (plan §3c rule 8, trap T5) — decided the same way by the server and the
1065
- * client: a multiLang field gets this key and no other. The sentence decides when it names a language ("translate the
1066
- * summary to English", "תרגם לאנגלית") — matched against the runtime's own language names (`Intl.DisplayNames`) in the
1067
- * languages the admin speaks, never a hand-kept list; the last one named wins. Otherwise the item's own language: the
1068
- * locale most of its multiLang fields are filled in (schema order breaks a tie); else the admin's; else the first.
1069
- */
1070
- /** The languages whose names a sentence may use — the admin's two UI languages. */
1071
- const LOCALE_NAME_LANGUAGES = ['en', 'he'];
1072
- const DISPLAY_TYPE_LANGUAGE = 'language';
1073
- /** Every locale the type's multiLang fields hold, in schema order. */
1074
- function itemLocales(fields) {
1075
- return [...new Set(fields.flatMap(f => f.locales ?? []))];
1076
- }
1077
- function displayName(locale, inLanguage) {
1078
- try {
1079
- const name = new Intl.DisplayNames([inLanguage], { type: DISPLAY_TYPE_LANGUAGE }).of(locale);
1080
- return name && name !== locale ? name : null;
1081
- }
1082
- catch {
1083
- return null;
1084
- }
1085
- }
1086
- function languageNames(locale, languages) {
1087
- return languages.flatMap(lang => {
1088
- const name = displayName(locale, lang);
1089
- return name ? [name.toLowerCase()] : [];
1090
- });
1091
- }
1092
- /** The last position a locale's name appears at in the sentence, or -1. */
1093
- function lastMention(sentence, locale, languages) {
1094
- const s = sentence.toLowerCase();
1095
- return Math.max(-1, ...languageNames(locale, languages).map(n => s.lastIndexOf(n)));
1096
- }
1097
- /** The locale the sentence names; the last one named wins ("the Hebrew summary to English" → en). */
1098
- function namedLocale(sentence, locales, languages = LOCALE_NAME_LANGUAGES) {
1099
- const named = locales
1100
- .map(locale => ({ locale, at: lastMention(sentence, locale, languages) }))
1101
- .filter(m => m.at >= 0)
1102
- .sort((a, b) => b.at - a.at);
1103
- return named[0]?.locale ?? null;
1104
- }
1105
- /** The locale most of the item's multiLang fields are filled in (schema order breaks a tie); else the UI's; else the first. */
1106
- function primaryLocale(fields, values, uiLang) {
1107
- const locales = itemLocales(fields);
1108
- if (!locales.length)
1109
- return uiLang;
1110
- const filled = (locale) => fields.filter(f => {
1111
- const v = values[f.key];
1112
- return f.locales?.includes(locale) && isPlainRecord(v) && !isEmptyFieldValue(v[locale]);
1113
- }).length;
1114
- const best = locales.reduce((a, b) => (filled(b) > filled(a) ? b : a));
1115
- if (filled(best) > 0)
1116
- return best;
1117
- return locales.includes(uiLang) ? uiLang : locales[0];
1118
- }
1119
- /** The write locale of a content-item turn. */
1120
- function turnLocale(sentence, fields, values, uiLang) {
1121
- return namedLocale(sentence, itemLocales(fields)) ?? primaryLocale(fields, values, uiLang);
1122
- }
1123
- /** The language's own name in the admin's language (`en` → "English" / "אנגלית"). */
1124
- const languageName = (locale, uiLang) => displayName(locale, uiLang) ?? locale;
1125
-
1126
1531
  /**
1127
1532
  * @vectoriox/iox-ui/assist-core — the shared, FRAMEWORK-FREE vocabulary of AI Assist (iox-ai-guidance
1128
1533
  * `architecture/ai/ai-assist-plan.md` §3b): the surfaces and their specs, the brief and its handle map, the route
1129
1534
  * request, and family `fields` for surface S2 (one content item) — its brief (`summarizeItem`), its strict output format
1130
1535
  * (`fieldsJsonSchema`) and the ONE check that applies an answer (`applyFieldEdits`), run by iox-cms on a copy and by
1131
- * cms-client as the trial. Pure: no transport, no clock, no randomness.
1536
+ * cms-client as the trial — and family `words` for surface S1 (the builder, this page): `summarizePage`, `wordsJsonSchema`,
1537
+ * `applyWordEdits`, `pageSuggestions`. Every family's words pass ONE fact gate (`assistFactIssues` over generation-core's
1538
+ * `factIssues`, R-H2). Pure: no transport, no clock, no randomness.
1132
1539
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets, jest
1133
1540
  * moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM. It imports generation-core (the strict
1134
1541
  * schema builders and budget), so a consumer maps both.
1135
- * TODO(after the 2026-11-19 demo): extract the fact gate `factIssues` out of generation-core's `planWordIssues` into
1136
- * this entry (plan §3b, R-H2) — `planWordIssues` becomes its caller; deferred because it edits generation-core.
1137
1542
  */
1138
1543
 
1139
1544
  /**
1140
1545
  * Generated bundle index. Do not edit.
1141
1546
  */
1142
1547
 
1143
- export { AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, ASSIST_MODEL_AUTO, ASSIST_POLL_MS, ASSIST_ROUTES, AssistBriefError, AssistBudgetError, AssistFieldKind, AssistIssueCode, AssistPathError, AssistPermission, AssistRefusalCode, AssistRouteKey, AssistScope, AssistStep, AssistSurface, AssistTurnStatus, BOOLEAN_FALSE, BOOLEAN_TRUE, CommitKind, EditFamily, FIELDS_PER_PART, FIELD_HANDLE_PREFIX, FieldsAnswerKey, ItemSuggestionKind, LOCALE_NAME_LANGUAGES, MAX_ASSIST_PROPERTIES, MAX_ROUTE_PROPERTIES, MAX_SENTENCE_CHARS, MEMORY_TURNS, NEW_TARGET, NONE_TEXT, NeverWriteReason, RouteAnswerKey, SHORTEN_FROM_CHARS, SIBLING_HANDLE_PREFIX, SURFACES, SurfaceStatus, applyFieldEdits, assertAssistBudget, assistBudgetIssues, assistFields, assistPath, assistSession, assistSessionKey, builtSurfaces, clipText, commitOf, containsHtml, decodeFieldsAnswers, fieldHandle, fieldsJsonSchema, fieldsNamedIn, isEmptyFieldValue, isPlainRecord, isSessionOf, isTerminalTurn, isWritable, itemLocales, itemSuggestions, languageName, memoryLine, namedLocale, paragraphsToRichText, primaryLocale, readFieldValue, readLocaleValues, readRoute, resolveHandle, richTextParagraphs, routeJsonSchema, sessionMemory, summarizeItem, surfacePermissions, surfaceSpec, titleField, turnLocale, unknownHandles, validateTurnRequest };
1548
+ export { AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, ASSIST_MODEL_AUTO, ASSIST_POLL_MS, ASSIST_ROUTES, AssistBriefError, AssistBudgetError, AssistFieldKind, AssistIssueCode, AssistPathError, AssistPermission, AssistRefusalCode, AssistRouteKey, AssistScope, AssistStep, AssistSurface, AssistTurnStatus, BOOLEAN_FALSE, BOOLEAN_TRUE, CommitKind, EditFamily, FIELDS_PER_PART, FIELD_HANDLE_PREFIX, FOCUS_TEXT_CHARS, FieldsAnswerKey, ItemSuggestionKind, LOCALE_NAME_LANGUAGES, MAX_ASSIST_PROPERTIES, MAX_ROUTE_PROPERTIES, MAX_SENTENCE_CHARS, MEMORY_TURNS, NEW_TARGET, NONE_TEXT, NeverWriteReason, PAGE_WORD_SLOTS, PagePartKind, PageSuggestionKind, RouteAnswerKey, SHORTEN_FROM_CHARS, SHORTEN_HEADING_FROM_CHARS, SHORTEN_TEXT_FROM_CHARS, SIBLING_HANDLE_PREFIX, SURFACES, SurfaceStatus, WORDS_PER_PART, WordsAnswerKey, applyFieldEdits, applyWordEdits, assertAssistBudget, assistBudgetIssues, assistFactIssues, assistFields, assistPath, assistSession, assistSessionKey, builtSurfaces, clipText, commitOf, containsHtml, decodeFieldsAnswers, decodeWordsAnswers, escapeText, fieldHandle, fieldsJsonSchema, fieldsNamedIn, isEmptyFieldValue, isPlainRecord, isSessionOf, isTerminalTurn, isWritable, itemLocales, itemSuggestions, languageName, memoryLine, namedLocale, pageSuggestions, pageWriteLocale, paragraphsToRichText, primaryLocale, readFieldValue, readLocaleValues, readRoute, readableWords, resolveHandle, richTextParagraphs, routeJsonSchema, sessionMemory, summarizeItem, summarizePage, surfacePermissions, surfaceSpec, titleField, turnLocale, unknownHandles, validateTurnRequest, wordsJsonSchema };
1144
1549
  //# sourceMappingURL=vectoriox-iox-ui-assist-core.mjs.map