@vectoriox/iox-ui 5.123.0 → 5.125.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.
@@ -75,6 +75,7 @@ var AssistPermission;
75
75
  AssistPermission["ContentRead"] = "content_read";
76
76
  AssistPermission["ContentCreate"] = "content_create";
77
77
  AssistPermission["ContentUpdate"] = "content_update";
78
+ AssistPermission["ContentDelete"] = "content_delete";
78
79
  AssistPermission["PageRead"] = "page_read";
79
80
  AssistPermission["PageCreate"] = "page_create";
80
81
  AssistPermission["PageUpdate"] = "page_update";
@@ -91,6 +92,7 @@ var SurfaceStatus;
91
92
  const spec = (s) => ({
92
93
  perContentType: false,
93
94
  readsPhotos: false,
95
+ routed: true,
94
96
  ...s,
95
97
  });
96
98
  const SURFACES = {
@@ -117,16 +119,20 @@ const SURFACES = {
117
119
  scopes: [AssistScope.Field, AssistScope.Item, AssistScope.Type],
118
120
  status: SurfaceStatus.Built,
119
121
  }),
122
+ // S3 (AI4): one vision read per photo group writes a draft's fields (the photos go into its picture fields by code);
123
+ // the owner's "Create N drafts" is a Run, and its Undo removes what it wrote and the photos this flow uploaded.
120
124
  [AssistSurface.ContentFromPhotos]: spec({
121
125
  surface: AssistSurface.ContentFromPhotos,
122
126
  families: [EditFamily.Fields, EditFamily.Media],
123
127
  commit: CommitKind.Run,
124
- steps: [AssistStep.AssistRoute, AssistStep.AssistRead, AssistStep.AssistEdit],
128
+ steps: [AssistStep.AssistRead],
125
129
  permissions: [AssistPermission.ContentCreate, AssistPermission.StorageAll],
130
+ undoPermissions: [AssistPermission.ContentDelete],
126
131
  perContentType: true,
127
132
  readsPhotos: true,
133
+ routed: false,
128
134
  scopes: [AssistScope.Photo, AssistScope.Photos, AssistScope.Type],
129
- status: SurfaceStatus.Planned,
135
+ status: SurfaceStatus.Built,
130
136
  }),
