@burdenoff/microfe-healthybowl 2026.812.21 → 2026.813.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,11 @@
1
1
  import { MAX_REQUEST_BODY_BYTES as e } from "./gatewayLimits.js";
2
- var t = 10 * 1024 * 1024, n = 8e3, r = 2e4, i = class extends Error {
2
+ import { formatPageRanges as t, isMostlyImagePages as n, truncatePagesForInline as r } from "./documentText.js";
3
+ var i = 10 * 1024 * 1024, a = 8e3, o = 2e4, s = class extends Error {
3
4
  constructor(e) {
4
5
  super(e), this.reason = e, this.name = "AttachmentRejectedError";
5
6
  }
6
7
  };
7
- function a(e) {
8
+ function c(e) {
8
9
  return {
9
10
  id: e.id,
10
11
  filename: e.filename,
@@ -14,7 +15,7 @@ function a(e) {
14
15
  fileId: e.fileId
15
16
  };
16
17
  }
17
- var o = new Set([
18
+ var l = new Set([
18
19
  "txt",
19
20
  "md",
20
21
  "markdown",
@@ -38,23 +39,42 @@ var o = new Set([
38
39
  "toml",
39
40
  "conf"
40
41
  ]);
41
- function s(e) {
42
+ function u(e) {
42
43
  let t = e.lastIndexOf(".");
43
44
  return t >= 0 ? e.slice(t + 1).toLowerCase() : "";
44
45
  }
45
- function c(e, t) {
46
- return e.startsWith("image/") ? "image" : e.startsWith("text/") || e === "application/json" || e === "application/xml" || e === "application/x-yaml" || o.has(s(t)) ? "text" : "document";
46
+ function d(e, t) {
47
+ return e.startsWith("image/") ? "image" : e.startsWith("text/") || e === "application/json" || e === "application/xml" || e === "application/x-yaml" || l.has(u(t)) ? "text" : "document";
48
+ }
49
+ var f = {
50
+ "application/pdf": "pdf",
51
+ "application/x-pdf": "pdf",
52
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
53
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx"
54
+ }, p = {
55
+ pdf: "pdf",
56
+ docx: "docx",
57
+ xlsx: "xlsx"
58
+ };
59
+ function m(e, t) {
60
+ return f[e.toLowerCase()] ?? p[u(t)] ?? null;
47
61
  }
48
- function l(e) {
62
+ var h = [
63
+ "image/*",
64
+ "text/*",
65
+ ...[...l].map((e) => `.${e}`),
66
+ ...Object.keys(p).map((e) => `.${e}`)
67
+ ].join(",");
68
+ function g(e) {
49
69
  return e < 1024 ? `${e} B` : e < 1024 * 1024 ? `${(e / 1024).toFixed(1)} KB` : `${(e / (1024 * 1024)).toFixed(1)} MB`;
50
70
  }
51
- function u(e, t) {
71
+ function _(e, t) {
52
72
  return e > 0 || t.some((e) => e.status === "pending" || e.status === "uploading");
53
73
  }
54
- function d(e, t) {
74
+ function v(e, t) {
55
75
  return t >= 5 ? "too-many" : e.size === 0 ? "empty" : e.size > 10485760 && !e.type.startsWith("image/") ? "too-large" : null;
56
76
  }
57
- function f(e, t) {
77
+ function y(e, t) {
58
78
  if (e.length <= t) return {
59
79
  text: e,
60
80
  truncated: !1
@@ -65,99 +85,261 @@ function f(e, t) {
65
85
  truncated: !0
66
86
  };
67
87
  }
68
- function p(e, t) {
69
- let n = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${l(e.size)}`];
70
- return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${l(e.size)}; truncated):` : " Contents:", " ```", ...e.textContent.split("\n").map((e) => ` ${e}`), " ```") : e.kind === "image" ? n.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : e.kind === "text" ? n.push(" Text file — contents omitted because this turn ran out of inline budget, not because they are", " unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they", " can re-send just that section.") : n.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), n.join("\n");
88
+ function b(e) {
89
+ return [
90
+ " ```",
91
+ ...e.split("\n").map((e) => ` ${e}`),
92
+ " ```"
93
+ ];
94
+ }
95
+ function x(e) {
96
+ return e?.pageNumbers?.length ? e.pageNumbers : e?.pagesIncluded ? Array.from({ length: e.pagesIncluded }, (e, t) => t + 1) : [];
97
+ }
98
+ function S(e) {
99
+ let n = e.extraction, r = [];
100
+ if (n?.pageCount) {
101
+ let e = x(n);
102
+ e.length >= n.pageCount ? r.push(`${n.pageCount} page${n.pageCount === 1 ? "" : "s"}`) : e.length === 1 ? r.push(`page ${e[0]} of ${n.pageCount}`) : r.push(`pages ${t(e)} of ${n.pageCount}`);
103
+ }
104
+ if (n?.sheetNames?.length && r.push(`sheets: ${n.sheetNames.join(", ")}`), e.textTruncated && e.textContent) {
105
+ let t = n?.sourceChars;
106
+ r.push(t && t > e.textContent.length ? `first ${e.textContent.length} characters of ${t}; truncated` : `first ${e.textContent.length} characters; truncated`);
107
+ }
108
+ return r.length > 0 ? ` (${r.join("; ")})` : "";
109
+ }
110
+ var C = " Do NOT guess at, summarise or characterise its contents — you have not seen them.", w = [" Fetch the URL above if you can; otherwise ask the user to paste the relevant section as text.", C];
111
+ function T(e) {
112
+ let n = e.extraction;
113
+ if (!n?.pageCount) return [];
114
+ let r = new Set(x(n)), i = new Set(n.imagePages ?? []), a = [...i].filter((e) => !r.has(e)).sort((e, t) => e - t), o = [];
115
+ if (a.length > 0) {
116
+ let e = a.length === 1 ? `Page ${a[0]}` : `Pages ${t(a)}`;
117
+ o.push(` ${e} of this document contain no extractable text — they are images.`, " Nothing about those pages is available to you.");
118
+ }
119
+ let s = [];
120
+ for (let e = 1; e <= n.pageCount; e += 1) !r.has(e) && !i.has(e) && s.push(e);
121
+ if (s.length > 0) {
122
+ let e = s.length === 1 ? `Page ${s[0]}` : `Pages ${t(s)}`;
123
+ o.push(` ${e} of this document ${s.length === 1 ? "was" : "were"} not read at all.`);
124
+ }
125
+ return o.length > 0 && o.push(C), o;
126
+ }
127
+ function E(e) {
128
+ let t = e.extraction;
129
+ if (!t || t.status === "unsupported") return [" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."];
130
+ if (t.status === "no-text") return t.format === "docx" || t.format === "xlsx" ? [
131
+ " NO TEXT AVAILABLE — this document holds no readable text; it is either empty or contains only",
132
+ " images, charts or drawings, none of which carry text. No text could be extracted.",
133
+ ...w
134
+ ] : [
135
+ ` NO TEXT AVAILABLE — this document appears to be scanned images; no text could be extracted${t.pagesScanned && t.pageCount && t.pagesScanned < t.pageCount ? ` (the first ${t.pagesScanned} of ${t.pageCount} pages were checked)` : ""}.`,
136
+ " There is no text layer to read, so nothing about its contents is available to you.",
137
+ ...w
138
+ ];
139
+ if (t.status === "encrypted") return [
140
+ " NO TEXT AVAILABLE — this document is encrypted or password-protected; it could not be opened",
141
+ " and no text could be extracted.",
142
+ ...w
143
+ ];
144
+ if (t.status === "corrupt") return [` NO TEXT AVAILABLE — this file could not be read${t.detail ? ` (${t.detail})` : ""}; no text could be extracted.`, ...w];
145
+ if (!e.textContent) return [
146
+ " Text WAS extracted from this document but is omitted because this turn ran out of inline budget,",
147
+ " not because it is unavailable. Ask the user which part matters so they can re-send just that",
148
+ " section, or fetch the URL above if you can.",
149
+ C
150
+ ];
151
+ let r = t.pagesScanned ?? t.pageCount ?? 0, i = t.textPageCount;
152
+ if (t.pageCount && i !== void 0 && n(i, r)) {
153
+ let n = r - i;
154
+ return [
155
+ ` NOT READ — this document is mostly images. Only ${i} of its ${t.pageCount} page${t.pageCount === 1 ? "" : "s"} carr${i === 1 ? "ies" : "y"} a text layer;`,
156
+ ` the other ${n} contain no extractable text at all. Treat this as a document you have NOT`,
157
+ " read: the fragment below is the whole of what was available, not a summary of the document.",
158
+ ...T(e),
159
+ ` The only extractable text${S(e)}:`,
160
+ ...b(e.textContent)
161
+ ];
162
+ }
163
+ return [
164
+ ` Extracted text${S(e)}:`,
165
+ ...b(e.textContent),
166
+ ...T(e)
167
+ ];
71
168
  }
72
- function m(e) {
73
- let t = e.filter((e) => e.status === "ready");
74
- if (t.length === 0) return "";
75
- let n = r, i = t.map((e) => {
76
- if (e.kind !== "text" || !e.textContent) return e;
77
- if (n <= 0) return {
169
+ function D(e, t, n = O) {
170
+ let r = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${g(e.size)}`];
171
+ return e.downloadUrl && r.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? r.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${g(e.size)}; truncated):` : " Contents:", ...b(e.textContent)) : e.kind === "document" ? r.push(...E(e)) : e.kind === "image" ? n.has(e.id) ? r.push(" NOT VIEWABLE IN THIS MESSAGE — this image did not fit the request-size budget, so only its URL", " travelled; its pixels are NOT attached. Fetch the URL above if you can; otherwise ask the user", " to describe it.", C) : r.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : e.kind === "text" ? r.push(" Text file — contents omitted because this turn ran out of inline budget, not because they are", " unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they", " can re-send just that section.") : r.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), r.join("\n");
172
+ }
173
+ var O = /* @__PURE__ */ new Set();
174
+ function k(e, t) {
175
+ let n = o, i = t, s = [...e], c = (e) => {
176
+ let t = !!e.extraction, o = Math.min(n, a, t ? i : Infinity);
177
+ if (o <= 0) return {
78
178
  ...e,
79
179
  textContent: void 0,
80
180
  textTruncated: !0
81
181
  };
82
- let { text: t, truncated: r } = f(e.textContent, n);
83
- return n -= t.length, {
182
+ if (e.documentPages?.length) {
183
+ let t = r(e.documentPages, o);
184
+ return t.text === "" ? {
185
+ ...e,
186
+ textContent: void 0,
187
+ textTruncated: !0
188
+ } : (n -= t.text.length, i -= t.text.length, {
189
+ ...e,
190
+ textContent: t.text,
191
+ textTruncated: e.textTruncated || t.truncated,
192
+ ...e.extraction ? { extraction: {
193
+ ...e.extraction,
194
+ pagesIncluded: t.pagesIncluded,
195
+ pageNumbers: t.pageNumbers
196
+ } } : {}
197
+ });
198
+ }
199
+ let { text: s, truncated: c } = y(e.textContent ?? "", o);
200
+ return n -= s.length, t && (i -= s.length), {
84
201
  ...e,
85
- textContent: t,
86
- textTruncated: e.textTruncated || r
202
+ textContent: s,
203
+ textTruncated: e.textTruncated || c
87
204
  };
205
+ };
206
+ for (let t of [!1, !0]) e.forEach((e, n) => {
207
+ e.textContent && !!e.extraction === t && (s[n] = c(e));
88
208
  });
209
+ return s;
210
+ }
211
+ function A(e, t, n) {
212
+ let r = k(e, t);
89
213
  return [
90
214
  "",
91
- `--- Attachments (${t.length}) ---`,
215
+ `--- Attachments (${e.length}) ---`,
92
216
  "The user attached the following file(s) to this message.",
93
- ...i.map(p),
217
+ ...r.map((e, t) => D(e, t, n)),
94
218
  "--- End attachments ---"
95
219
  ].join("\n");
96
220
  }
97
- function h(e, t) {
98
- let n = m(t);
221
+ var j = 1024;
222
+ function M(e, t) {
223
+ let n = U(e);
224
+ if (n.length === 0) return {
225
+ documentChars: o,
226
+ demotedImageIds: O
227
+ };
228
+ let r = (r, i, a) => {
229
+ let o = new Set(n.slice(0, r).map((e) => e.id)), s = A(e, i, a), c = t ? `${t}\n${s}` : s.trimStart(), { media: l } = W(e, o);
230
+ return z(c, [{
231
+ type: "text",
232
+ text: c
233
+ }, ...l]) + j <= F;
234
+ };
235
+ for (let e = n.length; e >= 0; --e) {
236
+ let t = new Set(n.slice(e).map((e) => e.id));
237
+ if (r(e, 2e4, t)) return {
238
+ documentChars: o,
239
+ demotedImageIds: t
240
+ };
241
+ if (!r(e, 0, t)) continue;
242
+ let i = 0, a = o;
243
+ for (; i < a;) {
244
+ let n = Math.ceil((i + a) / 2);
245
+ r(e, n, t) ? i = n : a = n - 1;
246
+ }
247
+ return {
248
+ documentChars: i,
249
+ demotedImageIds: t
250
+ };
251
+ }
252
+ return {
253
+ documentChars: o,
254
+ demotedImageIds: new Set(n.map((e) => e.id))
255
+ };
256
+ }
257
+ function N(e, t = "") {
258
+ let n = e.filter((e) => e.status === "ready");
259
+ if (n.length === 0) return "";
260
+ let r = M(n, t);
261
+ return A(n, r.documentChars, r.demotedImageIds);
262
+ }
263
+ function P(e, t) {
264
+ let n = N(t, e);
99
265
  return n ? e ? `${e}\n${n}` : n.trimStart() : e;
100
266
  }
101
- var g = e - 32768, _ = .6, v = typeof TextEncoder == "function" ? new TextEncoder() : null;
102
- function y(e) {
103
- return v ? v.encode(e).length : e.length;
267
+ var F = e - 32768, I = .6, L = typeof TextEncoder == "function" ? new TextEncoder() : null;
268
+ function R(e) {
269
+ return L ? L.encode(e).length : e.length;
104
270
  }
105
- function b(e, t) {
106
- return y(JSON.stringify({
271
+ function z(e, t) {
272
+ return R(JSON.stringify({
107
273
  prompt: e,
108
274
  parts: t ?? []
109
275
  }));
110
276
  }
111
- function x(e) {
277
+ function B(e) {
112
278
  return e.filter((e) => e.status === "ready" && e.kind === "image" && !!(e.inlineDataUrl ?? e.previewUrl)).length;
113
279
  }
114
- function S(e) {
280
+ function V(e) {
115
281
  return (e ?? []).filter((e) => e.type === "image" && !!e.data).length;
116
282
  }
117
- function C(e) {
283
+ function H(e) {
118
284
  let t = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(e);
119
285
  return t ? {
120
286
  mimeType: t[1],
121
287
  base64: t[2]
122
288
  } : null;
123
289
  }
124
- function w(e, t) {
125
- let n = t.filter((e) => e.status === "ready");
126
- if (n.length === 0) return;
127
- let r = [], i = [], a = 0, o = 0;
128
- for (let e of n) {
129
- if (e.kind === "image") {
130
- let t = e.inlineDataUrl ?? e.previewUrl, n = t ? C(t) : null;
131
- if (n !== null && a < 3 && o + n.base64.length <= 15e5 && n) {
132
- a += 1, o += n.base64.length, i.push(r.length), r.push({
290
+ function U(e) {
291
+ let t = [], n = 0;
292
+ for (let r of e) {
293
+ if (r.kind !== "image") continue;
294
+ let e = r.inlineDataUrl ?? r.previewUrl, i = e ? H(e) : null;
295
+ i && (t.length >= 3 || n + i.base64.length > 15e5 || (t.push(r), n += i.base64.length));
296
+ }
297
+ return t;
298
+ }
299
+ function W(e, t) {
300
+ let n = [], r = [];
301
+ for (let i of e) {
302
+ if (i.kind === "image") {
303
+ let e = i.inlineDataUrl ?? i.previewUrl, a = e ? H(e) : null;
304
+ if (a && t.has(i.id)) {
305
+ r.push(n.length), n.push({
133
306
  type: "image",
134
- mimeType: n.mimeType,
135
- data: n.base64,
136
- ...e.downloadUrl ? { url: e.downloadUrl } : {},
137
- name: e.filename
307
+ mimeType: a.mimeType,
308
+ data: a.base64,
309
+ ...i.downloadUrl ? { url: i.downloadUrl } : {},
310
+ name: i.filename
138
311
  });
139
312
  continue;
140
313
  }
141
- e.downloadUrl && r.push({
314
+ i.downloadUrl && n.push({
142
315
  type: "image",
143
- mimeType: e.mimeType,
144
- url: e.downloadUrl,
145
- name: e.filename
316
+ mimeType: i.mimeType,
317
+ url: i.downloadUrl,
318
+ name: i.filename
146
319
  });
147
320
  continue;
148
321
  }
149
- e.downloadUrl && r.push({
322
+ i.downloadUrl && n.push({
150
323
  type: "file",
151
- mimeType: e.mimeType,
152
- url: e.downloadUrl,
153
- name: e.filename
324
+ mimeType: i.mimeType,
325
+ url: i.downloadUrl,
326
+ name: i.filename
154
327
  });
155
328
  }
329
+ return {
330
+ media: n,
331
+ inlinedIndices: r
332
+ };
333
+ }
334
+ function G(e, t) {
335
+ let n = t.filter((e) => e.status === "ready");
336
+ if (n.length === 0) return;
337
+ let { media: r, inlinedIndices: i } = W(n, new Set(U(n).map((e) => e.id)));
156
338
  if (r.length !== 0) {
157
- for (; i.length > 0 && b(e, [{
339
+ for (; i.length > 0 && z(e, [{
158
340
  type: "text",
159
341
  text: e
160
- }, ...r]) > g;) {
342
+ }, ...r]) > F;) {
161
343
  let e = i.pop();
162
344
  if (e === void 0) break;
163
345
  let t = r[e];
@@ -168,16 +350,16 @@ function w(e, t) {
168
350
  name: t.name
169
351
  } : r.splice(e, 1));
170
352
  }
171
- if (r.length !== 0 && !(b(e, [{
353
+ if (r.length !== 0 && !(z(e, [{
172
354
  type: "text",
173
355
  text: e
174
- }, ...r]) > g)) return [{
356
+ }, ...r]) > F)) return [{
175
357
  type: "text",
176
358
  text: e
177
359
  }, ...r];
178
360
  }
179
361
  }
180
362
  //#endregion
181
- export { i as AttachmentRejectedError, _ as INLINE_IMAGE_QUALITY, t as MAX_FILE_BYTES, n as MAX_INLINE_CHARS_PER_FILE, w as buildPromptParts, h as buildPromptWithAttachments, c as classifyAttachment, x as countInlineImageCandidates, S as countInlinedImageParts, l as formatBytes, u as hasAttachmentWorkInFlight, a as toMessageAttachment, f as truncateForInline, d as validateFile };
363
+ export { h as ATTACHMENT_ACCEPT, s as AttachmentRejectedError, I as INLINE_IMAGE_QUALITY, i as MAX_FILE_BYTES, a as MAX_INLINE_CHARS_PER_FILE, G as buildPromptParts, P as buildPromptWithAttachments, d as classifyAttachment, B as countInlineImageCandidates, V as countInlinedImageParts, m as detectDocumentFormat, g as formatBytes, _ as hasAttachmentWorkInFlight, c as toMessageAttachment, y as truncateForInline, v as validateFile };
182
364
 
183
365
  //# sourceMappingURL=assistantAttachments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nimport { MAX_REQUEST_BODY_BYTES } from './gatewayLimits';\n\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\nfunction describeAttachment(attachment: AssistantAttachment, index: number): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = MAX_REQUEST_BODY_BYTES;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return attachments.filter(\n (attachment) =>\n attachment.status === 'ready' &&\n attachment.kind === 'image' &&\n Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.length;\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":";AAgCA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAoDhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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N,UAAU,EAAW;IACrB,KAAK,EAAW;IAChB,MAAM,EAAW;IAClB,CAAC;AAEJ;;AAOF,EAAI,EAAW,eACb,EAAM,KAAK;GACT,MAAM;GACN,UAAU,EAAW;GACrB,KAAK,EAAW;GAChB,MAAM,EAAW;GAClB,CAAC;;AAIF,OAAM,WAAW,GAQrB;SACE,EAAe,SAAS,KACxB,EAAsB,GAAY,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAG,IACpF;GACA,IAAM,IAAQ,EAAe,KAAK;AAClC,OAAI,MAAU,KAAA,EAAW;GACzB,IAAM,IAAO,EAAM;AACf,IAAC,KAAQ,EAAK,SAAS,WACvB,EAAK,MACP,EAAM,KAAS;IAAE,MAAM,EAAK;IAAM,UAAU,EAAK;IAAU,KAAK,EAAK;IAAK,MAAM,EAAK;IAAM,GAI3F,EAAM,OAAO,GAAO,EAAE;;AAItB,QAAM,WAAW,KAQjB,IAAsB,GAAY,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAG,GAIxF,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM"}
1
+ {"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nimport { MAX_REQUEST_BODY_BYTES } from './gatewayLimits';\nimport {\n formatPageRanges,\n isMostlyImagePages,\n truncatePagesForInline,\n type DocumentExtraction,\n type DocumentFormat,\n} from './documentText';\n\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /**\n * Inlined content for this attachment, already truncated to\n * `MAX_INLINE_CHARS_PER_FILE`. Text files carry the file itself; PDF/DOCX/XLSX\n * carry whatever `extractDocumentText` pulled out of them (BOFF-6291).\n */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /**\n * Outcome of the client-side document extraction. Present on every `document`\n * we ATTEMPTED to read — including the failures, which is the point: a scanned\n * or encrypted PDF has to reach the model as a sentence rather than as\n * nothing. Absent means no extractor exists for the type.\n */\n extraction?: DocumentExtraction;\n /**\n * Per-page text for a PDF, kept so the SHARED inline budget can also cut on a\n * page boundary rather than mid-sentence. Already trimmed to the per-file\n * budget at prepare time, so this never holds a whole 50-page document.\n * Draft-only; `toMessageAttachment` never carries it to storage.\n */\n documentPages?: string[];\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\n/**\n * Document formats we can turn into text in the browser (BOFF-6291).\n *\n * Anything else stays a `document` with no extraction, and the prompt block\n * says so — the honest fallback that used to be the ONLY behaviour.\n */\nexport type { DocumentFormat } from './documentText';\n\nconst DOCUMENT_MIME_TYPES: Record<string, DocumentFormat> = {\n 'application/pdf': 'pdf',\n 'application/x-pdf': 'pdf',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n};\n\nconst DOCUMENT_EXTENSIONS: Record<string, DocumentFormat> = {\n pdf: 'pdf',\n docx: 'docx',\n xlsx: 'xlsx',\n};\n\n/**\n * Which extractor (if any) can read this file.\n *\n * MIME first, extension second — same order as `classifyAttachment`, and for\n * the same reason: Windows reports `application/octet-stream` for plenty of\n * files whose extension is perfectly informative.\n */\nexport function detectDocumentFormat(mimeType: string, filename: string): DocumentFormat | null {\n return DOCUMENT_MIME_TYPES[mimeType.toLowerCase()] ?? DOCUMENT_EXTENSIONS[getExtension(filename)] ?? null;\n}\n\n/**\n * The composer's `<input accept>` — DERIVED from what we can actually read.\n *\n * It used to be a hand-written list (`…,.pdf,.csv,.json,.md,.txt,.xlsx,.docx`)\n * that invited exactly the files the model could not see: a farmer picked a\n * soil-test PDF because the picker offered it, and the assistant then asked\n * them to paste it as text. Building the list from `TEXT_EXTENSIONS` and\n * `DOCUMENT_EXTENSIONS` makes that class of mismatch a compile-time\n * impossibility rather than a thing to remember.\n */\nexport const ATTACHMENT_ACCEPT = [\n 'image/*',\n 'text/*',\n ...[...TEXT_EXTENSIONS].map((extension) => `.${extension}`),\n ...Object.keys(DOCUMENT_EXTENSIONS).map((extension) => `.${extension}`),\n].join(',');\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\n/** Indented fenced block holding an attachment's inlined content. */\nfunction fencedContent(content: string): string[] {\n return [' ```', ...content.split('\\n').map((line) => ` ${line}`), ' ```'];\n}\n\n/**\n * The pages whose text is actually in front of the model.\n *\n * `pageNumbers` is the truth when the extractor produced it. `pagesIncluded` is\n * the older, coarser field — how FAR into the document we got — and is only a\n * fallback, because on a document with image pages the two differ and reporting\n * the coarser one is what lets a 40-page certificate with 3 readable pages\n * describe itself as \"40 pages\".\n */\nfunction pagesActuallyRead(extraction: DocumentExtraction | undefined): number[] {\n if (extraction?.pageNumbers?.length) return extraction.pageNumbers;\n if (extraction?.pagesIncluded) return Array.from({ length: extraction.pagesIncluded }, (_, index) => index + 1);\n return [];\n}\n\n/**\n * The parenthetical after \"Extracted text\" — what the model is looking at, and\n * what it is NOT.\n *\n * Deliberately the same shape as the text path's \"first N characters of M;\n * truncated\", because a partial document presented as whole is the single most\n * expensive way this feature can fail: the assistant reads eight thousand\n * characters of a forty-page organic-certification audit and tells the farmer\n * it is compliant.\n *\n * The page fact counts PAGES READ, never pages processed. \"40 pages\" is only\n * ever emitted when all forty are genuinely below.\n */\nfunction extractionScope(attachment: AssistantAttachment): string {\n const extraction = attachment.extraction;\n const facts: string[] = [];\n\n if (extraction?.pageCount) {\n const read = pagesActuallyRead(extraction);\n if (read.length >= extraction.pageCount) {\n facts.push(`${extraction.pageCount} page${extraction.pageCount === 1 ? '' : 's'}`);\n } else if (read.length === 1) {\n facts.push(`page ${read[0]} of ${extraction.pageCount}`);\n } else {\n facts.push(`pages ${formatPageRanges(read)} of ${extraction.pageCount}`);\n }\n }\n if (extraction?.sheetNames?.length) {\n facts.push(`sheets: ${extraction.sheetNames.join(', ')}`);\n }\n if (attachment.textTruncated && attachment.textContent) {\n const total = extraction?.sourceChars;\n facts.push(\n total && total > attachment.textContent.length\n ? `first ${attachment.textContent.length} characters of ${total}; truncated`\n : `first ${attachment.textContent.length} characters; truncated`\n );\n }\n\n return facts.length > 0 ? ` (${facts.join('; ')})` : '';\n}\n\n/**\n * The one sentence every \"you have not seen this\" branch ends on. Kept as a\n * constant so no branch can be added without it.\n */\nconst DO_NOT_GUESS = ' Do NOT guess at, summarise or characterise its contents — you have not seen them.';\n\n/** Closing instruction shared by every \"we could not read this\" branch. */\nconst NO_TEXT_ADVICE = [\n ' Fetch the URL above if you can; otherwise ask the user to paste the relevant section as text.',\n DO_NOT_GUESS,\n];\n\n/**\n * Name the pages that were NOT read, so a document is never presented as whole.\n *\n * Two ways a page goes unread, and the model needs both: it had no text layer\n * (an image page), or it fell outside what we processed — the 100-page scan cap\n * or the inline budget.\n */\nfunction unreadPageDisclosure(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n if (!extraction?.pageCount) return [];\n\n const read = new Set(pagesActuallyRead(extraction));\n const known = new Set(extraction.imagePages ?? []);\n const imagePages = [...known].filter((page) => !read.has(page)).sort((left, right) => left - right);\n const lines: string[] = [];\n\n if (imagePages.length > 0) {\n const label = imagePages.length === 1 ? `Page ${imagePages[0]}` : `Pages ${formatPageRanges(imagePages)}`;\n lines.push(\n ` ${label} of this document contain no extractable text — they are images.`,\n ' Nothing about those pages is available to you.'\n );\n }\n\n const notProcessed: number[] = [];\n for (let page = 1; page <= extraction.pageCount; page += 1) {\n if (!read.has(page) && !known.has(page)) notProcessed.push(page);\n }\n if (notProcessed.length > 0) {\n const label = notProcessed.length === 1 ? `Page ${notProcessed[0]}` : `Pages ${formatPageRanges(notProcessed)}`;\n lines.push(` ${label} of this document ${notProcessed.length === 1 ? 'was' : 'were'} not read at all.`);\n }\n\n if (lines.length > 0) lines.push(DO_NOT_GUESS);\n return lines;\n}\n\n/**\n * What a PDF/DOCX/XLSX attachment says to the model.\n *\n * Every branch is a positive statement. The one thing this must never do is\n * emit an attachment header with nothing after it, because a file that is\n * merely *listed* reads to the model as a file it may reason about.\n */\nfunction describeDocument(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n\n // No extractor ran at all (.zip, .pptx, a legacy .doc). Unchanged behaviour.\n if (!extraction || extraction.status === 'unsupported') {\n return [\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.',\n ];\n }\n\n if (extraction.status === 'no-text') {\n // A PDF with no text layer is a scan. A .docx or .xlsx with no text is\n // simply empty (or holds only images and charts) — saying \"scanned\" there\n // would be a confident, checkable falsehood.\n if (extraction.format === 'docx' || extraction.format === 'xlsx') {\n return [\n ' NO TEXT AVAILABLE — this document holds no readable text; it is either empty or contains only',\n ' images, charts or drawings, none of which carry text. No text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n const scanned =\n extraction.pagesScanned && extraction.pageCount && extraction.pagesScanned < extraction.pageCount\n ? ` (the first ${extraction.pagesScanned} of ${extraction.pageCount} pages were checked)`\n : '';\n return [\n ` NO TEXT AVAILABLE — this document appears to be scanned images; no text could be extracted${scanned}.`,\n ' There is no text layer to read, so nothing about its contents is available to you.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'encrypted') {\n return [\n ' NO TEXT AVAILABLE — this document is encrypted or password-protected; it could not be opened',\n ' and no text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'corrupt') {\n const detail = extraction.detail ? ` (${extraction.detail})` : '';\n return [\n ` NO TEXT AVAILABLE — this file could not be read${detail}; no text could be extracted.`,\n ...NO_TEXT_ADVICE,\n ];\n }\n\n // status === 'ok' but the shared inline budget went to earlier attachments.\n if (!attachment.textContent) {\n return [\n ' Text WAS extracted from this document but is omitted because this turn ran out of inline budget,',\n ' not because it is unavailable. Ask the user which part matters so they can re-send just that',\n ' section, or fetch the URL above if you can.',\n DO_NOT_GUESS,\n ];\n }\n\n // Mostly images: a text layer exists, but on so few pages that presenting the\n // fragment as \"the document\" is the same falsehood as reading a scan. The\n // fragment is still handed over — throwing away three real pages of audit\n // findings would be its own kind of dishonesty — but the header refuses on\n // the document's behalf, so the model cannot treat it as read.\n //\n // Gated on `textPageCount` being PRESENT, never defaulted: an extraction that\n // predates the density pass knows nothing about image pages, and treating\n // \"unknown\" as \"zero text pages\" would refuse a document we read perfectly.\n const scanned = extraction.pagesScanned ?? extraction.pageCount ?? 0;\n const textPages = extraction.textPageCount;\n if (extraction.pageCount && textPages !== undefined && isMostlyImagePages(textPages, scanned)) {\n const imageCount = scanned - textPages;\n return [\n ` NOT READ — this document is mostly images. Only ${textPages} of its ${extraction.pageCount} page${\n extraction.pageCount === 1 ? '' : 's'\n } carr${textPages === 1 ? 'ies' : 'y'} a text layer;`,\n ` the other ${imageCount} contain no extractable text at all. Treat this as a document you have NOT`,\n ' read: the fragment below is the whole of what was available, not a summary of the document.',\n ...unreadPageDisclosure(attachment),\n ` The only extractable text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ];\n }\n\n return [\n ` Extracted text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ...unreadPageDisclosure(attachment),\n ];\n}\n\nfunction describeAttachment(\n attachment: AssistantAttachment,\n index: number,\n demotedImageIds: ReadonlySet<string> = EMPTY_IDS\n): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ...fencedContent(attachment.textContent)\n );\n } else if (attachment.kind === 'document') {\n lines.push(...describeDocument(attachment));\n } else if (attachment.kind === 'image') {\n if (demotedImageIds.has(attachment.id)) {\n // This photo COULD have travelled as pixels and does not, because the\n // turn would otherwise exceed the gateway's body cap. That decision is\n // invisible unless it is said, and an answer written as if the model had\n // looked at a photo it never received is the worst outcome here.\n lines.push(\n ' NOT VIEWABLE IN THIS MESSAGE — this image did not fit the request-size budget, so only its URL',\n ' travelled; its pixels are NOT attached. Fetch the URL above if you can; otherwise ask the user',\n ' to describe it.',\n DO_NOT_GUESS\n );\n } else {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n }\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\n\n/**\n * Spend the shared inline budget.\n *\n * ## Order: verified capabilities first, the new one last\n *\n * Attachments are still served in the order the user picked them, but in TWO\n * passes — text files, then extracted document text. Both of the other two ways\n * an attachment reaches the model (a photo's pixels, a `.csv`'s contents) work\n * in production today; BOFF-6291's extracted document text is new. So when they\n * cannot all fit, the new one yields. A single in-order pass let a dense PDF\n * picked first take 8,000 characters off the `.csv` behind it, which is a\n * regression in a shipped path paid for by a feature nobody had yet.\n *\n * ## Two ceilings, both of which have to hold HERE\n *\n * - `MAX_INLINE_CHARS_PER_FILE`. It used to be applied only by the extractor,\n * and this pass then re-ran the page fit against the whole 20,000-character\n * TOTAL — so a PDF whose page 1 was 30,000 characters came out of prepare at\n * 8,000, went back up to 20,000 here, and the `.csv` attached beside it got\n * nothing at all. The clamp below is the invariant; the extractor storing\n * only the already-fitted pages (`FittedPages.pages`) is its belt.\n * - `documentLimit` — how much document text the request BODY can afford once\n * the images have been paid for. See `fitInlineBudget`.\n */\nfunction applyInlineBudget(usable: AssistantAttachment[], documentLimit: number): AssistantAttachment[] {\n let remaining = MAX_INLINE_CHARS_TOTAL;\n let documentRemaining = documentLimit;\n const budgeted: AssistantAttachment[] = [...usable];\n\n const spend = (attachment: AssistantAttachment): AssistantAttachment => {\n const isDocument = Boolean(attachment.extraction);\n const limit = Math.min(\n remaining,\n MAX_INLINE_CHARS_PER_FILE,\n isDocument ? documentRemaining : Number.POSITIVE_INFINITY\n );\n if (limit <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n\n // A PDF still knows its page boundaries here, so the shared budget cuts on\n // one too rather than undoing the page-aligned trim done at prepare time.\n if (attachment.documentPages?.length) {\n const fitted = truncatePagesForInline(attachment.documentPages, limit);\n if (fitted.text === '') {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n remaining -= fitted.text.length;\n documentRemaining -= fitted.text.length;\n return {\n ...attachment,\n textContent: fitted.text,\n textTruncated: attachment.textTruncated || fitted.truncated,\n ...(attachment.extraction\n ? {\n extraction: {\n ...attachment.extraction,\n pagesIncluded: fitted.pagesIncluded,\n pageNumbers: fitted.pageNumbers,\n },\n }\n : {}),\n };\n }\n\n const { text, truncated } = truncateForInline(attachment.textContent ?? '', limit);\n remaining -= text.length;\n if (isDocument) documentRemaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n };\n\n for (const documents of [false, true]) {\n usable.forEach((attachment, index) => {\n if (!attachment.textContent) return;\n if (Boolean(attachment.extraction) !== documents) return;\n budgeted[index] = spend(attachment);\n });\n }\n\n return budgeted;\n}\n\nfunction renderAttachmentBlock(\n usable: AssistantAttachment[],\n documentLimit: number,\n demotedImageIds: ReadonlySet<string>\n): string {\n const budgeted = applyInlineBudget(usable, documentLimit);\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map((attachment, index) => describeAttachment(attachment, index, demotedImageIds)),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * The one thing the modelled body genuinely misses: `buildPromptForMode`\n * prepends its 493-character api-calls preamble AFTER this block is built, and\n * `parts[0]` duplicates the whole prompt, so it is charged twice — 986 bytes.\n * The GraphQL document and page context are already covered many times over by\n * `TURN_BODY_HEADROOM_BYTES`, so this reserve stays small on purpose: every\n * byte of it is a byte of document text a farmer does not get.\n */\nexport const PROMPT_ENVELOPE_RESERVE_BYTES = 1_024;\n\n/**\n * How much extracted document text this turn can afford, and which photos will\n * therefore still carry pixels.\n *\n * ## The problem\n *\n * `buildPromptParts` demotes inline images to url-only until the body fits the\n * gateway's 256 KB cap. The prompt it measures already contains the attachment\n * block, and `parts[0]` duplicates the whole prompt — so 20,000 characters of\n * extracted document text costs ~41,000 bytes of the budget and can push a\n * perfectly ordinary 80 KB photo out of the turn. Before BOFF-6291 documents\n * contributed no text at all, so this is new pressure on the one attachment\n * capability that is verified working in production, and it is silent.\n *\n * ## The policy\n *\n * Images win. Document text is cut — to zero if that is what it takes — before\n * a single photo loses its pixels. Only if the turn will not fit even with NO\n * document text do we fall back to the pre-existing demotion, and then the\n * prompt block says so on that image (see `describeAttachment`) so the model\n * knows it is not seeing everything.\n *\n * Measured rather than modelled: each candidate budget is rendered and weighed\n * with `estimateTurnBodyBytes`, the same function `buildPromptParts` uses, so\n * the two cannot drift. At most five attachments and ~15 probes per send.\n */\nfunction fitInlineBudget(\n usable: AssistantAttachment[],\n userText: string\n): { documentChars: number; demotedImageIds: ReadonlySet<string> } {\n const candidates = inlineImageCandidates(usable);\n // No pixels at stake: keep the pre-existing behaviour byte for byte.\n if (candidates.length === 0) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: EMPTY_IDS };\n }\n\n const fits = (keep: number, documentChars: number, demoted: ReadonlySet<string>): boolean => {\n const allowed = new Set(candidates.slice(0, keep).map((attachment) => attachment.id));\n const block = renderAttachmentBlock(usable, documentChars, demoted);\n const promptText = userText ? `${userText}\\n${block}` : block.trimStart();\n const { media } = composeMedia(usable, allowed);\n const body = estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]);\n return body + PROMPT_ENVELOPE_RESERVE_BYTES <= MAX_INLINE_TURN_BODY_BYTES;\n };\n\n // `buildPromptParts` pops its inline images from the END, so the first photo —\n // the one the question is usually about — is the last to lose its pixels.\n // Walk the same order, so the set we reserve for is the set it will inline.\n for (let keep = candidates.length; keep >= 0; keep -= 1) {\n const demoted: ReadonlySet<string> = new Set(candidates.slice(keep).map((attachment) => attachment.id));\n if (fits(keep, MAX_INLINE_CHARS_TOTAL, demoted)) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: demoted };\n }\n if (!fits(keep, 0, demoted)) continue;\n\n // Largest document budget that still leaves every one of these images its\n // pixels. Monotone in `documentChars`, so a binary search is exact.\n let low = 0;\n let high = MAX_INLINE_CHARS_TOTAL;\n while (low < high) {\n const mid = Math.ceil((low + high) / 2);\n if (fits(keep, mid, demoted)) low = mid;\n else high = mid - 1;\n }\n return { documentChars: low, demotedImageIds: demoted };\n }\n\n // Not even an image-free, text-free turn fits — the user's own message is\n // over the cap. `buildPromptParts` drops `parts` wholesale in that case, which\n // halves the body, so trimming the document here would buy nothing.\n return {\n documentChars: MAX_INLINE_CHARS_TOTAL,\n demotedImageIds: new Set(candidates.map((attachment) => attachment.id)),\n };\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * `userText` is the user's own message — the rest of the prompt this block will\n * be concatenated with. It is optional only so existing callers and tests keep\n * compiling; passing it is what lets the budget be measured against the real\n * turn rather than against the block alone.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[], userText = ''): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n const budget = fitInlineBudget(usable, userText);\n return renderAttachmentBlock(usable, budget.documentChars, budget.demotedImageIds);\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments, content);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = MAX_REQUEST_BODY_BYTES;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return attachments.filter(\n (attachment) =>\n attachment.status === 'ready' &&\n attachment.kind === 'image' &&\n Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * The ready images that COULD travel as pixels, in turn order, after the two\n * static budgets (`MAX_INLINE_IMAGE_PARTS`, `MAX_INLINE_IMAGE_BASE64_CHARS`).\n *\n * Factored out so `fitInlineBudget` reserves body space for exactly the set\n * `buildPromptParts` will try to inline, rather than for its own guess at it.\n */\nfunction inlineImageCandidates(usable: AssistantAttachment[]): AssistantAttachment[] {\n const chosen: AssistantAttachment[] = [];\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind !== 'image') continue;\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n if (!parsed) continue;\n if (chosen.length >= MAX_INLINE_IMAGE_PARTS) continue;\n if (inlineChars + parsed.base64.length > MAX_INLINE_IMAGE_BASE64_CHARS) continue;\n chosen.push(attachment);\n inlineChars += parsed.base64.length;\n }\n\n return chosen;\n}\n\n/**\n * The media parts for a turn, given which images are allowed to carry bytes.\n *\n * Everything not in `inlinedImageIds` degrades to url-only, exactly as the\n * demotion loop would leave it — so weighing a hypothetical turn and building\n * the real one go through the same code.\n */\nfunction composeMedia(\n usable: AssistantAttachment[],\n inlinedImageIds: ReadonlySet<string>\n): { media: AssistantPromptPart[]; inlinedIndices: number[] } {\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n\n if (parsed && inlinedImageIds.has(attachment.id)) {\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Document BYTES are never inlined: a PDF is not an image, and 10 MB of it\n // would not fit the body anyway. Its TEXT already travels in the prompt\n // block (BOFF-6291 extracts it client-side), so what a part adds here is\n // only the reference — same as for text files, and a missing URL costs\n // nothing because the content is already across.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n return { media, inlinedIndices };\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const candidates = new Set(inlineImageCandidates(usable).map((attachment) => attachment.id));\n const { media, inlinedIndices } = composeMedia(usable, candidates);\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":";;AAuCA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAsEhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAWT,IAAM,IAAsD;CAC1D,mBAAmB;CACn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