131
137
  [AssistSurface.ContentList]: spec({
132
138
  surface: AssistSurface.ContentList,
@@ -201,7 +207,15 @@ const ALL_SUFFIX = '_all';
201
207
  */
202
208
  function surfacePermissions(surface, contentType, families = []) {
203
209
  const s = SURFACES[surface];
204
- const all = [...s.permissions, ...families.flatMap(f => s.familyPermissions?.[f] ?? [])];
210
+ return specialised(surface, contentType, [...s.permissions, ...families.flatMap(f => s.familyPermissions?.[f] ?? [])]);
211
+ }
212
+ /** What a Run surface's Undo needs: the surface's own permissions and its `undoPermissions`, specialised the same way. */
213
+ function surfaceUndoPermissions(surface, contentType) {
214
+ const s = SURFACES[surface];
215
+ return specialised(surface, contentType, [...s.permissions, ...(s.undoPermissions ?? [])]);
216
+ }
217
+ function specialised(surface, contentType, all) {
218
+ const s = SURFACES[surface];
205
219
  const named = all.map(p => {
206
220
  if (!s.perContentType || !contentType || !p.startsWith(CONTENT_PERMISSION_PREFIX) || p.endsWith(ALL_SUFFIX))
207
221
  return p;
@@ -261,6 +275,10 @@ var AssistIssueCode;
261
275
  AssistIssueCode["AvoidWord"] = "avoidWord";
262
276
  /** A look whose colours fail the contrast audit in a mode the site is worn in (family `look`, R4). */
263
277
  AssistIssueCode["Contrast"] = "contrast";
278
+ /** S3: a value said to come from the owner's notes when the owner gave none. */
279
+ AssistIssueCode["NotFromOwner"] = "notFromOwner";
280
+ /** S3: the photos a turn names are not this flow's uploads, or too many / none. */
281
+ AssistIssueCode["BadPhotos"] = "badPhotos";
264
282
  })(AssistIssueCode || (AssistIssueCode = {}));
265
283
  /** A caller's mistake building a brief (a focus that is not on the screen) — never a model answer. */
266
284
  class AssistBriefError extends Error {
@@ -734,17 +752,21 @@ function split$1(list, max) {
734
752
  const size = Math.ceil(list.length / count);
735
753
  return Array.from({ length: count }, (_, i) => list.slice(i * size, (i + 1) * size));
736
754
  }
737
- function partSchema(fields, locale, part, of) {
755
+ function partSchema(fields, locale, part, of, extra) {
738
756
  const properties = Object.fromEntries(fields.map(f => [f.handle, fieldSchema(f, locale)]));
739
757
  const which = of > 1 ? ` (part ${part + 1} of ${of})` : '';
740
- return jsonClosedObject({
758
+ const own = extra?.build(fields.map(f => f.handle), part) ?? {};
759
+ const answer = {
741
760
  [FieldsAnswerKey.Fields]: jsonClosedObject(properties, fields.map(f => f.handle), `Per field${which}: its new value, or its leave value.`),
761
+ ...own,
742
762
  [FieldsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner on what changed, or what needs them.' },
743
- }, Object.values(FieldsAnswerKey));
763
+ };
764
+ return jsonClosedObject(answer, Object.keys(answer));
744
765
  }
745
766
  function fieldsJsonSchema(schema, options) {
746
- const groups = split$1(chosen(assistFields(schema), options.fields), FIELDS_PER_PART);
747
- const parts = groups.map((g, i) => partSchema(g, options.locale, i, groups.length));
767
+ const perPart = FIELDS_PER_PART - (options.extra?.keys.length ?? 0);
768
+ const groups = split$1(chosen(assistFields(schema), options.fields), perPart);
769
+ const parts = groups.map((g, i) => partSchema(g, options.locale, i, groups.length, options.extra));
748
770
  parts.forEach((p, i) => assertAssistBudget(`fields ${schema.name} part ${i + 1}`, [p]));
749
771
  return { parts, handles: groups.map(g => g.map(f => f.handle)) };
750
772
  }
@@ -955,6 +977,324 @@ function applyFieldEdits(values, edits, ctx) {
955
977
  return { ok: true, result, changes: applied.map(p => p.change), kept: planned.filter(isKept).map(p => p.change), issues: [] };
956
978
  }
957
979
 
980
+ /**
981
+ * Surface S3 — photos → content (ai-assist-plan §4 S3, A-D11, R-H7): the owner's photos, uploaded FIRST, become DRAFT
982
+ * items of one content type. One photo = one item unless the owner says they are one item (the first photo is then the
983
+ * main image, the rest the gallery). Each group is read by ONE vision request (`assistRead`, ≤ 6 photos — F8) whose
984
+ * strict format is the type's writable fields (`fieldsJsonSchema`) plus which values came from the owner's notes and an
985
+ * alt text per photo. Every value is then tagged by where it came from: SEEN in the photo, FROM YOU (the owner's notes),
986
+ * or NEEDS YOU (left empty: a fact the owner gives — a price, a place, a date, a phone — or a required field nothing
987
+ * showed). The photos go into the type's picture fields by code, never by the model. Nothing is written by a read: the
988
+ * owner reviews the drafts and creates them (a Run, with Undo).
989
+ */
990
+ var PhotoGrouping;
991
+ (function (PhotoGrouping) {
992
+ /** One item per photo. */
993
+ PhotoGrouping["Each"] = "each";
994
+ /** Every photo is ONE item: the first the main image, the rest its gallery. */
995
+ PhotoGrouping["One"] = "one";
996
+ })(PhotoGrouping || (PhotoGrouping = {}));
997
+ /** The most photos one S3 turn takes (the board: "Up to 20 at a time"). */
998
+ const MAX_ASSIST_PHOTOS = 20;
999
+ /** The most photos one vision request reads (F8 — the reading's own limit); a larger group's others go to its gallery unread. */
1000
+ const PHOTOS_PER_READ = 6;
1001
+ const PHOTO_GROUP_HANDLE_PREFIX = 'p';
1002
+ const photoGroupHandle = (index) => `${PHOTO_GROUP_HANDLE_PREFIX}${index + 1}`;
1003
+ /** The groups the photos make — one per photo, or one for all. */
1004
+ function groupPhotos(photos, grouping) {
1005
+ if (!photos.length)
1006
+ return [];
1007
+ const group = (list, i) => ({
1008
+ handle: photoGroupHandle(i), photos: [...list], read: Math.min(list.length, PHOTOS_PER_READ),
1009
+ });
1010
+ return grouping === PhotoGrouping.One ? [group(photos, 0)] : photos.map((p, i) => group([p], i));
1011
+ }
1012
+ /** How many vision requests a turn makes — what its estimate multiplies. */
1013
+ const photoReadCount = (photos, grouping) => photos <= 0 ? 0 : grouping === PhotoGrouping.One ? 1 : photos;
1014
+ // ── the type's picture fields ────────────────────────────────────────────────────────────────
1015
+ var PictureControl;
1016
+ (function (PictureControl) {
1017
+ PictureControl["Image"] = "image";
1018
+ PictureControl["Media"] = "media";
1019
+ PictureControl["Gallery"] = "gallery";
1020
+ })(PictureControl || (PictureControl = {}));
1021
+ const STRING = 'string';
1022
+ const ARRAY = 'array';
1023
+ const isPictureLeaf = (def) => !!def && def.type === STRING
1024
+ && (def.controller?.type === PictureControl.Media || def.controller?.type === PictureControl.Image);
1025
+ const isPictureList = (def) => !!def && def.type === ARRAY
1026
+ && (def.controller?.type === PictureControl.Gallery || isPictureLeaf(def.items) || def.items?.controller?.type === PictureControl.Media);
1027
+ function photoSlots(schema) {
1028
+ const props = schema.schemaObject?.properties ?? {};
1029
+ const role = schema.metaData?.previewImageField;
1030
+ const keys = Object.keys(props);
1031
+ const main = role && isPictureLeaf(props[role]) ? role : keys.find(k => isPictureLeaf(props[k])) ?? null;
1032
+ const gallery = keys.find(k => isPictureList(props[k])) ?? null;
1033
+ return { main, gallery };
1034
+ }
1035
+ /** A type the photos can become: it has a picture field to put them in. */
1036
+ const takesPhotos = (schema) => {
1037
+ const slots = photoSlots(schema);
1038
+ return !!(slots.main || slots.gallery);
1039
+ };
1040
+ const nameWords = (text) => text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w.length >= 3);
1041
+ const singular = (w) => (w.endsWith('ies') ? `${w.slice(0, -3)}y` : w.endsWith('s') ? w.slice(0, -1) : w);
1042
+ /**
1043
+ * "Make them into" — the type suggested for the photos: one the sentence names (its name or label, either number), else
1044
+ * the first type that takes photos. Null when none does (the owner adds a picture field first).
1045
+ */
1046
+ function suggestPhotoType(schemas, sentence = '') {
1047
+ const candidates = schemas.filter(takesPhotos);
1048
+ const said = new Set(nameWords(sentence).map(singular));
1049
+ const named = candidates.find(s => [s.name, s.metaData?.label ?? ''].some(n => nameWords(n).some(w => said.has(singular(w)))));
1050
+ return (named ?? candidates[0])?.name ?? null;
1051
+ }
1052
+ const labelOf$2 = (schema, key) => key ? (schema.schemaObject.properties[key]?.label || key) : null;
1053
+ /** S3's brief: the type's writable fields (`f.<key>`), the groups (`p<n>`), the picture fields, siblings as voice. */
1054
+ function summarizePhotos(schema, ctx) {
1055
+ const fields = assistFields(schema);
1056
+ const slots = photoSlots(schema);
1057
+ const groups = groupPhotos(ctx.photos, ctx.grouping);
1058
+ const item = summarizeItem(schema, {}, { locale: ctx.locale, siblings: ctx.siblings ?? [] });
1059
+ const picture = new Set([slots.main, slots.gallery].filter(Boolean));
1060
+ const title = titleField(schema, fields);
1061
+ const surface = SURFACES[AssistSurface.ContentFromPhotos];
1062
+ const handles = {
1063
+ ...item.handles,
1064
+ ...Object.fromEntries(groups.map(g => [g.handle, { key: g.handle, path: [] }])),
1065
+ };
1066
+ const never = fields.filter(f => f.never && !picture.has(f.key)).map(f => ({ handle: f.handle, label: f.label, reason: f.never }));
1067
+ const brief = {
1068
+ surface: AssistSurface.ContentFromPhotos,
1069
+ focus: {
1070
+ scope: AssistScope.Photos,
1071
+ type: { name: schema.name, label: schema.metaData?.label || schema.name },
1072
+ grouping: ctx.grouping,
1073
+ groups: groups.map(g => ({ handle: g.handle, photos: g.photos.length, read: g.read })),
1074
+ fields: fields.filter(isWritable).map(f => ({
1075
+ handle: f.handle, label: f.label, kind: f.kind, required: f.required,
1076
+ ...(f.options ? { options: f.options } : {}), ...(f.locales ? { multiLang: true } : {}),
1077
+ })),
1078
+ titleHandle: title && isWritable(title) ? title.handle : null,
1079
+ pictures: { main: labelOf$2(schema, slots.main), gallery: labelOf$2(schema, slots.gallery) },
1080
+ },
1081
+ around: { siblings: item.brief.around.siblings },
1082
+ owner: ctx.owner ?? null,
1083
+ rules: {
1084
+ families: surface.families,
1085
+ locale: ctx.locale,
1086
+ never,
1087
+ scope: AssistScope.Photos,
1088
+ widensTo: surface.scopes.slice(surface.scopes.indexOf(AssistScope.Photos) + 1),
1089
+ },
1090
+ memory: (ctx.memory ?? []).slice(-MEMORY_TURNS),
1091
+ };
1092
+ return { brief, handles, groups, slots };
1093
+ }
1094
+ /** The brief ONE read is sent: the same brief, its focus narrowed to the group being read (`p<n>`). */
1095
+ function photoGroupBrief(brief, handle) {
1096
+ const groups = brief.focus.groups.filter(g => g.handle === handle);
1097
+ return { ...brief, focus: { ...brief.focus, scope: AssistScope.Photo, groups } };
1098
+ }
1099
+ // ── the strict format of one read ────────────────────────────────────────────────────────────
1100
+ var PhotoAnswerKey;
1101
+ (function (PhotoAnswerKey) {
1102
+ PhotoAnswerKey["FromYou"] = "fromYou";
1103
+ PhotoAnswerKey["Alt"] = "alt";
1104
+ })(PhotoAnswerKey || (PhotoAnswerKey = {}));
1105
+ /** One read's format: the type's writable fields (split as any fields request) + which came from the notes + the alt texts. */
1106
+ function photoDraftJsonSchema(schema, options) {
1107
+ const altSchema = {
1108
+ ...jsonListOf(jsonText()),
1109
+ description: `Exactly ${options.read} alt text(s), one per photo in the order shown: what it shows for a person who cannot see it, in ${options.locale}. Never a claim about the business.`,
1110
+ };
1111
+ const fromYou = (handles) => ({
1112
+ ...jsonListOf(jsonOneOf(handles)),
1113
+ description: 'The fields whose value came from the owner\'s notes, not from the photos. [] when none did.',
1114
+ });
1115
+ const writable = assistFields(schema).filter(isWritable);
1116
+ if (!writable.length) {
1117
+ // Nothing to write but the alt texts: one part with no fields at all.
1118
+ const answer = { [PhotoAnswerKey.Alt]: altSchema, [FieldsAnswerKey.Note]: { ...jsonText(), description: 'One short line for the owner.' } };
1119
+ return {
1120
+ parts: [{ type: 'object', properties: answer, required: Object.keys(answer), additionalProperties: false }],
1121
+ handles: [[]],
1122
+ };
1123
+ }
1124
+ return fieldsJsonSchema(schema, {
1125
+ locale: options.locale,
1126
+ extra: {
1127
+ keys: [PhotoAnswerKey.FromYou, PhotoAnswerKey.Alt],
1128
+ build: (handles, part) => ({
1129
+ [PhotoAnswerKey.FromYou]: fromYou(handles),
1130
+ ...(part === 0 ? { [PhotoAnswerKey.Alt]: altSchema } : {}),
1131
+ }),
1132
+ },
1133
+ });
1134
+ }
1135
+ const listOf$2 = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
1136
+ function decodePhotoDraftAnswers(answers) {
1137
+ const objects = answers.filter(isPlainRecord);
1138
+ const notes = objects.map(a => a[FieldsAnswerKey.Note]).filter((n) => typeof n === 'string' && n.trim() !== '').map(n => n.trim());
1139
+ return {
1140
+ edits: decodeFieldsAnswers(answers),
1141
+ fromYou: [...new Set(objects.flatMap(a => listOf$2(a[PhotoAnswerKey.FromYou])))],
1142
+ alt: objects.flatMap(a => listOf$2(a[PhotoAnswerKey.Alt])).map(t => t.trim()),
1143
+ note: notes.join(' '),
1144
+ };
1145
+ }
1146
+ // ── the draft ────────────────────────────────────────────────────────────────────────────────
1147
+ /** Where a draft's value came from — what the review card says beside it. */
1148
+ var ValueSource;
1149
+ (function (ValueSource) {
1150
+ /** Visible in the photo. */
1151
+ ValueSource["Seen"] = "seen";
1152
+ /** The owner's own words — the notes, or a value typed at review. */
1153
+ ValueSource["FromYou"] = "fromYou";
1154
+ /** Left empty: a fact the owner gives, or a required field nothing showed. */
1155
+ ValueSource["NeedsYou"] = "needsYou";
1156
+ /** Left empty, and nothing asks for it (an optional field the photos did not answer). */
1157
+ ValueSource["Empty"] = "empty";
1158
+ })(ValueSource || (ValueSource = {}));
1159
+ /** The facts an owner gives — a field of one of these is NEEDS YOU when empty (R-H7: never filled by the AI). */
1160
+ const OWNER_FACTS = new Set([
1161
+ NeverWriteReason.Money, NeverWriteReason.Stock, NeverWriteReason.ProductCode, NeverWriteReason.Contact,
1162
+ NeverWriteReason.Date, NeverWriteReason.WebAddress,
1163
+ ]);
1164
+ const ALT_HANDLE = 'alt';
1165
+ function altIssues(alt, read) {
1166
+ const issue = (message) => ({ code: AssistIssueCode.WrongType, handle: ALT_HANDLE, message });
1167
+ if (alt.length !== read)
1168
+ return [issue(`expected ${read} alt text(s), one per photo — got ${alt.length}`)];
1169
+ return alt.flatMap((t, i) => (!t ? [issue(`photo ${i + 1} has no alt text`)]
1170
+ : containsHtml(t) ? [{ code: AssistIssueCode.HtmlNotAllowed, handle: ALT_HANDLE, message: `photo ${i + 1}: markup is not written by Assist` }]
1171
+ : t.length > AROUND_TEXT_CHARS ? [issue(`photo ${i + 1}: an alt text is at most ${AROUND_TEXT_CHARS} characters`)] : []));
1172
+ }
1173
+ const sourceOfEmpty = (field) => (field.never && OWNER_FACTS.has(field.never)) || (!field.never && field.required) ? ValueSource.NeedsYou : ValueSource.Empty;
1174
+ /**
1175
+ * One read's answer → its draft, by the SAME check every fields turn runs (`applyFieldEdits` on an empty item, the fact
1176
+ * gate included) plus the alt texts and the owner's-notes claim. All or none: an issue refuses the draft (the read is
1177
+ * re-asked once with the issues). The photos are placed by code: main = the first, gallery = the rest.
1178
+ */
1179
+ function draftFromPhotos(answer, ctx) {
1180
+ const applied = applyFieldEdits({}, answer.edits, {
1181
+ schema: ctx.schema, handles: ctx.handles, locale: ctx.locale, sentence: ctx.sentence ?? '', words: ctx.words, named: [],
1182
+ });
1183
+ const notes = (ctx.sentence ?? '').trim();
1184
+ const fromYou = answer.fromYou.filter(h => applied.changes.some(c => c.handle === h));
1185
+ const issues = [
1186
+ ...applied.issues,
1187
+ ...altIssues(answer.alt, ctx.group.read),
1188
+ ...assistFactIssues(answer.alt.map(text => ({ handle: ALT_HANDLE, text })), { words: ctx.words, sentence: notes, existing: [] }),
1189
+ ...answer.fromYou.filter(h => !Object.prototype.hasOwnProperty.call(ctx.handles, h))
1190
+ .map(h => ({ code: AssistIssueCode.UnknownHandle, handle: h, message: `"${h}" is not a field of this type` })),
1191
+ ...(!notes && fromYou.length ? [{ code: AssistIssueCode.NotFromOwner, message: 'the owner gave no notes, so no value came from them' }] : []),
1192
+ ];
1193
+ if (issues.length)
1194
+ return { ok: false, draft: null, issues };
1195
+ const slots = photoSlots(ctx.schema);
1196
+ const urls = ctx.group.photos.map(p => p.url);
1197
+ const values = { ...applied.result };
1198
+ if (slots.main)
1199
+ values[slots.main] = urls[0];
1200
+ const galleryUrls = slots.main ? urls.slice(1) : urls;
1201
+ if (slots.gallery && galleryUrls.length)
1202
+ values[slots.gallery] = galleryUrls;
1203
+ const picture = new Set([slots.main, slots.gallery]);
1204
+ const changed = new Map(applied.changes.map(c => [c.key, c]));
1205
+ const fields = assistFields(ctx.schema).filter(f => !picture.has(f.key)).map(f => {
1206
+ const c = changed.get(f.key);
1207
+ const base = { handle: f.handle, key: f.key, label: f.label, kind: f.kind, ...(f.never ? { never: f.never } : {}) };
1208
+ if (!c)
1209
+ return { ...base, value: null, source: sourceOfEmpty(f) };
1210
+ return { ...base, value: c.after, source: fromYou.includes(f.handle) ? ValueSource.FromYou : ValueSource.Seen, ...(c.locale ? { locale: c.locale } : {}) };
1211
+ });
1212
+ const title = titleField(ctx.schema);
1213
+ const titleValue = title ? fields.find(f => f.key === title.key)?.value : null;
1214
+ return {
1215
+ ok: true,
1216
+ issues: [],
1217
+ draft: {
1218
+ group: ctx.group.handle, photos: ctx.group.photos, alt: answer.alt, title: typeof titleValue === 'string' ? titleValue : '',
1219
+ values, fields, note: answer.note,
1220
+ },
1221
+ };
1222
+ }
1223
+ // ── the owner's own values at review ("City for all") ────────────────────────────────────────
1224
+ const TEXT_CONTROLS = new Set(['text', 'textarea', 'tag', 'email']);
1225
+ const MULTI_LANG = 'multiLang';
1226
+ /** The longest value an owner types for every draft at once. */
1227
+ const OWNER_FILL_MAX_CHARS = 500;
1228
+ const isTextLeaf = (def) => !!def && def.type === STRING && TEXT_CONTROLS.has(def.controller?.type ?? '');
1229
+ function isTextField(schema, key) {
1230
+ const def = schema.schemaObject.properties[key];
1231
+ if (def?.controller?.type === MULTI_LANG)
1232
+ return Object.values(def.properties ?? {}).every(isTextLeaf) && !!Object.keys(def.properties ?? {}).length;
1233
+ return isTextLeaf(def);
1234
+ }
1235
+ /** The fields the owner may type ONE value into for every draft at review: plain text, never a secret, relation or picture. */
1236
+ function ownerFillFields(schema) {
1237
+ const refused = new Set([NeverWriteReason.Secret, NeverWriteReason.Relation, NeverWriteReason.Media, NeverWriteReason.Structure]);
1238
+ return assistFields(schema).filter(f => !(f.never && refused.has(f.never)) && isTextField(schema, f.key));
1239
+ }
1240
+ /** What the server refuses in a review's fill: a field the owner may not fill so, a value that is not one short text. */
1241
+ function ownerFillIssues(schema, fill) {
1242
+ if (fill === undefined)
1243
+ return [];
1244
+ if (!isPlainRecord(fill))
1245
+ return [{ code: AssistIssueCode.BadRequest, message: 'the fill is an object of field → text' }];
1246
+ const allowed = new Set(ownerFillFields(schema).map(f => f.key));
1247
+ return Object.entries(fill).flatMap(([key, value]) => {
1248
+ if (!allowed.has(key))
1249
+ return [{ code: AssistIssueCode.UnknownHandle, handle: key, message: `"${key}" cannot be filled for every draft` }];
1250
+ if (typeof value !== 'string' || !value.trim())
1251
+ return [{ code: AssistIssueCode.WrongType, handle: key, message: `${key}: a text` }];
1252
+ if (value.length > OWNER_FILL_MAX_CHARS)
1253
+ return [{ code: AssistIssueCode.WrongType, handle: key, message: `${key}: at most ${OWNER_FILL_MAX_CHARS} characters` }];
1254
+ if (containsHtml(value))
1255
+ return [{ code: AssistIssueCode.HtmlNotAllowed, handle: key, message: `${key}: no markup` }];
1256
+ return [];
1257
+ });
1258
+ }
1259
+ /**
1260
+ * The owner's "for all" values put into a draft — only where the draft holds nothing (a value the photos gave is never
1261
+ * overwritten); a multiLang field gets the locale's key. The value is the owner's: FROM YOU. Unknown keys are ignored
1262
+ * (the server refuses them first, `ownerFillIssues`).
1263
+ */
1264
+ function withOwnerFill(draft, fill, ctx) {
1265
+ const allowed = new Set(ownerFillFields(ctx.schema).map(f => f.key));
1266
+ const values = { ...draft.values };
1267
+ const filled = new Map();
1268
+ for (const [key, raw] of Object.entries(fill)) {
1269
+ const value = typeof raw === 'string' ? raw.trim() : '';
1270
+ if (!allowed.has(key) || !value)
1271
+ continue;
1272
+ const multi = ctx.schema.schemaObject.properties[key]?.controller?.type === MULTI_LANG;
1273
+ const current = multi ? (isPlainRecord(values[key]) ? values[key][ctx.locale] : undefined) : values[key];
1274
+ if (!isEmptyFieldValue(current))
1275
+ continue;
1276
+ values[key] = multi ? { ...(isPlainRecord(values[key]) ? values[key] : {}), [ctx.locale]: value } : value;
1277
+ filled.set(key, value);
1278
+ }
1279
+ if (!filled.size)
1280
+ return draft;
1281
+ const fields = draft.fields.map(f => (filled.has(f.key)
1282
+ ? { ...f, value: filled.get(f.key), source: ValueSource.FromYou, ...(ctx.schema.schemaObject.properties[f.key]?.controller?.type === MULTI_LANG ? { locale: ctx.locale } : {}) }
1283
+ : f));
1284
+ return { ...draft, values, fields };
1285
+ }
1286
+ // ── a draft once written ─────────────────────────────────────────────────────────────────────
1287
+ /** `info.source` of an item a Run wrote (plan §3e) — what the list's "AI draft" pill and the Run's Undo read. */
1288
+ const AI_DRAFT_SOURCE = 'ai';
1289
+ const aiDraftStamp = (turnId, group) => ({ source: AI_DRAFT_SOURCE, assistTurn: turnId, draftKey: `${turnId}:${group}` });
1290
+ /** An item a Run wrote that is still unpublished — the list shows it as an "AI draft". */
1291
+ function isAiDraft(item) {
1292
+ if (!isPlainRecord(item))
1293
+ return false;
1294
+ const info = item['info'];
1295
+ return isPlainRecord(info) && info['source'] === AI_DRAFT_SOURCE && item['isPublished'] !== true;
1296
+ }
1297
+
958
1298
  /**
959
1299
  * The ONE locale a content-item turn writes in (plan §3c rule 8, trap T5) — decided the same way by the server and the
960
1300
  * client: a multiLang field gets this key and no other. The sentence decides when it names a language ("translate the
@@ -2468,17 +2808,50 @@ var AssistRefusalCode;
2468
2808
  /** The chosen model cannot do the step (on the studio's own key any model may be typed; this one lacks a need). */
2469
2809
  AssistRefusalCode["ModelDeclined"] = "ai.assistModelDeclined";
2470
2810
  })(AssistRefusalCode || (AssistRefusalCode = {}));
2811
+ /** A Run's life (plan §3e `Run`): written by the runner (resumable), undone by it. */
2812
+ var AssistRunStatus;
2813
+ (function (AssistRunStatus) {
2814
+ AssistRunStatus["Writing"] = "writing";
2815
+ AssistRunStatus["Written"] = "written";
2816
+ AssistRunStatus["Undoing"] = "undoing";
2817
+ AssistRunStatus["Undone"] = "undone";
2818
+ AssistRunStatus["Failed"] = "failed";
2819
+ })(AssistRunStatus || (AssistRunStatus = {}));
2820
+ const RUN_BUSY = new Set([AssistRunStatus.Writing, AssistRunStatus.Undoing]);
2821
+ const isRunBusy = (status) => !!status && RUN_BUSY.has(status);
2822
+ /** What the server refuses in a run request against the turn's drafts: none, unknown or repeated picks. */
2823
+ function validateRunRequest(req, drafts) {
2824
+ const issue = (code, message, handle) => ({ code, message, ...(handle ? { handle } : {}) });
2825
+ if (!isObject(req))
2826
+ return [issue(AssistIssueCode.BadRequest, 'a run is an object')];
2827
+ const picks = req['picks'];
2828
+ if (!Array.isArray(picks) || !picks.length || !picks.every(nonEmpty))
2829
+ return [issue(AssistIssueCode.BadRequest, 'picks name at least one draft')];
2830
+ const known = new Set(drafts.map(d => d.group));
2831
+ return [
2832
+ ...picks.filter(p => !known.has(p)).map(p => issue(AssistIssueCode.UnknownHandle, `"${p}" is not a draft of this turn`, p)),
2833
+ ...(new Set(picks).size !== picks.length ? [issue(AssistIssueCode.Duplicate, 'a draft is picked twice')] : []),
2834
+ ...(req['fill'] !== undefined && !isObject(req['fill']) ? [issue(AssistIssueCode.BadRequest, 'fill is an object of field → text')] : []),
2835
+ ];
2836
+ }
2471
2837
  var AssistRouteKey;
2472
2838
  (function (AssistRouteKey) {
2473
2839
  AssistRouteKey["Turns"] = "turns";
2474
2840
  AssistRouteKey["Turn"] = "turn";
2475
2841
  AssistRouteKey["Session"] = "session";
2842
+ /** S3: one photo up, through the normal upload path, marked as this flow's (Undo may remove it). */
2843
+ AssistRouteKey["Photos"] = "photos";
2844
+ AssistRouteKey["Run"] = "run";
2845
+ AssistRouteKey["Undo"] = "undo";
2476
2846
  })(AssistRouteKey || (AssistRouteKey = {}));
2477
2847
  /** The path templates, `:param` filled by `assistPath` — neither side hand-types a URL. */
2478
2848
  const ASSIST_ROUTES = {
2479
2849
  [AssistRouteKey.Turns]: 'admin/api/org/:orgId/ai/assist/turns',
2480
2850
  [AssistRouteKey.Turn]: 'admin/api/org/:orgId/ai/assist/turns/:turnId',
2481
2851
  [AssistRouteKey.Session]: 'admin/api/org/:orgId/ai/assist/sessions/:sessionKey',
2852
+ [AssistRouteKey.Photos]: 'admin/api/org/:orgId/ai/assist/photos',
2853
+ [AssistRouteKey.Run]: 'admin/api/org/:orgId/ai/assist/turns/:turnId/run',
2854
+ [AssistRouteKey.Undo]: 'admin/api/org/:orgId/ai/assist/turns/:turnId/undo',
2482
2855
  };
2483
2856
  class AssistPathError extends Error {
2484
2857
  }
@@ -2517,6 +2890,8 @@ function outcome(turn) {
2517
2890
  case AssistTurnStatus.Refused: return `refused: ${turn.refusal?.message ?? ''}`.trim();
2518
2891
  case AssistTurnStatus.Failed: return 'failed';
2519
2892
  case AssistTurnStatus.Done: {
2893
+ if (turn.drafts?.length)
2894
+ return `drafted ${turn.drafts.length} item(s)${turn.contentType ? ` of ${turn.contentType}` : ''} from photos`;
2520
2895
  const changed = named(turn.changes);
2521
2896
  const kept = named(turn.kept);
2522
2897
  const head = changed ? `changed ${changed}` : `no change${turn.reply ? `: ${turn.reply}` : ''}`;
@@ -2549,6 +2924,23 @@ const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
2549
2924
  const isOwnerEdited = (v) => v === undefined || (Array.isArray(v) && v.every(nonEmpty));
2550
2925
  /** A key `assistSessionKey` made for this surface. */
2551
2926
  const isSessionOf = (key, surface) => nonEmpty(key) && (key === surface || key.startsWith(`${surface}${SESSION_SEPARATOR}`));
2927
+ const GROUPINGS = new Set(Object.values(PhotoGrouping));
2928
+ /** S3's photos: 1–20, each a storage key, none twice; a grouping. */
2929
+ function photoIssues(photos, grouping) {
2930
+ const issue = (message) => ({ code: AssistIssueCode.BadPhotos, message });
2931
+ const out = [];
2932
+ if (!Array.isArray(photos) || !photos.length)
2933
+ out.push(issue('a photos turn names its photos'));
2934
+ else if (photos.length > MAX_ASSIST_PHOTOS)
2935
+ out.push(issue(`at most ${MAX_ASSIST_PHOTOS} photos a turn`));
2936
+ else if (!photos.every(p => isObject(p) && nonEmpty(p['key'])))
2937
+ out.push(issue('each photo is its storage key'));
2938
+ else if (new Set(photos.map(p => p['key'])).size !== photos.length)
2939
+ out.push(issue('a photo is named twice'));
2940
+ if (!GROUPINGS.has(String(grouping)))
2941
+ out.push({ code: AssistIssueCode.BadRequest, message: `the grouping is one of ${[...GROUPINGS].join(', ')}` });
2942
+ return out;
2943
+ }
2552
2944
  /** What the server refuses in a posted turn before anything runs. Empty = accepted. */
2553
2945
  function validateTurnRequest(req) {
2554
2946
  const issue = (code, message) => ({ code, message });
@@ -2560,10 +2952,13 @@ function validateTurnRequest(req) {
2560
2952
  return [issue(AssistIssueCode.UnknownSurface, `"${String(surface)}" is not a surface`)];
2561
2953
  const sentence = req['sentence'];
2562
2954
  const brief = req['brief'];
2955
+ // A surface its screen routes takes the owner's notes, which may be empty — but are still a text.
2956
+ const sentenceMissing = spec.routed ? !nonEmpty(sentence) : typeof sentence !== 'string';
2563
2957
  return [
2564
2958
  ...(spec.status !== SurfaceStatus.Built ? [issue(AssistIssueCode.SurfaceNotBuilt, `${surface} is not built yet`)] : []),
2565
2959
  ...(!isSessionOf(req['sessionKey'], surface) ? [issue(AssistIssueCode.BadRequest, `the session key is not a ${surface} session`)] : []),
2566
- ...(!nonEmpty(sentence) ? [issue(AssistIssueCode.EmptySentence, 'the sentence is empty')] : []),
2960
+ ...(sentenceMissing ? [issue(AssistIssueCode.EmptySentence, 'the sentence is empty')] : []),
2961
+ ...(spec.readsPhotos && spec.commit === CommitKind.Run ? photoIssues(req['photos'], req['grouping']) : []),
2567
2962
  ...(nonEmpty(sentence) && sentence.length > MAX_SENTENCE_CHARS ? [issue(AssistIssueCode.SentenceTooLong, `the sentence is over ${MAX_SENTENCE_CHARS} characters`)] : []),
2568
2963
  ...(!nonEmpty(req['model']) ? [issue(AssistIssueCode.BadRequest, 'no model choice (auto or a model id)')] : []),
2569
2964
  ...(!isObject(brief) || brief['surface'] !== surface ? [issue(AssistIssueCode.BadRequest, `the brief is not a ${surface} brief`)] : []),
@@ -2584,7 +2979,9 @@ function validateTurnRequest(req) {
2584
2979
  * (`fieldsJsonSchema`) and the ONE check that applies an answer (`applyFieldEdits`), run by iox-cms on a copy and by
2585
2980
  * cms-client as the trial — and family `words` for surface S1 (the builder, this page): `summarizePage`, `wordsJsonSchema`,
2586
2981
  * `applyWordEdits`, `pageSuggestions` — and family `style` (`pageLooks`, `styleJsonSchema`, `applyStyleEdits`; both applied as
2587
- * one turn by `applyPageEdits`). Every family's words pass ONE fact gate (`assistFactIssues` over generation-core's
2982
+ * one turn by `applyPageEdits`) — and surface S3, photos → content (`summarizePhotos`, `photoDraftJsonSchema`, `draftFromPhotos`:
2983
+ * one vision read per photo group becomes a draft whose every value says where it came from; `withOwnerFill` for the
2984
+ * review's "for all" values; the Run's wire in `assist-turn.ts`). Every family's words pass ONE fact gate (`assistFactIssues` over generation-core's
2588
2985
  * `factIssues`, R-H2). Pure: no transport, no clock, no randomness.
2589
2986
  * ⚠️ Not re-exported from the main entry. Consumers wire the usual trio — ng-package raw-ts assets, jest
2590
2987
  * moduleNameMapper, tsconfig paths — or `nest start` dies with ERR_REQUIRE_ESM. It imports generation-core (the strict
@@ -2595,5 +2992,5 @@ function validateTurnRequest(req) {
2595
2992
  * Generated bundle index. Do not edit.
2596
2993
  */
2597
2994
 
2598
- export { AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, ASK_SECTION_PATTERNS, ASK_STYLE_SETS, 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, LOOK_AXES, LOOK_AXIS_LABELS, LOOK_KEEP, LookAnswerKey, LookAxis, LookButtons, MAX_ASSIST_PROPERTIES, MAX_ROUTE_PROPERTIES, MAX_SENTENCE_CHARS, MEMORY_TURNS, MODE_LABELS, NEW_TARGET, NONE_TEXT, NeverWriteReason, PAGE_WORD_SLOTS, PageChangeOp, PagePartKind, PageSuggestionKind, RouteAnswerKey, SECTION_START, SHORTEN_FROM_CHARS, SHORTEN_HEADING_FROM_CHARS, SHORTEN_TEXT_FROM_CHARS, SIBLING_HANDLE_PREFIX, SURFACES, SectionChangeKind, SectionsAnswerKey, StyleAnswerKey, SurfaceStatus, WORDS_PER_PART, WordsAnswerKey, adjustAxesOf, applyFieldEdits, applyLookEdits, applyPageEdits, applySectionEdits, applyStyleEdits, applyWordEdits, askSectionPatternNames, askableStyles, assertAssistBudget, assistBudgetIssues, assistFactIssues, assistFields, assistPath, assistSession, assistSessionKey, builtSurfaces, clipText, commitOf, containsHtml, decodeFieldsAnswers, decodeLookAnswers, decodeSectionsAnswers, decodeStyleAnswers, decodeWordsAnswers, escapeText, fieldHandle, fieldsJsonSchema, fieldsNamedIn, isEmptyFieldValue, isPlainRecord, isSchemeEdit, isSectionEdit, isSessionOf, isSiteLookEdit, isSizeEdit, isStyleEdit, isTerminalTurn, isWritable, itemLocales, itemSuggestions, languageName, lookAxisValue, lookHex, lookJsonSchema, lookNames, memoryLine, namedLocale, pageLooks, pageSuggestions, pageWriteLocale, paragraphsToRichText, primaryLocale, readFieldValue, readLocaleValues, readRoute, readableWords, resolveHandle, richTextParagraphs, routeJsonSchema, sectionLabel, sectionPatternOf, sectionsJsonSchema, serializedBaselineStyles, sessionMemory, styleJsonSchema, summarizeItem, summarizeLook, summarizePage, surfacePermissions, surfaceSpec, titleField, turnLocale, unknownHandles, validateTurnRequest, wordsJsonSchema };
2995
+ export { AI_DRAFT_SOURCE, AROUND_ITEMS_MAX, AROUND_TEXT_CHARS, ASK_SECTION_PATTERNS, ASK_STYLE_SETS, ASSIST_MODEL_AUTO, ASSIST_POLL_MS, ASSIST_ROUTES, AssistBriefError, AssistBudgetError, AssistFieldKind, AssistIssueCode, AssistPathError, AssistPermission, AssistRefusalCode, AssistRouteKey, AssistRunStatus, AssistScope, AssistStep, AssistSurface, AssistTurnStatus, BOOLEAN_FALSE, BOOLEAN_TRUE, CommitKind, EditFamily, FIELDS_PER_PART, FIELD_HANDLE_PREFIX, FOCUS_TEXT_CHARS, FieldsAnswerKey, ItemSuggestionKind, LOCALE_NAME_LANGUAGES, LOOK_AXES, LOOK_AXIS_LABELS, LOOK_KEEP, LookAnswerKey, LookAxis, LookButtons, MAX_ASSIST_PHOTOS, MAX_ASSIST_PROPERTIES, MAX_ROUTE_PROPERTIES, MAX_SENTENCE_CHARS, MEMORY_TURNS, MODE_LABELS, NEW_TARGET, NONE_TEXT, NeverWriteReason, OWNER_FILL_MAX_CHARS, PAGE_WORD_SLOTS, PHOTOS_PER_READ, PHOTO_GROUP_HANDLE_PREFIX, PageChangeOp, PagePartKind, PageSuggestionKind, PhotoAnswerKey, PhotoGrouping, RouteAnswerKey, SECTION_START, SHORTEN_FROM_CHARS, SHORTEN_HEADING_FROM_CHARS, SHORTEN_TEXT_FROM_CHARS, SIBLING_HANDLE_PREFIX, SURFACES, SectionChangeKind, SectionsAnswerKey, StyleAnswerKey, SurfaceStatus, ValueSource, WORDS_PER_PART, WordsAnswerKey, adjustAxesOf, aiDraftStamp, applyFieldEdits, applyLookEdits, applyPageEdits, applySectionEdits, applyStyleEdits, applyWordEdits, askSectionPatternNames, askableStyles, assertAssistBudget, assistBudgetIssues, assistFactIssues, assistFields, assistPath, assistSession, assistSessionKey, builtSurfaces, clipText, commitOf, containsHtml, decodeFieldsAnswers, decodeLookAnswers, decodePhotoDraftAnswers, decodeSectionsAnswers, decodeStyleAnswers, decodeWordsAnswers, draftFromPhotos, escapeText, fieldHandle, fieldsJsonSchema, fieldsNamedIn, groupPhotos, isAiDraft, isEmptyFieldValue, isPlainRecord, isRunBusy, isSchemeEdit, isSectionEdit, isSessionOf, isSiteLookEdit, isSizeEdit, isStyleEdit, isTerminalTurn, isWritable, itemLocales, itemSuggestions, languageName, lookAxisValue, lookHex, lookJsonSchema, lookNames, memoryLine, namedLocale, ownerFillFields, ownerFillIssues, pageLooks, pageSuggestions, pageWriteLocale, paragraphsToRichText, photoDraftJsonSchema, photoGroupBrief, photoGroupHandle, photoReadCount, photoSlots, primaryLocale, readFieldValue, readLocaleValues, readRoute, readableWords, resolveHandle, richTextParagraphs, routeJsonSchema, sectionLabel, sectionPatternOf, sectionsJsonSchema, serializedBaselineStyles, sessionMemory, styleJsonSchema, suggestPhotoType, summarizeItem, summarizeLook, summarizePage, summarizePhotos, surfacePermissions, surfaceSpec, surfaceUndoPermissions, takesPhotos, titleField, turnLocale, unknownHandles, validateRunRequest, validateTurnRequest, withOwnerFill, wordsJsonSchema };
2599
2996
  //# sourceMappingURL=vectoriox-iox-ui-assist-core.mjs.map