@arbidocs/react 0.5.102 → 0.5.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/annotations/freeze/index.cjs +14 -14
  2. package/dist/annotations/freeze/index.js +3 -3
  3. package/dist/artifacts/index.cjs +45 -45
  4. package/dist/artifacts/index.js +8 -8
  5. package/dist/bundle-DCWPYNGD.cjs +14 -0
  6. package/dist/{bundle-IC65W2AO.cjs.map → bundle-DCWPYNGD.cjs.map} +1 -1
  7. package/dist/bundle-JCKKGEJE.js +5 -0
  8. package/dist/{bundle-YNOX7VIL.js.map → bundle-JCKKGEJE.js.map} +1 -1
  9. package/dist/calls/livekit/index.cjs +51 -51
  10. package/dist/calls/livekit/index.d.cts +1 -1
  11. package/dist/calls/livekit/index.d.ts +1 -1
  12. package/dist/calls/livekit/index.js +6 -6
  13. package/dist/{chunk-WJME7DI4.cjs → chunk-524AFWK7.cjs} +68 -68
  14. package/dist/{chunk-WJME7DI4.cjs.map → chunk-524AFWK7.cjs.map} +1 -1
  15. package/dist/{chunk-Q65QCWNI.cjs → chunk-6TUNWGRJ.cjs} +60 -60
  16. package/dist/{chunk-Q65QCWNI.cjs.map → chunk-6TUNWGRJ.cjs.map} +1 -1
  17. package/dist/{chunk-NDIKMOBJ.cjs → chunk-7C77IBQZ.cjs} +3 -3
  18. package/dist/{chunk-NDIKMOBJ.cjs.map → chunk-7C77IBQZ.cjs.map} +1 -1
  19. package/dist/{chunk-OYPKKHXY.js → chunk-7KZS22EK.js} +4 -4
  20. package/dist/{chunk-OYPKKHXY.js.map → chunk-7KZS22EK.js.map} +1 -1
  21. package/dist/{chunk-NIKPG4PW.js → chunk-A2XSLTIP.js} +3 -3
  22. package/dist/{chunk-NIKPG4PW.js.map → chunk-A2XSLTIP.js.map} +1 -1
  23. package/dist/{chunk-ALT6ETIE.js → chunk-A6HUB6PX.js} +6 -6
  24. package/dist/{chunk-ALT6ETIE.js.map → chunk-A6HUB6PX.js.map} +1 -1
  25. package/dist/{chunk-PC4O3JDV.cjs → chunk-B6I2HRRF.cjs} +3 -3
  26. package/dist/{chunk-PC4O3JDV.cjs.map → chunk-B6I2HRRF.cjs.map} +1 -1
  27. package/dist/{chunk-UW2SGTI5.js → chunk-GR7CZEJJ.js} +3 -3
  28. package/dist/{chunk-UW2SGTI5.js.map → chunk-GR7CZEJJ.js.map} +1 -1
  29. package/dist/{chunk-VIOW22Q4.cjs → chunk-IXE7HCCA.cjs} +44 -44
  30. package/dist/{chunk-VIOW22Q4.cjs.map → chunk-IXE7HCCA.cjs.map} +1 -1
  31. package/dist/{chunk-4SH5INC3.js → chunk-LD2SJBXC.js} +5 -5
  32. package/dist/{chunk-4SH5INC3.js.map → chunk-LD2SJBXC.js.map} +1 -1
  33. package/dist/{chunk-6SG2OGDR.js → chunk-M74JCOXW.js} +7 -2
  34. package/dist/chunk-M74JCOXW.js.map +1 -0
  35. package/dist/{chunk-YIZH5RVW.js → chunk-MAUZSNQY.js} +3 -3
  36. package/dist/{chunk-YIZH5RVW.js.map → chunk-MAUZSNQY.js.map} +1 -1
  37. package/dist/{chunk-HAGC67GL.cjs → chunk-Q2GNEVG2.cjs} +7 -2
  38. package/dist/chunk-Q2GNEVG2.cjs.map +1 -0
  39. package/dist/{chunk-ZEGCZATR.js → chunk-RC42YRVA.js} +4 -4
  40. package/dist/{chunk-ZEGCZATR.js.map → chunk-RC42YRVA.js.map} +1 -1
  41. package/dist/{chunk-Z3W4XFWB.cjs → chunk-TTHJNRLY.cjs} +5 -5
  42. package/dist/{chunk-Z3W4XFWB.cjs.map → chunk-TTHJNRLY.cjs.map} +1 -1
  43. package/dist/{chunk-5X3JANHT.js → chunk-V73GLDHD.js} +4 -4
  44. package/dist/{chunk-5X3JANHT.js.map → chunk-V73GLDHD.js.map} +1 -1
  45. package/dist/{chunk-ORBUPHMV.cjs → chunk-YD25DEMR.cjs} +41 -41
  46. package/dist/{chunk-ORBUPHMV.cjs.map → chunk-YD25DEMR.cjs.map} +1 -1
  47. package/dist/{chunk-5EELSW26.cjs → chunk-YNKV4MN6.cjs} +6 -6
  48. package/dist/{chunk-5EELSW26.cjs.map → chunk-YNKV4MN6.cjs.map} +1 -1
  49. package/dist/document-tools/core.cjs +100 -100
  50. package/dist/document-tools/core.d.cts +2 -2
  51. package/dist/document-tools/core.d.ts +2 -2
  52. package/dist/document-tools/core.js +5 -5
  53. package/dist/document-tools/index.cjs +103 -103
  54. package/dist/document-tools/index.d.cts +1 -1
  55. package/dist/document-tools/index.d.ts +1 -1
  56. package/dist/document-tools/index.js +7 -7
  57. package/dist/index.cjs +2355 -2211
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.cts +137 -27
  60. package/dist/index.d.ts +137 -27
  61. package/dist/index.js +175 -39
  62. package/dist/index.js.map +1 -1
  63. package/dist/{query-keys.d-O3lHn6rp.d.cts → query-keys.d-Bpb7R_lB.d.cts} +5 -0
  64. package/dist/{query-keys.d-O3lHn6rp.d.ts → query-keys.d-Bpb7R_lB.d.ts} +5 -0
  65. package/dist/shell/index.cjs +39 -39
  66. package/dist/shell/index.js +4 -4
  67. package/dist/{useAudioRecorder.d-DpDeeeAZ.d.cts → useAudioRecorder.d-B9rlMI_E.d.cts} +1 -1
  68. package/dist/{useAudioRecorder.d-DpDeeeAZ.d.ts → useAudioRecorder.d-B9rlMI_E.d.ts} +1 -1
  69. package/package.json +3 -3
  70. package/dist/bundle-IC65W2AO.cjs +0 -14
  71. package/dist/bundle-YNOX7VIL.js +0 -5
  72. package/dist/chunk-6SG2OGDR.js.map +0 -1
  73. package/dist/chunk-HAGC67GL.cjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkVOFNX4P6_cjs = require('./chunk-VOFNX4P6.cjs');
4
3
  var chunk5NOZDH3F_cjs = require('./chunk-5NOZDH3F.cjs');
4
+ var chunkVOFNX4P6_cjs = require('./chunk-VOFNX4P6.cjs');
5
5
 
6
6
  // src/ai/stored-markdown.ts
7
7
  var FENCE = /^\s*(```|~~~)/;
@@ -305,5 +305,5 @@ exports.unescapeMarkdown = unescapeMarkdown;
305
305
  exports.unwrapCitationLinks = unwrapCitationLinks;
306
306
  exports.versionLabel = versionLabel;
307
307
  exports.versionRef = versionRef;
308
- //# sourceMappingURL=chunk-NDIKMOBJ.cjs.map
309
- //# sourceMappingURL=chunk-NDIKMOBJ.cjs.map
308
+ //# sourceMappingURL=chunk-7C77IBQZ.cjs.map
309
+ //# sourceMappingURL=chunk-7C77IBQZ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai/stored-markdown.ts","../src/artifacts/versions.ts"],"names":["normalizeCitationMarkup","normalizeMarkdown"],"mappings":";;;;;;AAgBA,IAAM,KAAA,GAAQ,eAAA;AAGd,SAAS,gBAAA,CAAiB,MAAc,EAAA,EAAsC;AAC5E,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,OAAO,KACJ,KAAA,CAAM,IAAI,CAAA,CACV,GAAA,CAAI,CAAC,IAAA,KAAS;AACb,IAAA,IAAI,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG;AACpB,MAAA,OAAA,GAAU,CAAC,OAAA;AACX,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAA,GAAU,IAAA,GAAO,EAAA,CAAG,IAAI,CAAA;AAAA,EACjC,CAAC,CAAA,CACA,IAAA,CAAK,IAAI,CAAA;AACd;AAOA,IAAM,mBAAA,GAAsB,+BAAA;AAE5B,IAAM,gBAAA,GAAmB,WAAA;AACzB,IAAM,WAAA,GAAc,8BAAA;AAoBb,SAAS,iBAAiB,IAAA,EAAsB;AACrD,EAAA,IAAI,CAAC,IAAA,CAAK,QAAA,CAAS,IAAI,GAAG,OAAO,IAAA;AACjC,EAAA,OAAO,gBAAA,CAAiB,IAAA,EAAM,CAAC,IAAA,KAAS;AACtC,IAAA,IAAI,CAAC,IAAA,CAAK,QAAA,CAAS,I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,OAAO,CAAC,CAAC,EAAA,IAAM,MAAA,CAAO,KAAK,EAAE,CAAA;AAC/B","file":"chunk-NDIKMOBJ.cjs","sourcesContent":["/**\n * Helpers for markdown that is STORED (an agent's draft saved as an artifact, then read back from\n * the backend's parse). Pure and SDK-free; they sit next to `normalizeCitationMarkup`, which they\n * build on.\n *\n * Two directions:\n *\n * - Going in (`cleanDraftMarkdown` = `unwrapCitationLinks` + `stripAgentPreamble` +\n * `promoteBoldTitle`): a streamed draft carries citation links, `(*Source: ...*)` notes and\n * sometimes narration before the document. A stored letter should hold only the letter.\n * - Coming out (`unescapeMarkdown`): the backend's parse of a stored `.md` returns the text with\n * markdown punctuation backslash-escaped (`**Fees.**` comes back as `\\*\\*Fees\\.\\*\\*`).\n */\n\nimport { normalizeCitationMarkup } from './normalize-citations'\n\nconst FENCE = /^\\s*(```|~~~)/\n\n/** Run `fn` on every line outside a fenced code block. */\nfunction mapOutsideFences(text: string, fn: (line: string) => string): string {\n let inFence = false\n return text\n .split('\\n')\n .map((line) => {\n if (FENCE.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : fn(line)\n })\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Coming out: undo the parser's escaping\n// ---------------------------------------------------------------------------------------------\n\n/** A backslash followed by markdown punctuation: the only thing the parser's escaping produces. */\nconst ESCAPED_PUNCTUATION = /\\\\([\\\\`*_{}[\\]()#+\\-.!|>~<])/g\n/** The only escapes the parser puts inside an inline code span. */\nconst ESCAPED_EMPHASIS = /\\\\([*_])/g\nconst INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\\1(?!`)/g\n\n/**\n * Undo the backend's escaping of a markdown artifact: `\\*\\*Scope\\.\\*\\*` becomes `**Scope.**`.\n *\n * THE RULE. Apply this ONLY to text of an artifact that was stored from markdown (an agent draft\n * or an edited version, always uploaded as `.md`): for those the parser escapes every markdown\n * punctuation character, including the backslash itself, so removing one level of escaping is the\n * exact inverse (an author's literal `\\*` is stored as `\\\\\\*` and comes back as `\\*`). Do not\n * apply it to a PDF or Word parse, where a backslash is just a character.\n *\n * Details:\n * - Only a backslash followed by markdown punctuation (``\\ ` * _ { } [ ] ( ) # + - . ! | > ~ <``)\n * is removed; `\\n`, `C:\\temp` and a trailing backslash are left alone.\n * - Pairs are read left to right, so `\\\\*` is an escaped backslash followed by a bare `*`.\n * - Fenced code blocks are never touched (the parser does not escape inside them).\n * - Inline code spans: the parser DOES escape `*` and `_` there (`` `a*b` `` comes back as\n * `` `a\\*b` ``), so only `\\*` and `\\_` are undone inside a span; any other backslash in code\n * (`` `re\\.x` ``) is a literal and stays.\n */\nexport function unescapeMarkdown(text: string): string {\n if (!text.includes('\\\\')) return text\n return mapOutsideFences(text, (line) => {\n if (!line.includes('\\\\')) return line\n let out = ''\n let last = 0\n for (const span of line.matchAll(INLINE_CODE)) {\n const at = span.index ?? 0\n out +=\n line.slice(last, at).replace(ESCAPED_PUNCTUATION, '$1') +\n span[0].replace(ESCAPED_EMPHASIS, '$1')\n last = at + span[0].length\n }\n return out + line.slice(last).replace(ESCAPED_PUNCTUATION, '$1')\n })\n}\n\n/**\n * The parser also mangles the TITLE of a stored markdown document (seen on a real backend): the\n * first heading comes back doubled (`## # Title`) or alone inside a code fence\n * (a fence, `# Title`, a fence). Both are repaired, on the first non-blank line only, so a code\n * block or heading later in the text is never touched. Like `unescapeMarkdown`, apply it only to\n * artifacts stored from markdown.\n */\nexport function repairParsedTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const doubled = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/.exec(lines[first])\n if (doubled) {\n lines[first] = doubled[1]\n return lines.join('\\n')\n }\n if (/^\\s*```\\s*$/.test(lines[first]) && /^#{1,6}\\s+\\S/.test(lines[first + 1] ?? '')) {\n if (/^\\s*```\\s*$/.test(lines[first + 2] ?? '')) lines.splice(first + 2, 1)\n else return text\n lines.splice(first, 1)\n return lines.join('\\n')\n }\n return text\n}\n\nconst DOUBLED_HEADING = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_HEADING = /^[-*+]\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_IN_LIST = /^[-*+]\\s+[-*+]\\s+(\\S.*)$/\nconst LIST_ORDINAL = /^[-*+]\\s+(\\d{1,9})([.)])\\s+(\\S.*)$/\nconst LIST_ITEM_LINE = /^\\s*(?:[-*+]|\\d{1,9}[.)])\\s/\nconst TABLE_DELIMITER_CELL = /^:?-{1,}:?$/\n\n/** `1. a 2. b 3. c` (one line) split where the next ordinal follows: `['1. a', '2. b', '3. c']`. */\nfunction splitRunOfOrdinals(first: number, delimiter: string, rest: string): string[] {\n const items: string[] = []\n let n = first\n let remaining = rest\n for (;;) {\n const next = new RegExp(`^(.+?)\\\\s+${n + 1}\\\\${delimiter}\\\\s+(\\\\S.*)$`).exec(remaining)\n if (!next) break\n items.push(`${n}${delimiter} ${next[1]}`)\n n += 1\n remaining = next[2]\n }\n items.push(`${n}${delimiter} ${remaining}`)\n return items\n}\n\n/**\n * A table the parser put on ONE line (`| h | h | |---|---| | a | b |`, rows joined by a space, which\n * leaves one empty cell between rows) back as a pipe table. `null` when the line is not that shape.\n */\nfunction rebuildFlatTable(line: string): string[] | null {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) return null\n const cells = trimmed\n .slice(1, -1)\n .split('|')\n .map((c) => c.trim())\n const firstRule = cells.findIndex((c) => TABLE_DELIMITER_CELL.test(c))\n if (firstRule < 2 || cells[firstRule - 1] !== '') return null\n const columns = firstRule - 1\n const rows: string[][] = []\n for (let at = 0; at < cells.length; at += columns + 1) {\n const row = cells.slice(at, at + columns)\n const gap = cells[at + columns]\n if (row.length !== columns || (gap !== undefined && gap !== '')) return null\n rows.push(row)\n }\n const [header, rule, ...body] = rows\n if (!rule.every((c) => TABLE_DELIMITER_CELL.test(c))) return null\n const fmt = (row: string[]): string => `| ${row.join(' | ')} |`\n return [fmt(header), fmt(rule.map(() => '---')), ...body.map(fmt)]\n}\n\n/**\n * Undo how the backend's parse of a stored `.md` restructures it (seen on a real backend):\n * - a heading comes back doubled (`## # Title`) or as a list item (`- # Title`);\n * - every list item gets a `- ` of its own on top of the original marker, so `* a` returns as\n * `- * a` and `1. a` as `- 1. a`, which a markdown editor loads as a list inside a list item\n * (and saves as `- - a`); a run of ordinals can come back on one line (`- 1. a 2. b`);\n * - a table comes back on one line.\n * List nesting and the bullet/ordered difference of a flat `- x` cannot be recovered, so items\n * stay flat. Items of one list are kept tight (no blank line between them). Fenced code is\n * never touched. Like `unescapeMarkdown`, apply it only to artifacts stored from markdown.\n */\nexport function repairParsedStructure(text: string): string {\n const out: string[] = []\n let inFence = false\n for (const line of text.split('\\n')) {\n if (FENCE.test(line)) {\n inFence = !inFence\n out.push(line)\n continue\n }\n if (inFence) {\n out.push(line)\n continue\n }\n const table = rebuildFlatTable(line)\n if (table) {\n out.push(...table)\n continue\n }\n const heading = DOUBLED_HEADING.exec(line) ?? LIST_HEADING.exec(line)\n if (heading) {\n out.push(heading[1])\n continue\n }\n const ordinal = LIST_ORDINAL.exec(line)\n if (ordinal) {\n out.push(...splitRunOfOrdinals(Number(ordinal[1]), ordinal[2], ordinal[3]))\n continue\n }\n const nested = LIST_IN_LIST.exec(line)\n out.push(nested ? `- ${nested[1]}` : line)\n }\n // Items parsed as separate chunks arrive one blank line apart: that is one tight list.\n return out\n .filter(\n (line, i) =>\n !(\n line === '' &&\n LIST_ITEM_LINE.test(out[i - 1] ?? '') &&\n LIST_ITEM_LINE.test(out[i + 1] ?? '')\n )\n )\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Going in: clean a streamed draft before it is stored\n// ---------------------------------------------------------------------------------------------\n\n/** `(*Source: Terms.pdf*)`, `(Sources: a, b)` and the italic form `*(Source: ...)*`. */\nconst SOURCE_NOTE =\n /[ \\t]*(?:\\*+\\(\\s*Sources?\\s*:[^)\\n]*\\)\\*+|\\(\\s*\\*{0,2}\\s*Sources?\\s*:[^)\\n]*\\))/gi\nconst CITE_TOKEN = /^\\]\\(#cite-[\\w-]+\\)/\n\n/**\n * Remove the citation links of ONE line and keep every word. A link is `[text](#cite-N)`, but the\n * model also writes brackets inside the text (`[We act for [PLACEHOLDER].](#cite-1)`) and links that\n * overlap other brackets, so a regex cannot find the opening bracket. This scans the line with a\n * stack of `[`: a `](#cite-N)` takes the nearest open `[` with it (both are removed, the text\n * between stays); a plain `]` closes the nearest `[`; a `](#cite-N)` with no open `[` loses only\n * the marker. Brackets that are not part of a link are never touched.\n */\nfunction removeCitationLinks(line: string): string {\n if (!line.includes('](#cite-')) return line\n const drop = new Set<number>()\n const open: number[] = []\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === '[') open.push(i)\n else if (c === ']') {\n const token = CITE_TOKEN.exec(line.slice(i, i + 40))\n if (token) {\n const opener = open.pop()\n if (opener !== undefined) drop.add(opener)\n for (let k = i; k < i + token[0].length; k++) drop.add(k)\n i += token[0].length - 1\n } else open.pop()\n }\n }\n let out = ''\n for (let i = 0; i < line.length; i++) if (!drop.has(i)) out += line[i]\n return out\n}\n\n/** A line whose `**` do not pair up (one half was wrapped into a link) loses the stray marks. */\nfunction balanceBold(line: string): string {\n // A bold-wrapped heading (`**# Title**`) is just a heading.\n if (/^\\s*\\*\\*#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '').trim()\n if ((line.match(/\\*\\*/g)?.length ?? 0) % 2 === 0) return line\n if (/^#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '')\n return line.replace(/\\*\\*\\s*$/, '').replace(/^(\\s*(?:[-*]\\s+)?)\\*\\*(?=\\s)/, '$1')\n}\n\n/**\n * Text for storage from text that carries citations: `normalizeCitationMarkup` first (it hoists\n * list, heading and bold tokens out of the link so unwrapping cannot orphan half of a `**` pair),\n * then `[text](#cite-N)` becomes `text`, `(*Source: ...*)` notes are dropped, and a bold or\n * heading marker that lost its partner is repaired. Fenced code is left alone.\n */\nexport function unwrapCitationLinks(text: string): string {\n const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ''))\n return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {\n const unlinked = removeCitationLinks(line)\n return unlinked === line ? line : balanceBold(unlinked)\n })\n}\n\nconst HEADING = /^#{1,6}\\s+\\S/\nconst HR_ONLY = /^\\s*(?:-{3,}|\\*{3,}|_{3,})\\s*$/\n/** A whole-line bold title: `**Client Engagement Letter**`. */\nconst BOLD_LINE = /^\\*\\*[^*#].*\\*\\*$/\nconst MAX_PREAMBLE_CHARS = 900\nconst MAX_PREAMBLE_PARAGRAPHS = 4\nconst MAX_TITLE_CHARS = 100\n\n/**\n * How a paragraph of agent narration opens. An ALLOW-LIST: a paragraph that opens any other way is\n * treated as document text and never removed.\n */\nconst NARRATION_OPENER =\n /^(?:I(?:['’](?:ll|ve|m|d))?\\s|let me\\b|here(?:['’]s| is| are)\\b|below is\\b|sure[,.! ]|certainly[,.! ]|of course[,.! ]|okay[,.! ]|based on (?:the|your|my)\\b|per the (?:user|instructions?)|as requested\\b|the workspace\\b|no (?:relevant |workspace |matching )?documents?\\b|there (?:are|is) no (?:relevant |workspace )?documents?\\b|after (?:reviewing|reading|searching)\\b)/i\n\n/** Structure a covering note would not have: lists, tables, quotes, code, headings, bold, links. */\nconst STRUCTURED = /^\\s*(?:[-*+>|]|\\d{1,9}[.)]\\s|#{1,6}\\s|```|~~~)|\\*\\*|\\]\\(/m\n\n/**\n * Cut the agent's narration written BEFORE the document. Strictly non-destructive: if in doubt the\n * text is returned whole (a stray sentence is easy to delete, a lost clause is not recoverable).\n *\n * Text is removed only when ALL of these hold:\n * 1. a real markdown heading line (`# Title`, any level) follows it, and the cut stops exactly at\n * the FIRST such line (never at a bold line, never at a line that merely contains `**`);\n * 2. what precedes it is at most 4 paragraphs and 900 characters of plain prose (horizontal rules\n * between them are ignored): no list, table, quote, code, heading, bold or link;\n * 3. EVERY paragraph opens with an allow-listed narration opener: first person (\"I'll ...\",\n * \"I now have ...\"), \"Let me\", \"Here is/are\", \"Below is\", \"Sure\", \"Based on the ...\", \"Per the\n * instructions\", \"As requested\", \"The workspace ...\", \"No (relevant) documents ...\", \"There is\n * no document ...\", \"After reviewing ...\".\n * Anything else (a dateline, an address, a salutation, a sentence of the letter) keeps the text whole.\n */\nexport function stripAgentPreamble(text: string): string {\n const lines = text.split('\\n')\n const start = lines.findIndex((l) => HEADING.test(l))\n if (start <= 0) return text\n const before = lines\n .slice(0, start)\n .filter((l) => !HR_ONLY.test(l))\n .join('\\n')\n .trim()\n if (!before) return lines.slice(start).join('\\n')\n const paragraphs = before.split(/\\n\\s*\\n/).map((p) => p.trim())\n const narration =\n before.length <= MAX_PREAMBLE_CHARS &&\n paragraphs.length <= MAX_PREAMBLE_PARAGRAPHS &&\n !STRUCTURED.test(before) &&\n paragraphs.every((p) => NARRATION_OPENER.test(p))\n return narration ? lines.slice(start).join('\\n') : text\n}\n\n/**\n * Make the document's title a real heading: the FIRST non-blank line of the text, when it is a\n * short whole-line bold title (`**Letter**`, even with a stray inner `**`), becomes `# Letter`.\n * Nothing else is ever promoted: not a later line, not a mid-sentence fragment (the title must\n * start with a capital or digit, be at most 100 characters, hold no sentence break and not end in\n * `,` `;` or `:`), and a document that already opens with a heading is left alone.\n */\nexport function promoteBoldTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const line = lines[first].trim()\n if (!BOLD_LINE.test(line)) return text\n const title = line.replace(/\\*\\*/g, '').trim()\n if (\n title.length === 0 ||\n title.length > MAX_TITLE_CHARS ||\n !/^[\\p{Lu}\\d]/u.test(title) ||\n /[,;:]$/.test(title) ||\n /[.!?]\\s+\\S/.test(title)\n ) {\n return text\n }\n lines[first] = `# ${title}`\n return lines.join('\\n')\n}\n\n/** Tidy headings only: strip stray bold marks from heading lines (`# **Title**`). */\nfunction cleanHeadings(text: string): string {\n return mapOutsideFences(text, (line) =>\n /^\\s*#{1,6}\\s/.test(line) ? line.replace(/\\*\\*/g, '').trim() : line\n )\n}\n\n/** Which stage of the cleanup produced the text that is returned. */\nexport type DraftCleanStage = 'cleaned' | 'unwrapped' | 'raw'\n\nexport interface DraftCleanReport {\n /** What to store. */\n text: string\n /**\n * `cleaned`: the full cleanup. `unwrapped`: only the citation links were removed (the preamble or\n * title step was rejected by the guard). `raw`: the input as streamed (even link removal was\n * rejected).\n */\n stage: DraftCleanStage\n /** Length of the returned text over the length of the input without its citation markup. */\n ratio: number\n /** Which steps changed the text before the guard (for logs). */\n changedBy: ('citations' | 'preamble' | 'title')[]\n /** The guard rejected a step because it would have lost content. */\n guarded: boolean\n}\n\nconst MIN_RATIO = 0.7\nconst countMatches = (text: string, re: RegExp): number => text.match(re)?.length ?? 0\nconst LIST_NUMBER = /^\\s*\\d{1,9}[.)]\\s/gm\nconst HEADING_LINE = /^#{1,6}\\s/gm\n/** The text with only its citation markup gone: the floor no cleanup may go far under. */\nconst withoutCitationMarkup = (raw: string): string =>\n mapOutsideFences(raw.replace(SOURCE_NOTE, ''), removeCitationLinks).trim()\nconst tidy = (text: string): string => text.replace(/\\n{3,}/g, '\\n\\n').trim()\n/** `after` is `before` with a leading part removed (a prefix cut, never a cut in the middle). */\nconst isPrefixCut = (before: string, after: string): boolean =>\n before.trimEnd().endsWith(after.trim())\n/** Nothing structural was lost: headings and numbered items are all still there. */\nconst keepsStructure = (candidate: string, reference: string): boolean =>\n countMatches(candidate, LIST_NUMBER) >= countMatches(reference, LIST_NUMBER) &&\n countMatches(candidate, HEADING_LINE) >= countMatches(reference, HEADING_LINE)\n\n/** The three text steps of the cleanup; replaceable so the guard can be tested. */\nexport interface DraftCleanSteps {\n unwrap: (text: string) => string\n strip: (text: string) => string\n promote: (text: string) => string\n}\nconst DEFAULT_CLEAN_STEPS: DraftCleanSteps = {\n unwrap: unwrapCitationLinks,\n strip: stripAgentPreamble,\n promote: promoteBoldTitle,\n}\n\n/**\n * `cleanDraftMarkdown` with a safety net and a report, for storing a streamed draft. Each stage is\n * accepted only if it provably cost nothing but narration and citation markup:\n * - links removed: at least 70% of the text length remains and no heading or numbered item is lost\n * (else `raw`, the input exactly as streamed);\n * - narration removed: only a pure prefix of the text may go, and nothing structural;\n * - title and heading tidy: at least 70% of the text remains and no heading or numbered item is lost.\n * A rejected stage falls back to the previous one (`cleaned` -> `unwrapped` -> `raw`).\n */\nexport function cleanDraftWithReport(\n raw: string,\n steps: DraftCleanSteps = DEFAULT_CLEAN_STEPS\n): DraftCleanReport {\n const floor = withoutCitationMarkup(raw)\n const ratio = (t: string): number => (floor.length ? t.length / floor.length : 1)\n const unwrapped = tidy(steps.unwrap(raw))\n const stripped = tidy(steps.strip(unwrapped))\n const titled = tidy(cleanHeadings(steps.promote(stripped)))\n const changedBy: DraftCleanReport['changedBy'] = []\n if (unwrapped !== raw.trim()) changedBy.push('citations')\n if (stripped !== unwrapped) changedBy.push('preamble')\n if (titled !== stripped) changedBy.push('title')\n\n const unwrappedOk = unwrapped.length >= MIN_RATIO * floor.length && keepsStructure(unwrapped, raw)\n if (!unwrappedOk) return { text: raw, stage: 'raw', ratio: 1, changedBy, guarded: true }\n const strippedOk =\n stripped === unwrapped ||\n (isPrefixCut(unwrapped, stripped) && keepsStructure(stripped, unwrapped))\n const titledOk = titled.length >= MIN_RATIO * stripped.length && keepsStructure(titled, stripped)\n if (strippedOk && titledOk) {\n return { text: titled, stage: 'cleaned', ratio: ratio(titled), changedBy, guarded: false }\n }\n return { text: unwrapped, stage: 'unwrapped', ratio: ratio(unwrapped), changedBy, guarded: true }\n}\n\n/**\n * Everything a streamed draft needs before it is stored as the artifact's first version:\n * `unwrapCitationLinks`, `stripAgentPreamble`, `promoteBoldTitle`, clean headings, collapsed blank\n * runs, trimmed, under the guard of `cleanDraftWithReport` (use it to know which stage was kept).\n */\nexport function cleanDraftMarkdown(raw: string): string {\n return cleanDraftWithReport(raw).text\n}\n","/**\n * Versions of a document. A document keeps ONE id for its whole life; its versions live inside it\n * (`current_version` + `versions`, numbered 1..n). A version is named by a version reference\n * `doc-…@v{n}`; a plain document id means its current version. The workspace list carries every\n * document's `versions`, and `GET /v1/document/{id}/versions` (`arbi.documents.versions`) the same\n * list on its own.\n */\n\nimport { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\nimport { normalizeMarkdown } from './normalize-markdown'\n\n/** One version entry as the API returns it (a subset of `DocVersion`). */\nexport interface DocVersionEntry {\n n: number\n file_name?: string | null\n created_at?: string | null\n reason?: string | null\n /** The version an edit started from, when it was not the previous one. */\n made_from?: number | null\n is_current?: boolean | null\n /** The assistant message whose turn made this version, and its thread (none: a person's). */\n source_message_ext_id?: string | null\n conversation_ext_id?: string | null\n}\n\n/** The fields of a workspace document the version list needs (a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n current_version?: number | null\n versions?: readonly DocVersionEntry[] | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n /** The version reference `doc-…@v{n}`: what opening or comparing this version names. */\n id: string\n /** The document (the same for every version). */\n docId: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** 1-based version number within the document. */\n number: number\n /** upload | edit | signed | sync */\n reason: string\n isCurrent: boolean\n /** The version this one was saved from (an older one than the previous version when restored). */\n savedFromId?: string | null\n /** The thread (and its message) whose turn made this version; none for a person's. */\n thread?: { conversationId: string; messageId: string | null } | null\n}\n\nconst VERSION_REF = /^(doc-[A-Za-z0-9]+)@v([1-9][0-9]*)$/\n\n/** `doc-…@v{n}`: a reference to version `n` of a document. */\nexport function versionRef(docId: string, version: number): string {\n return `${docId}@v${version}`\n}\n\n/**\n * Split a reference into the document and the version it names. A plain document id (or anything\n * else) names no version: the document's current one.\n */\nexport function parseVersionRef(ref: string | null | undefined): {\n docId: string\n version: number | null\n} {\n const match = VERSION_REF.exec(ref ?? '')\n if (!match) return { docId: ref ?? '', version: null }\n return { docId: match[1], version: Number(match[2]) }\n}\n\n/** The version a version was saved from: `made_from`, else the one before it. */\nexport function savedFromId(docId: string, entry: DocVersionEntry): string | null {\n if (entry.made_from) return versionRef(docId, entry.made_from)\n return entry.n > 1 ? versionRef(docId, entry.n - 1) : null\n}\n\n/** A document's version entries (oldest first) as plain version rows. */\nexport function toArtifactVersions(\n docId: string | null | undefined,\n entries: readonly DocVersionEntry[] | null | undefined,\n currentVersion?: number | null\n): ArtifactVersion[] {\n if (!docId) return []\n const current = currentVersion ?? entries?.find((e) => e.is_current)?.n ?? null\n return [...(entries ?? [])]\n .sort((a, b) => a.n - b.n)\n .map((e) => ({\n id: versionRef(docId, e.n),\n docId,\n name: e.file_name ?? '',\n createdAt: e.created_at ?? '',\n number: e.n,\n reason: e.reason ?? 'upload',\n isCurrent: current != null ? e.n === current : !!e.is_current,\n savedFromId: savedFromId(docId, e),\n thread: e.conversation_ext_id\n ? { conversationId: e.conversation_ext_id, messageId: e.source_message_ext_id ?? null }\n : null,\n }))\n}\n\n/** The versions of a listed document, oldest first (`[]` when the document is not given). */\nexport function documentVersions(doc: VersionedDoc | null | undefined): ArtifactVersion[] {\n if (!doc?.external_id) return []\n const entries = doc.versions?.length\n ? doc.versions\n : [{ n: doc.current_version ?? 1, file_name: doc.file_name, created_at: doc.created_at }]\n return toArtifactVersions(doc.external_id, entries, doc.current_version ?? null)\n}\n\n/** The row `ref` names: an exact version, or (a plain document id) the current version. */\nexport function findVersion(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): ArtifactVersion | undefined {\n if (!ref) return undefined\n const { docId, version } = parseVersionRef(ref)\n return version == null\n ? versions.find((v) => v.docId === docId && v.isCurrent)\n : versions.find((v) => v.docId === docId && v.number === version)\n}\n\n/**\n * \"v2\": the version number `ref` names. `null` when there is nothing to tell apart (the document\n * has a single version, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): string | null {\n if (!ref || versions.length <= 1) return null\n const version = findVersion(versions, ref)\n return version ? `v${version.number}` : null\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`, `repairParsedStructure`: doubled headings, `- ` stacked on list markers,\n * one-line tables), then normalised. Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n if (!options?.unescape) return text\n // Canonical spelling last, so the text an editor starts from is what a save would persist.\n return normalizeMarkdown(\n repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))\n ).replace(/\\n$/, '')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n"]}
1
+ {"version":3,"sources":["../src/ai/stored-markdown.ts","../src/artifacts/versions.ts"],"names":["normalizeCitationMarkup","normalizeMarkdown"],"mappings":";;;;;;AAgBA,IAAM,KAAA,GAAQ,eAAA;AAGd,SAAS,gBAAA,CAAiB,MAAc,EAAA,EAAsC;AAC5E,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,OAAO,KACJ,KAAA,CAAM,IAAI,CAAA,CACV,GAAA,CAAI,CAAC,IAAA,KAAS;AACb,IAAA,IAAI,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG;AACpB,MAAA,OAAA,GAAU,CAAC,OAAA;AACX,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAA,GAAU,IAAA,GAAO,EAAA,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C,CAAA,KAAA,CAAO,CAAA,CAAE,OAAA,IAAW,EAAA,EAAI,IAAA,EAAM,CAAA,CAAE,KAAK,MAAM,CAAA;AAC5E,EAAA,IAAI,CAAC,OAAA,EAAS,QAAA,EAAU,OAAO,IAAA;AAE/B,EAAA,OAAOC,mCAAA;AAAA,IACL,qBAAA,CAAsB,iBAAA,CAAkB,gBAAA,CAAiB,IAAI,CAAC,CAAC;AAAA,GACjE,CAAE,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACrB;AAGA,IAAM,MAAA,GAAS,MAAA;AAGR,SAAS,aAAa,EAAA,EAA6C;AACxE,EAAA,OAAO,CAAC,CAAC,EAAA,IAAM,MAAA,CAAO,KAAK,EAAE,CAAA;AAC/B","file":"chunk-7C77IBQZ.cjs","sourcesContent":["/**\n * Helpers for markdown that is STORED (an agent's draft saved as an artifact, then read back from\n * the backend's parse). Pure and SDK-free; they sit next to `normalizeCitationMarkup`, which they\n * build on.\n *\n * Two directions:\n *\n * - Going in (`cleanDraftMarkdown` = `unwrapCitationLinks` + `stripAgentPreamble` +\n * `promoteBoldTitle`): a streamed draft carries citation links, `(*Source: ...*)` notes and\n * sometimes narration before the document. A stored letter should hold only the letter.\n * - Coming out (`unescapeMarkdown`): the backend's parse of a stored `.md` returns the text with\n * markdown punctuation backslash-escaped (`**Fees.**` comes back as `\\*\\*Fees\\.\\*\\*`).\n */\n\nimport { normalizeCitationMarkup } from './normalize-citations'\n\nconst FENCE = /^\\s*(```|~~~)/\n\n/** Run `fn` on every line outside a fenced code block. */\nfunction mapOutsideFences(text: string, fn: (line: string) => string): string {\n let inFence = false\n return text\n .split('\\n')\n .map((line) => {\n if (FENCE.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : fn(line)\n })\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Coming out: undo the parser's escaping\n// ---------------------------------------------------------------------------------------------\n\n/** A backslash followed by markdown punctuation: the only thing the parser's escaping produces. */\nconst ESCAPED_PUNCTUATION = /\\\\([\\\\`*_{}[\\]()#+\\-.!|>~<])/g\n/** The only escapes the parser puts inside an inline code span. */\nconst ESCAPED_EMPHASIS = /\\\\([*_])/g\nconst INLINE_CODE = /(`+)(?!`)(.+?)(?<!`)\\1(?!`)/g\n\n/**\n * Undo the backend's escaping of a markdown artifact: `\\*\\*Scope\\.\\*\\*` becomes `**Scope.**`.\n *\n * THE RULE. Apply this ONLY to text of an artifact that was stored from markdown (an agent draft\n * or an edited version, always uploaded as `.md`): for those the parser escapes every markdown\n * punctuation character, including the backslash itself, so removing one level of escaping is the\n * exact inverse (an author's literal `\\*` is stored as `\\\\\\*` and comes back as `\\*`). Do not\n * apply it to a PDF or Word parse, where a backslash is just a character.\n *\n * Details:\n * - Only a backslash followed by markdown punctuation (``\\ ` * _ { } [ ] ( ) # + - . ! | > ~ <``)\n * is removed; `\\n`, `C:\\temp` and a trailing backslash are left alone.\n * - Pairs are read left to right, so `\\\\*` is an escaped backslash followed by a bare `*`.\n * - Fenced code blocks are never touched (the parser does not escape inside them).\n * - Inline code spans: the parser DOES escape `*` and `_` there (`` `a*b` `` comes back as\n * `` `a\\*b` ``), so only `\\*` and `\\_` are undone inside a span; any other backslash in code\n * (`` `re\\.x` ``) is a literal and stays.\n */\nexport function unescapeMarkdown(text: string): string {\n if (!text.includes('\\\\')) return text\n return mapOutsideFences(text, (line) => {\n if (!line.includes('\\\\')) return line\n let out = ''\n let last = 0\n for (const span of line.matchAll(INLINE_CODE)) {\n const at = span.index ?? 0\n out +=\n line.slice(last, at).replace(ESCAPED_PUNCTUATION, '$1') +\n span[0].replace(ESCAPED_EMPHASIS, '$1')\n last = at + span[0].length\n }\n return out + line.slice(last).replace(ESCAPED_PUNCTUATION, '$1')\n })\n}\n\n/**\n * The parser also mangles the TITLE of a stored markdown document (seen on a real backend): the\n * first heading comes back doubled (`## # Title`) or alone inside a code fence\n * (a fence, `# Title`, a fence). Both are repaired, on the first non-blank line only, so a code\n * block or heading later in the text is never touched. Like `unescapeMarkdown`, apply it only to\n * artifacts stored from markdown.\n */\nexport function repairParsedTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const doubled = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/.exec(lines[first])\n if (doubled) {\n lines[first] = doubled[1]\n return lines.join('\\n')\n }\n if (/^\\s*```\\s*$/.test(lines[first]) && /^#{1,6}\\s+\\S/.test(lines[first + 1] ?? '')) {\n if (/^\\s*```\\s*$/.test(lines[first + 2] ?? '')) lines.splice(first + 2, 1)\n else return text\n lines.splice(first, 1)\n return lines.join('\\n')\n }\n return text\n}\n\nconst DOUBLED_HEADING = /^#{1,6}\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_HEADING = /^[-*+]\\s+(#{1,6}\\s+\\S.*)$/\nconst LIST_IN_LIST = /^[-*+]\\s+[-*+]\\s+(\\S.*)$/\nconst LIST_ORDINAL = /^[-*+]\\s+(\\d{1,9})([.)])\\s+(\\S.*)$/\nconst LIST_ITEM_LINE = /^\\s*(?:[-*+]|\\d{1,9}[.)])\\s/\nconst TABLE_DELIMITER_CELL = /^:?-{1,}:?$/\n\n/** `1. a 2. b 3. c` (one line) split where the next ordinal follows: `['1. a', '2. b', '3. c']`. */\nfunction splitRunOfOrdinals(first: number, delimiter: string, rest: string): string[] {\n const items: string[] = []\n let n = first\n let remaining = rest\n for (;;) {\n const next = new RegExp(`^(.+?)\\\\s+${n + 1}\\\\${delimiter}\\\\s+(\\\\S.*)$`).exec(remaining)\n if (!next) break\n items.push(`${n}${delimiter} ${next[1]}`)\n n += 1\n remaining = next[2]\n }\n items.push(`${n}${delimiter} ${remaining}`)\n return items\n}\n\n/**\n * A table the parser put on ONE line (`| h | h | |---|---| | a | b |`, rows joined by a space, which\n * leaves one empty cell between rows) back as a pipe table. `null` when the line is not that shape.\n */\nfunction rebuildFlatTable(line: string): string[] | null {\n const trimmed = line.trim()\n if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) return null\n const cells = trimmed\n .slice(1, -1)\n .split('|')\n .map((c) => c.trim())\n const firstRule = cells.findIndex((c) => TABLE_DELIMITER_CELL.test(c))\n if (firstRule < 2 || cells[firstRule - 1] !== '') return null\n const columns = firstRule - 1\n const rows: string[][] = []\n for (let at = 0; at < cells.length; at += columns + 1) {\n const row = cells.slice(at, at + columns)\n const gap = cells[at + columns]\n if (row.length !== columns || (gap !== undefined && gap !== '')) return null\n rows.push(row)\n }\n const [header, rule, ...body] = rows\n if (!rule.every((c) => TABLE_DELIMITER_CELL.test(c))) return null\n const fmt = (row: string[]): string => `| ${row.join(' | ')} |`\n return [fmt(header), fmt(rule.map(() => '---')), ...body.map(fmt)]\n}\n\n/**\n * Undo how the backend's parse of a stored `.md` restructures it (seen on a real backend):\n * - a heading comes back doubled (`## # Title`) or as a list item (`- # Title`);\n * - every list item gets a `- ` of its own on top of the original marker, so `* a` returns as\n * `- * a` and `1. a` as `- 1. a`, which a markdown editor loads as a list inside a list item\n * (and saves as `- - a`); a run of ordinals can come back on one line (`- 1. a 2. b`);\n * - a table comes back on one line.\n * List nesting and the bullet/ordered difference of a flat `- x` cannot be recovered, so items\n * stay flat. Items of one list are kept tight (no blank line between them). Fenced code is\n * never touched. Like `unescapeMarkdown`, apply it only to artifacts stored from markdown.\n */\nexport function repairParsedStructure(text: string): string {\n const out: string[] = []\n let inFence = false\n for (const line of text.split('\\n')) {\n if (FENCE.test(line)) {\n inFence = !inFence\n out.push(line)\n continue\n }\n if (inFence) {\n out.push(line)\n continue\n }\n const table = rebuildFlatTable(line)\n if (table) {\n out.push(...table)\n continue\n }\n const heading = DOUBLED_HEADING.exec(line) ?? LIST_HEADING.exec(line)\n if (heading) {\n out.push(heading[1])\n continue\n }\n const ordinal = LIST_ORDINAL.exec(line)\n if (ordinal) {\n out.push(...splitRunOfOrdinals(Number(ordinal[1]), ordinal[2], ordinal[3]))\n continue\n }\n const nested = LIST_IN_LIST.exec(line)\n out.push(nested ? `- ${nested[1]}` : line)\n }\n // Items parsed as separate chunks arrive one blank line apart: that is one tight list.\n return out\n .filter(\n (line, i) =>\n !(\n line === '' &&\n LIST_ITEM_LINE.test(out[i - 1] ?? '') &&\n LIST_ITEM_LINE.test(out[i + 1] ?? '')\n )\n )\n .join('\\n')\n}\n\n// ---------------------------------------------------------------------------------------------\n// Going in: clean a streamed draft before it is stored\n// ---------------------------------------------------------------------------------------------\n\n/** `(*Source: Terms.pdf*)`, `(Sources: a, b)` and the italic form `*(Source: ...)*`. */\nconst SOURCE_NOTE =\n /[ \\t]*(?:\\*+\\(\\s*Sources?\\s*:[^)\\n]*\\)\\*+|\\(\\s*\\*{0,2}\\s*Sources?\\s*:[^)\\n]*\\))/gi\nconst CITE_TOKEN = /^\\]\\(#cite-[\\w-]+\\)/\n\n/**\n * Remove the citation links of ONE line and keep every word. A link is `[text](#cite-N)`, but the\n * model also writes brackets inside the text (`[We act for [PLACEHOLDER].](#cite-1)`) and links that\n * overlap other brackets, so a regex cannot find the opening bracket. This scans the line with a\n * stack of `[`: a `](#cite-N)` takes the nearest open `[` with it (both are removed, the text\n * between stays); a plain `]` closes the nearest `[`; a `](#cite-N)` with no open `[` loses only\n * the marker. Brackets that are not part of a link are never touched.\n */\nfunction removeCitationLinks(line: string): string {\n if (!line.includes('](#cite-')) return line\n const drop = new Set<number>()\n const open: number[] = []\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === '[') open.push(i)\n else if (c === ']') {\n const token = CITE_TOKEN.exec(line.slice(i, i + 40))\n if (token) {\n const opener = open.pop()\n if (opener !== undefined) drop.add(opener)\n for (let k = i; k < i + token[0].length; k++) drop.add(k)\n i += token[0].length - 1\n } else open.pop()\n }\n }\n let out = ''\n for (let i = 0; i < line.length; i++) if (!drop.has(i)) out += line[i]\n return out\n}\n\n/** A line whose `**` do not pair up (one half was wrapped into a link) loses the stray marks. */\nfunction balanceBold(line: string): string {\n // A bold-wrapped heading (`**# Title**`) is just a heading.\n if (/^\\s*\\*\\*#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '').trim()\n if ((line.match(/\\*\\*/g)?.length ?? 0) % 2 === 0) return line\n if (/^#{1,6}\\s/.test(line)) return line.replace(/\\*\\*/g, '')\n return line.replace(/\\*\\*\\s*$/, '').replace(/^(\\s*(?:[-*]\\s+)?)\\*\\*(?=\\s)/, '$1')\n}\n\n/**\n * Text for storage from text that carries citations: `normalizeCitationMarkup` first (it hoists\n * list, heading and bold tokens out of the link so unwrapping cannot orphan half of a `**` pair),\n * then `[text](#cite-N)` becomes `text`, `(*Source: ...*)` notes are dropped, and a bold or\n * heading marker that lost its partner is repaired. Fenced code is left alone.\n */\nexport function unwrapCitationLinks(text: string): string {\n const withoutNotes = mapOutsideFences(text, (line) => line.replace(SOURCE_NOTE, ''))\n return mapOutsideFences(normalizeCitationMarkup(withoutNotes), (line) => {\n const unlinked = removeCitationLinks(line)\n return unlinked === line ? line : balanceBold(unlinked)\n })\n}\n\nconst HEADING = /^#{1,6}\\s+\\S/\nconst HR_ONLY = /^\\s*(?:-{3,}|\\*{3,}|_{3,})\\s*$/\n/** A whole-line bold title: `**Client Engagement Letter**`. */\nconst BOLD_LINE = /^\\*\\*[^*#].*\\*\\*$/\nconst MAX_PREAMBLE_CHARS = 900\nconst MAX_PREAMBLE_PARAGRAPHS = 4\nconst MAX_TITLE_CHARS = 100\n\n/**\n * How a paragraph of agent narration opens. An ALLOW-LIST: a paragraph that opens any other way is\n * treated as document text and never removed.\n */\nconst NARRATION_OPENER =\n /^(?:I(?:['’](?:ll|ve|m|d))?\\s|let me\\b|here(?:['’]s| is| are)\\b|below is\\b|sure[,.! ]|certainly[,.! ]|of course[,.! ]|okay[,.! ]|based on (?:the|your|my)\\b|per the (?:user|instructions?)|as requested\\b|the workspace\\b|no (?:relevant |workspace |matching )?documents?\\b|there (?:are|is) no (?:relevant |workspace )?documents?\\b|after (?:reviewing|reading|searching)\\b)/i\n\n/** Structure a covering note would not have: lists, tables, quotes, code, headings, bold, links. */\nconst STRUCTURED = /^\\s*(?:[-*+>|]|\\d{1,9}[.)]\\s|#{1,6}\\s|```|~~~)|\\*\\*|\\]\\(/m\n\n/**\n * Cut the agent's narration written BEFORE the document. Strictly non-destructive: if in doubt the\n * text is returned whole (a stray sentence is easy to delete, a lost clause is not recoverable).\n *\n * Text is removed only when ALL of these hold:\n * 1. a real markdown heading line (`# Title`, any level) follows it, and the cut stops exactly at\n * the FIRST such line (never at a bold line, never at a line that merely contains `**`);\n * 2. what precedes it is at most 4 paragraphs and 900 characters of plain prose (horizontal rules\n * between them are ignored): no list, table, quote, code, heading, bold or link;\n * 3. EVERY paragraph opens with an allow-listed narration opener: first person (\"I'll ...\",\n * \"I now have ...\"), \"Let me\", \"Here is/are\", \"Below is\", \"Sure\", \"Based on the ...\", \"Per the\n * instructions\", \"As requested\", \"The workspace ...\", \"No (relevant) documents ...\", \"There is\n * no document ...\", \"After reviewing ...\".\n * Anything else (a dateline, an address, a salutation, a sentence of the letter) keeps the text whole.\n */\nexport function stripAgentPreamble(text: string): string {\n const lines = text.split('\\n')\n const start = lines.findIndex((l) => HEADING.test(l))\n if (start <= 0) return text\n const before = lines\n .slice(0, start)\n .filter((l) => !HR_ONLY.test(l))\n .join('\\n')\n .trim()\n if (!before) return lines.slice(start).join('\\n')\n const paragraphs = before.split(/\\n\\s*\\n/).map((p) => p.trim())\n const narration =\n before.length <= MAX_PREAMBLE_CHARS &&\n paragraphs.length <= MAX_PREAMBLE_PARAGRAPHS &&\n !STRUCTURED.test(before) &&\n paragraphs.every((p) => NARRATION_OPENER.test(p))\n return narration ? lines.slice(start).join('\\n') : text\n}\n\n/**\n * Make the document's title a real heading: the FIRST non-blank line of the text, when it is a\n * short whole-line bold title (`**Letter**`, even with a stray inner `**`), becomes `# Letter`.\n * Nothing else is ever promoted: not a later line, not a mid-sentence fragment (the title must\n * start with a capital or digit, be at most 100 characters, hold no sentence break and not end in\n * `,` `;` or `:`), and a document that already opens with a heading is left alone.\n */\nexport function promoteBoldTitle(text: string): string {\n const lines = text.split('\\n')\n const first = lines.findIndex((l) => l.trim())\n if (first < 0) return text\n const line = lines[first].trim()\n if (!BOLD_LINE.test(line)) return text\n const title = line.replace(/\\*\\*/g, '').trim()\n if (\n title.length === 0 ||\n title.length > MAX_TITLE_CHARS ||\n !/^[\\p{Lu}\\d]/u.test(title) ||\n /[,;:]$/.test(title) ||\n /[.!?]\\s+\\S/.test(title)\n ) {\n return text\n }\n lines[first] = `# ${title}`\n return lines.join('\\n')\n}\n\n/** Tidy headings only: strip stray bold marks from heading lines (`# **Title**`). */\nfunction cleanHeadings(text: string): string {\n return mapOutsideFences(text, (line) =>\n /^\\s*#{1,6}\\s/.test(line) ? line.replace(/\\*\\*/g, '').trim() : line\n )\n}\n\n/** Which stage of the cleanup produced the text that is returned. */\nexport type DraftCleanStage = 'cleaned' | 'unwrapped' | 'raw'\n\nexport interface DraftCleanReport {\n /** What to store. */\n text: string\n /**\n * `cleaned`: the full cleanup. `unwrapped`: only the citation links were removed (the preamble or\n * title step was rejected by the guard). `raw`: the input as streamed (even link removal was\n * rejected).\n */\n stage: DraftCleanStage\n /** Length of the returned text over the length of the input without its citation markup. */\n ratio: number\n /** Which steps changed the text before the guard (for logs). */\n changedBy: ('citations' | 'preamble' | 'title')[]\n /** The guard rejected a step because it would have lost content. */\n guarded: boolean\n}\n\nconst MIN_RATIO = 0.7\nconst countMatches = (text: string, re: RegExp): number => text.match(re)?.length ?? 0\nconst LIST_NUMBER = /^\\s*\\d{1,9}[.)]\\s/gm\nconst HEADING_LINE = /^#{1,6}\\s/gm\n/** The text with only its citation markup gone: the floor no cleanup may go far under. */\nconst withoutCitationMarkup = (raw: string): string =>\n mapOutsideFences(raw.replace(SOURCE_NOTE, ''), removeCitationLinks).trim()\nconst tidy = (text: string): string => text.replace(/\\n{3,}/g, '\\n\\n').trim()\n/** `after` is `before` with a leading part removed (a prefix cut, never a cut in the middle). */\nconst isPrefixCut = (before: string, after: string): boolean =>\n before.trimEnd().endsWith(after.trim())\n/** Nothing structural was lost: headings and numbered items are all still there. */\nconst keepsStructure = (candidate: string, reference: string): boolean =>\n countMatches(candidate, LIST_NUMBER) >= countMatches(reference, LIST_NUMBER) &&\n countMatches(candidate, HEADING_LINE) >= countMatches(reference, HEADING_LINE)\n\n/** The three text steps of the cleanup; replaceable so the guard can be tested. */\nexport interface DraftCleanSteps {\n unwrap: (text: string) => string\n strip: (text: string) => string\n promote: (text: string) => string\n}\nconst DEFAULT_CLEAN_STEPS: DraftCleanSteps = {\n unwrap: unwrapCitationLinks,\n strip: stripAgentPreamble,\n promote: promoteBoldTitle,\n}\n\n/**\n * `cleanDraftMarkdown` with a safety net and a report, for storing a streamed draft. Each stage is\n * accepted only if it provably cost nothing but narration and citation markup:\n * - links removed: at least 70% of the text length remains and no heading or numbered item is lost\n * (else `raw`, the input exactly as streamed);\n * - narration removed: only a pure prefix of the text may go, and nothing structural;\n * - title and heading tidy: at least 70% of the text remains and no heading or numbered item is lost.\n * A rejected stage falls back to the previous one (`cleaned` -> `unwrapped` -> `raw`).\n */\nexport function cleanDraftWithReport(\n raw: string,\n steps: DraftCleanSteps = DEFAULT_CLEAN_STEPS\n): DraftCleanReport {\n const floor = withoutCitationMarkup(raw)\n const ratio = (t: string): number => (floor.length ? t.length / floor.length : 1)\n const unwrapped = tidy(steps.unwrap(raw))\n const stripped = tidy(steps.strip(unwrapped))\n const titled = tidy(cleanHeadings(steps.promote(stripped)))\n const changedBy: DraftCleanReport['changedBy'] = []\n if (unwrapped !== raw.trim()) changedBy.push('citations')\n if (stripped !== unwrapped) changedBy.push('preamble')\n if (titled !== stripped) changedBy.push('title')\n\n const unwrappedOk = unwrapped.length >= MIN_RATIO * floor.length && keepsStructure(unwrapped, raw)\n if (!unwrappedOk) return { text: raw, stage: 'raw', ratio: 1, changedBy, guarded: true }\n const strippedOk =\n stripped === unwrapped ||\n (isPrefixCut(unwrapped, stripped) && keepsStructure(stripped, unwrapped))\n const titledOk = titled.length >= MIN_RATIO * stripped.length && keepsStructure(titled, stripped)\n if (strippedOk && titledOk) {\n return { text: titled, stage: 'cleaned', ratio: ratio(titled), changedBy, guarded: false }\n }\n return { text: unwrapped, stage: 'unwrapped', ratio: ratio(unwrapped), changedBy, guarded: true }\n}\n\n/**\n * Everything a streamed draft needs before it is stored as the artifact's first version:\n * `unwrapCitationLinks`, `stripAgentPreamble`, `promoteBoldTitle`, clean headings, collapsed blank\n * runs, trimmed, under the guard of `cleanDraftWithReport` (use it to know which stage was kept).\n */\nexport function cleanDraftMarkdown(raw: string): string {\n return cleanDraftWithReport(raw).text\n}\n","/**\n * Versions of a document. A document keeps ONE id for its whole life; its versions live inside it\n * (`current_version` + `versions`, numbered 1..n). A version is named by a version reference\n * `doc-…@v{n}`; a plain document id means its current version. The workspace list carries every\n * document's `versions`, and `GET /v1/document/{id}/versions` (`arbi.documents.versions`) the same\n * list on its own.\n */\n\nimport { repairParsedStructure, repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\nimport { normalizeMarkdown } from './normalize-markdown'\n\n/** One version entry as the API returns it (a subset of `DocVersion`). */\nexport interface DocVersionEntry {\n n: number\n file_name?: string | null\n created_at?: string | null\n reason?: string | null\n /** The version an edit started from, when it was not the previous one. */\n made_from?: number | null\n is_current?: boolean | null\n /** The assistant message whose turn made this version, and its thread (none: a person's). */\n source_message_ext_id?: string | null\n conversation_ext_id?: string | null\n}\n\n/** The fields of a workspace document the version list needs (a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n current_version?: number | null\n versions?: readonly DocVersionEntry[] | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n /** The version reference `doc-…@v{n}`: what opening or comparing this version names. */\n id: string\n /** The document (the same for every version). */\n docId: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** 1-based version number within the document. */\n number: number\n /** upload | edit | signed | sync */\n reason: string\n isCurrent: boolean\n /** The version this one was saved from (an older one than the previous version when restored). */\n savedFromId?: string | null\n /** The thread (and its message) whose turn made this version; none for a person's. */\n thread?: { conversationId: string; messageId: string | null } | null\n}\n\nconst VERSION_REF = /^(doc-[A-Za-z0-9]+)@v([1-9][0-9]*)$/\n\n/** `doc-…@v{n}`: a reference to version `n` of a document. */\nexport function versionRef(docId: string, version: number): string {\n return `${docId}@v${version}`\n}\n\n/**\n * Split a reference into the document and the version it names. A plain document id (or anything\n * else) names no version: the document's current one.\n */\nexport function parseVersionRef(ref: string | null | undefined): {\n docId: string\n version: number | null\n} {\n const match = VERSION_REF.exec(ref ?? '')\n if (!match) return { docId: ref ?? '', version: null }\n return { docId: match[1], version: Number(match[2]) }\n}\n\n/** The version a version was saved from: `made_from`, else the one before it. */\nexport function savedFromId(docId: string, entry: DocVersionEntry): string | null {\n if (entry.made_from) return versionRef(docId, entry.made_from)\n return entry.n > 1 ? versionRef(docId, entry.n - 1) : null\n}\n\n/** A document's version entries (oldest first) as plain version rows. */\nexport function toArtifactVersions(\n docId: string | null | undefined,\n entries: readonly DocVersionEntry[] | null | undefined,\n currentVersion?: number | null\n): ArtifactVersion[] {\n if (!docId) return []\n const current = currentVersion ?? entries?.find((e) => e.is_current)?.n ?? null\n return [...(entries ?? [])]\n .sort((a, b) => a.n - b.n)\n .map((e) => ({\n id: versionRef(docId, e.n),\n docId,\n name: e.file_name ?? '',\n createdAt: e.created_at ?? '',\n number: e.n,\n reason: e.reason ?? 'upload',\n isCurrent: current != null ? e.n === current : !!e.is_current,\n savedFromId: savedFromId(docId, e),\n thread: e.conversation_ext_id\n ? { conversationId: e.conversation_ext_id, messageId: e.source_message_ext_id ?? null }\n : null,\n }))\n}\n\n/** The versions of a listed document, oldest first (`[]` when the document is not given). */\nexport function documentVersions(doc: VersionedDoc | null | undefined): ArtifactVersion[] {\n if (!doc?.external_id) return []\n const entries = doc.versions?.length\n ? doc.versions\n : [{ n: doc.current_version ?? 1, file_name: doc.file_name, created_at: doc.created_at }]\n return toArtifactVersions(doc.external_id, entries, doc.current_version ?? null)\n}\n\n/** The row `ref` names: an exact version, or (a plain document id) the current version. */\nexport function findVersion(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): ArtifactVersion | undefined {\n if (!ref) return undefined\n const { docId, version } = parseVersionRef(ref)\n return version == null\n ? versions.find((v) => v.docId === docId && v.isCurrent)\n : versions.find((v) => v.docId === docId && v.number === version)\n}\n\n/**\n * \"v2\": the version number `ref` names. `null` when there is nothing to tell apart (the document\n * has a single version, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n ref: string | null | undefined\n): string | null {\n if (!ref || versions.length <= 1) return null\n const version = findVersion(versions, ref)\n return version ? `v${version.number}` : null\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`, `repairParsedStructure`: doubled headings, `- ` stacked on list markers,\n * one-line tables), then normalised. Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n if (!options?.unescape) return text\n // Canonical spelling last, so the text an editor starts from is what a save would persist.\n return normalizeMarkdown(\n repairParsedStructure(repairParsedTitle(unescapeMarkdown(text)))\n ).replace(/\\n$/, '')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n"]}
@@ -1,8 +1,8 @@
1
+ import { ScrollArea, formatRelativeTime, configureEntityVocabulary } from './chunk-Y3MTRA7D.js';
1
2
  import { useNotify, selectUnread, DEFAULT_NOTIFY_TONE } from './chunk-BF5KW5ZI.js';
2
3
  import { mergeHostConfig, OWN_SESSION_SLOT } from './chunk-DPYBZDJB.js';
3
- import { parseVersionRef } from './chunk-UW2SGTI5.js';
4
- import { ScrollArea, formatRelativeTime, configureEntityVocabulary } from './chunk-Y3MTRA7D.js';
5
4
  import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from './chunk-47CCGUWR.js';
5
+ import { parseVersionRef } from './chunk-GR7CZEJJ.js';
6
6
  import { ArbiHostContext, useHostConfigRecord } from './chunk-VSCU7K4V.js';
7
7
  import { cn } from './chunk-SN5YV6FF.js';
8
8
  import { createStore } from 'zustand/vanilla';
@@ -555,5 +555,5 @@ function forgetLegacyThreadDocuments(conversationIds) {
555
555
  }
556
556
 
557
557
  export { ArbiHost, DEFAULT_ASSISTANT_NAME, LEGACY_THREAD_DOCUMENTS_KEY, MENTION_HREF_PREFIX, NotificationBell, Toaster, UNBOUND, assistantCopy, bindingOfRow, clearSearchSession, createSearchSession, extractMentions, filterMentionCandidates, findMentionQuery, forgetLegacyThreadDocuments, hasMessageBody, insertMention, latestThreadOfDocument, linkMentions, mentionFromHref, openDocumentId, opensInWord, persistSearchSession, readLegacyThreadDocuments, requestSearch, savedDocumentIdFor, sharedSearchSession, takeDocumentForTurn, takePendingSearch, toMessageMentions, useAssistantCopy, useAssistantName, useOpenDocumentId, useRegisterOpenDocument, useTurnDocumentId };
558
- //# sourceMappingURL=chunk-OYPKKHXY.js.map
559
- //# sourceMappingURL=chunk-OYPKKHXY.js.map
558
+ //# sourceMappingURL=chunk-7KZS22EK.js.map
559
+ //# sourceMappingURL=chunk-7KZS22EK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/host/assistant-copy.ts","../src/chat/mentions.ts","../src/chat/open-document.ts","../src/chat/thread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,IAAI;AACF,IAAA,OAAO,OAAO,YAAA,KAAiB,WAAA,GAAc,KAAA,CAAA,GAAY,YAAA;AAAA,EAC3D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGO,SAAS,yBAAA,GAAoD;AAClE,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,OAAA,IAAW,OAAA,CAAQ,2BAA2B,KAAK,MAAM,CAAA;AACnF,IAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAA;AAC9B,MAAA,KAAA,MAAW,CAAC,cAAA,EAAgB,UAAU,CAAA,IAAK,MAAA,CAAO,QAAQ,MAAM,CAAA;AAC9D,QAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,GAAA,CAAI,cAAc,CAAA,GAAI,UAAA;AAAA,IAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,GAAA;AACT;AAGO,SAAS,4BAA4B,eAAA,EAA0C;AACpF,EAAA,IAAI,eAAA,CAAgB,WAAW,CAAA,EAAG;AAClC,EAAA,MAAM,OAAO,yBAAA,EAA0B;AACvC,EAAA,eAAA,CAAgB,QAAQ,CAAC,EAAA,KAAO,OAAO,IAAA,CAAK,EAAE,CAAC,CAAA;AAC/C,EAAA,IAAI;AACF,IAAA,IAAI,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG,OAAA,EAAQ,EAAG,UAAA,CAAW,2BAA2B,CAAA;AAAA,kBACxE,EAAG,OAAA,CAAQ,6BAA6B,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,EAC3E,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-OYPKKHXY.js","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg pointer-coarse:w-88\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {(n.onSelect || n.href) && (\n <span className=\"shrink-0 self-center rounded-md bg-primary/10 px-2 py-1 text-xs font-medium text-primary\">\n {n.actionLabel ?? 'Open'}\n </span>\n )}\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context, ./merge and the entity vocabulary are all it reaches), so a\n * marketing site that only sets the blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\nimport { configureEntityVocabulary, type EntityVocabulary } from '../entities/vocabulary'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n // The site's nouns are in place before any kit below renders a label.\n const { vocabulary } = config as { vocabulary?: EntityVocabulary }\n if (vocabulary) configureEntityVocabulary(vocabulary)\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * What the kits call the assistant in their own words, from the host's name for it\n * (`ArbiHostConfig.assistantName`, also what people @mention). One label source: every kit phrase\n * that names the assistant is here, written once around the name, so a custom site's name shows\n * everywhere and ARBI's own text is unchanged (\"ARBI\" when the host names it nothing else).\n *\n * const copy = useAssistantCopy()\n * <Button>{copy.ask}</Button> // \"Ask ARBI\", or \"Ask Acme Assistant\"\n *\n * SDK-free: exported from `@arbidocs/react/shell` too, for presentational parts.\n */\nimport { useMemo } from 'react'\n// The record, not `useArbiHost` (`./config` names the SDK's types): this module stays SDK-free.\nimport { useHostConfigRecord } from './context'\n\n/** The assistant's name when the host names it nothing else. */\nexport const DEFAULT_ASSISTANT_NAME = 'ARBI'\n\n/** Every kit phrase that names the assistant. */\nexport interface AssistantCopy {\n /** The name itself. */\n name: string\n /** \"Ask ARBI\": a button or tab that starts a question. */\n ask: string\n /** \"Ask ARBI anything\": an empty list's call to ask. */\n askAnything: string\n /** \"Ask ARBI anything…\": the chat composer's placeholder. */\n askAnythingPlaceholder: string\n /** \"Ask ARBI...\": a compact composer's placeholder. */\n askPlaceholder: string\n /** \"Ask ARBI about your documents\": the empty chat's heading. */\n askAboutDocuments: string\n /** The files bulk bar's chat tooltip. */\n askAboutSelection: string\n /** \"ARBI is asking\": the heading over a question the assistant asks. */\n isAsking: string\n /** The composer's placeholder while the assistant waits for an answer. */\n answerPlaceholder: string\n /** The empty threads list, with the composer below it. */\n emptyThreadsComposer: string\n /** The empty threads list, with a New Task button. */\n emptyThreadsNewTask: string\n /** The drafting chip's hint while the thread drafts in a document. */\n draftingHint: string\n /** The drafting chip's hint before the document is attached. */\n draftingAttachHint: string\n /** The chat's facts tab note. */\n factsInContext: (facts: string) => string\n /** \"Ask one question — ARBI answers it for each of …\": the AI review's ask step. */\n reviewEach: (count: number, scope: string) => string\n /** The facts bar's note on the chat's facts budget. */\n factsBudgetHint: string\n /** An AI review cell left without an answer. */\n noAnswerHint: string\n /** The new-thread dialog's button that hands the thread to the assistant. */\n startWith: string\n /** The mail action bar's \"Reply with ARBI\". */\n replyWith: string\n /** The Word editor's comment button that @mentions the assistant. */\n include: string\n /** A reply to an email asked for outside a workspace. */\n replyNeedsWorkspace: string\n /** After an upload. */\n uploadedIndexing: string\n /** Before an upload completes. */\n afterUpload: string\n /** The built-in Deep research workflow's description and details. */\n deepResearch: { description: string; details: string }\n /** The built-in AI annotation operation's details. */\n annotate: { details: string; placeholder: string }\n}\n\nconst plural = (n: number) => (n === 1 ? '' : 's')\n\n/** The phrases for one name. `assistantCopy()` is ARBI's own text. */\nexport function assistantCopy(name: string = DEFAULT_ASSISTANT_NAME): AssistantCopy {\n return {\n name,\n ask: `Ask ${name}`,\n askAnything: `Ask ${name} anything`,\n askAnythingPlaceholder: `Ask ${name} anything…`,\n askPlaceholder: `Ask ${name}...`,\n askAboutDocuments: `Ask ${name} about your documents`,\n askAboutSelection: `Ask ${name} about the selected document(s) in a new thread`,\n isAsking: `${name} is asking`,\n answerPlaceholder: `Type your answer to ${name} — or pick an option above`,\n emptyThreadsComposer: `Type below to ask ${name}, bring in people, or both.`,\n emptyThreadsNewTask: `Use New Task to ask ${name}, bring in people, or both.`,\n draftingHint: `This thread works in the document: ${name} reads what it needs and makes its edits as tracked changes you accept or reject.`,\n draftingAttachHint: `Attach the open document to this thread: its questions then edit the document as tracked changes. Until then, ${name} only answers.`,\n factsInContext: (facts) =>\n `${facts} added to this chat are always in ${name}'s context for this chat.`,\n reviewEach: (count, scope) =>\n `Ask one question — ${name} answers it for each of the ${count} ${scope} document${plural(count)}.`,\n factsBudgetHint: `Facts added to this chat are always in ${name}'s context for this chat, so they share one budget. This estimates the tokens they add (≈4 characters per token), capped at ~2,000.`,\n noAnswerHint: `${name} finished this document without an answer for this field. The document may not say, or the request failed. Run it again to retry.`,\n startWith: `Start with ${name}`,\n replyWith: `Reply with ${name}`,\n include: `Include ${name}`,\n replyNeedsWorkspace: `Open a workspace to chat with ${name} about this email`,\n uploadedIndexing: `Files uploaded successfully. ${name} is now indexing them in the background.`,\n afterUpload: `After upload completes, ${name} will index files in the background.`,\n deepResearch: {\n description: `Send ${name} through your files and the web, and get an answer with sources`,\n details: `${name} searches your files and the web, then answers with the sources it used. You’ll see the research unfold in the chat.`,\n },\n annotate: {\n details: `Ask one question — ${name} answers it for every selected file and fills a new column with the answers.`,\n placeholder: `What should ${name} read out? e.g. What currency is the penalty clause denominated in?`,\n },\n }\n}\n\n/** The host's name for its assistant (`ArbiHostConfig.assistantName`), else \"ARBI\". */\nexport function useAssistantName(): string {\n const name = useHostConfigRecord().assistantName\n return (typeof name === 'string' && name.trim()) || DEFAULT_ASSISTANT_NAME\n}\n\n/** The kit phrases for the host's assistant name. */\nexport function useAssistantCopy(): AssistantCopy {\n const name = useAssistantName()\n return useMemo(() => assistantCopy(name), [name])\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone (by any of its labels) is not a message. */\nexport function hasMessageBody(\n value: string,\n recipientLabel: string | ReadonlyArray<string> = 'ARBI'\n): boolean {\n const text = value.trim().toLowerCase()\n const labels = typeof recipientLabel === 'string' ? [recipientLabel] : recipientLabel\n return !!text && !labels.some((label) => text === `@${label}`.toLowerCase())\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the documents open beside the chat, and which one a chat turn drafts in.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`). Being open binds nothing:\n * a turn names a document (`active_artifact_ext_id`, read with `takeDocumentForTurn` as the\n * question is sent) only when its thread is bound to it (`./thread-document`: started from the\n * document, or attached in that thread), when the document was made in that thread, or when the\n * open document is ambient (an email draft open in the composer). The server then binds the live\n * document to the turn: a Word document is read on demand and edited as tracked changes in the\n * open editor, and what the assistant saves becomes a child version of it. The request carries a\n * reference, never the content.\n *\n * The named document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document is on top and closing it hands\n * back to the one before. It is not the session state's viewing document (`useArbiSessionState`):\n * it holds what mounted viewers can draft in (saved documents only, with the callback that shows\n * the live one again), and a turn reads it outside React. A viewer on the session's viewing\n * document passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/** The fields that decide where a document opens. */\nexport interface WordDocumentKind {\n file_name?: string | null\n wp_type?: string | null\n}\n\n/**\n * A document edited in the Word editor: a `.docx`, or a document the assistant wrote (an\n * artifact). The one rule for where a document opens (`openWordEditor` or `openDocument`) and\n * which documents a chat drafts in.\n */\nexport function opensInWord(doc: WordDocumentKind | null | undefined): boolean {\n return !!doc && (doc.wp_type === 'artifact' || !!doc.file_name?.toLowerCase().endsWith('.docx'))\n}\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact or Word\n * document counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (!documentData || !opensInWord(documentData)) return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n /** The thread the document was made in: that thread drafts in it without being bound to it. */\n conversationId?: string | null\n /**\n * Drafted in by whichever chat is beside it, bound or not (an email draft open in the composer:\n * the composer is a drafting surface of its own).\n */\n ambient?: boolean\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n const { documentId, workspaceId, conversationId, ambient } = registration\n useEffect(() => {\n latest.current = registration\n })\n // What decides which chat drafts in it changed (its record loaded): readers re-render.\n useEffect(() => {\n if (documentId) emit()\n }, [documentId, workspaceId, conversationId, ambient])\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id (the most recently opened), or null. Re-renders when it changes. */\nexport function useOpenDocumentId(options?: { workspaceId?: string | null }): string | null {\n const workspaceId = options?.workspaceId ?? null\n return useSyncExternalStore(\n subscribe,\n () => openDocumentId({ workspaceId }),\n () => null\n )\n}\n\n/** The open document's id (the most recently opened); with `workspaceId`, only one of it. */\nexport function openDocumentId(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry || !inWorkspace(entry, options?.workspaceId)) return null\n return entry.documentId\n}\n\nfunction inWorkspace(entry: Entry, workspaceId: string | null | undefined): boolean {\n const own = entry.current().workspaceId\n return !workspaceId || !own || own === workspaceId\n}\n\n/** What a turn is about to be sent in: its conversation and the document its thread is bound to. */\nexport interface TurnDocumentInput {\n /** The thread's bound document (`threadDocumentId` / the session's `newChatDocumentId`). */\n boundDocumentId: string | null | undefined\n /** The conversation (null: a new chat). */\n conversationId: string | null | undefined\n /** The chat's workspace: an open document of another workspace is never picked up. */\n workspaceId?: string | null\n}\n\n/** The document a turn drafts in, and the open viewer showing it (if one is). */\nfunction pickTurnDocument({\n boundDocumentId,\n conversationId,\n workspaceId,\n}: TurnDocumentInput): { documentId: string; entry: Entry | undefined } | null {\n // A bound thread names its document on every turn, open or not.\n if (boundDocumentId) {\n const entry = [...entries].reverse().find((e) => e.documentId === boundDocumentId)\n return { documentId: boundDocumentId, entry }\n }\n // Unbound: only a document made in this thread, or an ambient one (an email draft).\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n if (!inWorkspace(entry, workspaceId)) continue\n const { ambient, conversationId: madeIn } = entry.current()\n if (ambient || (conversationId && madeIn === conversationId))\n return { documentId: entry.documentId, entry }\n }\n return null\n}\n\n/** The document a turn sent now would draft in, or null. Re-renders as documents open and close. */\nexport function useTurnDocumentId(input: TurnDocumentInput): string | null {\n const { boundDocumentId = null, conversationId = null, workspaceId = null } = input\n return useSyncExternalStore(\n subscribe,\n () => pickTurnDocument({ boundDocumentId, conversationId, workspaceId })?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear.\n */\nexport function takeDocumentForTurn(input: TurnDocumentInput): string | null {\n const picked = pickTurnDocument(input)\n if (!picked) return null\n const { documentId, entry } = picked\n if (entry) {\n const { shownId, showLive } = entry.current()\n if (shownId && shownId !== documentId && parseVersionRef(shownId).docId === documentId)\n showLive?.()\n }\n return documentId\n}\n","/**\n * A thread's document: the one document a conversation drafts in, part of the conversation.\n *\n * A thread is bound to a document only when it was started from it (\"Chat about this document\" in\n * the viewer) or the person attached it in that thread. Only that thread names it on its turns\n * (`active_artifact_ext_id`), on every turn and after a reload. A document merely open or docked\n * beside the chat binds nothing: a new chat (the ask bar, the new-chat button, the thread\n * launcher, home) starts unbound, so a question there never becomes an edit of whatever is open.\n *\n * The binding is the server's: the conversation's `bound_document_ext_id`, set by the first turn\n * (`bound_document_ext_id` on the turn that starts it) or by a PATCH, and read under each reader's\n * access (`bound_document_unavailable`: bound to a document this reader cannot open). It follows\n * the person to every device, and a shared thread's members all see it. The query cache holds it\n * (`./thread-binding`); a new chat's binding is the session's `newChatDocumentId` until its first\n * turn creates the conversation.\n *\n * This module is the light half (no query client, no SDK), so the shell entry can carry it.\n */\n\n/** What a conversation row says about its binding. */\nexport interface ThreadBindingRow {\n external_id: string\n bound_document_ext_id?: string | null\n bound_document_unavailable?: boolean | null\n updated_at?: string | null\n}\n\n/** A conversation's binding as this reader sees it. */\nexport interface ThreadBinding {\n /** The bound document, or null (unbound, or bound to one this reader cannot open). */\n documentId: string | null\n /** Bound to a document this reader cannot open (another member's private document, or deleted). */\n unavailable: boolean\n}\n\nexport const UNBOUND: ThreadBinding = { documentId: null, unavailable: false }\n\n/** A row's binding. */\nexport function bindingOfRow(row: ThreadBindingRow | null | undefined): ThreadBinding {\n if (!row) return UNBOUND\n const documentId = row.bound_document_ext_id ?? null\n return { documentId, unavailable: !documentId && row.bound_document_unavailable === true }\n}\n\n/** The most recently active conversation bound to a document, among `conversations`, or null. */\nexport function latestThreadOfDocument(\n conversations: readonly ThreadBindingRow[] | null | undefined,\n documentId: string\n): string | null {\n let latest: ThreadBindingRow | null = null\n for (const row of conversations ?? []) {\n if (row.bound_document_ext_id !== documentId) continue\n if (!latest || (row.updated_at ?? '') > (latest.updated_at ?? '')) latest = row\n }\n return latest?.external_id ?? null\n}\n\n// --------------------------------------------------------------------------------------------- //\n// Bindings this browser kept before the server held them (`localStorage`), moved to the server\n// once (`migrateLegacyThreadDocuments` in `./thread-binding`) and then forgotten.\n// --------------------------------------------------------------------------------------------- //\n\nexport const LEGACY_THREAD_DOCUMENTS_KEY = 'arbi-thread-documents'\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The bindings this browser kept locally (conversation id → document id); empty when none. */\nexport function readLegacyThreadDocuments(): Record<string, string> {\n const out: Record<string, string> = {}\n try {\n const parsed = JSON.parse(storage()?.getItem(LEGACY_THREAD_DOCUMENTS_KEY) ?? 'null') as unknown\n if (parsed && typeof parsed === 'object')\n for (const [conversationId, documentId] of Object.entries(parsed))\n if (typeof documentId === 'string') out[conversationId] = documentId\n } catch {\n // Damaged or blocked: nothing to move.\n }\n return out\n}\n\n/** Forget locally kept bindings (moved to the server); the key goes with the last of them. */\nexport function forgetLegacyThreadDocuments(conversationIds: readonly string[]): void {\n if (conversationIds.length === 0) return\n const rest = readLegacyThreadDocuments()\n conversationIds.forEach((id) => delete rest[id])\n try {\n if (Object.keys(rest).length === 0) storage()?.removeItem(LEGACY_THREAD_DOCUMENTS_KEY)\n else storage()?.setItem(LEGACY_THREAD_DOCUMENTS_KEY, JSON.stringify(rest))\n } catch {\n // Blocked: nothing more to do.\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/host/assistant-copy.ts","../src/chat/mentions.ts","../src/chat/open-document.ts","../src/chat/thread-document.ts"],"names":["storage","Sonner","jsx","useState","useMemo"],"mappings":";;;;;;;;;;;;;AA8BA,IAAM,KAAA,GAAyD;AAAA,EAC7D,KAAA,EAAO,EAAA;AAAA,EACP,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,KAAA;AAAA,EACV,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAO,WAAA,CAAgC,OAAO,EAAE,GAAG,OAAO,WAAA,EAAa,IAAA,EAAM,GAAA,EAAK,CAAA,EAAE,CAAE,CAAA;AACxF;AAGO,IAAM,sBAAqC,mBAAA;AAG3C,SAAS,kBAAA,CACd,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,OAAA,CAAQ,QAAA,CAAS,CAAC,CAAA,MAAO;AAAA,IACvB,GAAG,KAAA;AAAA,IACH,WAAA,EAAa,WAAA,KAAgB,MAAA,GAAY,CAAA,CAAE,WAAA,GAAc,WAAA;AAAA,IACzD,GAAA,EAAK,EAAE,GAAA,GAAM;AAAA,GACf,CAAE,CAAA;AACJ;AAMO,SAAS,aAAA,CACd,KAAA,EACA,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,kBAAA,CAAmB,aAAa,OAAO,CAAA;AACvC,EAAA,OAAA,CAAQ,QAAA,CAAS,EAAE,KAAA,EAAO,OAAA,EAAS,OAAO,CAAA;AAC5C;AAGO,SAAS,iBAAA,CAAkB,UAAyB,mBAAA,EAAoC;AAC7F,EAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,OAAA,CAAQ,QAAA,EAAS;AACrC,EAAA,IAAI,YAAY,IAAA,EAAM,OAAA,CAAQ,SAAS,EAAE,OAAA,EAAS,MAAM,CAAA;AACxD,EAAA,OAAO,OAAA;AACT;AAWO,SAAS,qBACd,GAAA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AA,GAA8B;AAE3C,SAAS,OAAA,GAA+B;AACtC,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,YAAA,KAAiB,WAAA,GAAc,KAAA,CAAA,GAAY,YAAA;AAAA,EAC3D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGO,SAAS,yBAAA,GAAoD;AAClE,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,OAAA,IAAW,OAAA,CAAQ,2BAA2B,KAAK,MAAM,CAAA;AACnF,IAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAA;AAC9B,MAAA,KAAA,MAAW,CAAC,cAAA,EAAgB,UAAU,CAAA,IAAK,MAAA,CAAO,QAAQ,MAAM,CAAA;AAC9D,QAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,GAAA,CAAI,cAAc,CAAA,GAAI,UAAA;AAAA,IAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,GAAA;AACT;AAGO,SAAS,4BAA4B,eAAA,EAA0C;AACpF,EAAA,IAAI,eAAA,CAAgB,WAAW,CAAA,EAAG;AAClC,EAAA,MAAM,OAAO,yBAAA,EAA0B;AACvC,EAAA,eAAA,CAAgB,QAAQ,CAAC,EAAA,KAAO,OAAO,IAAA,CAAK,EAAE,CAAC,CAAA;AAC/C,EAAA,IAAI;AACF,IAAA,IAAI,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG,OAAA,EAAQ,EAAG,UAAA,CAAW,2BAA2B,CAAA;AAAA,kBACxE,EAAG,OAAA,CAAQ,6BAA6B,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,EAC3E,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-7KZS22EK.js","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg pointer-coarse:w-88\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {(n.onSelect || n.href) && (\n <span className=\"shrink-0 self-center rounded-md bg-primary/10 px-2 py-1 text-xs font-medium text-primary\">\n {n.actionLabel ?? 'Open'}\n </span>\n )}\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context, ./merge and the entity vocabulary are all it reaches), so a\n * marketing site that only sets the blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\nimport { configureEntityVocabulary, type EntityVocabulary } from '../entities/vocabulary'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n // The site's nouns are in place before any kit below renders a label.\n const { vocabulary } = config as { vocabulary?: EntityVocabulary }\n if (vocabulary) configureEntityVocabulary(vocabulary)\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * What the kits call the assistant in their own words, from the host's name for it\n * (`ArbiHostConfig.assistantName`, also what people @mention). One label source: every kit phrase\n * that names the assistant is here, written once around the name, so a custom site's name shows\n * everywhere and ARBI's own text is unchanged (\"ARBI\" when the host names it nothing else).\n *\n * const copy = useAssistantCopy()\n * <Button>{copy.ask}</Button> // \"Ask ARBI\", or \"Ask Acme Assistant\"\n *\n * SDK-free: exported from `@arbidocs/react/shell` too, for presentational parts.\n */\nimport { useMemo } from 'react'\n// The record, not `useArbiHost` (`./config` names the SDK's types): this module stays SDK-free.\nimport { useHostConfigRecord } from './context'\n\n/** The assistant's name when the host names it nothing else. */\nexport const DEFAULT_ASSISTANT_NAME = 'ARBI'\n\n/** Every kit phrase that names the assistant. */\nexport interface AssistantCopy {\n /** The name itself. */\n name: string\n /** \"Ask ARBI\": a button or tab that starts a question. */\n ask: string\n /** \"Ask ARBI anything\": an empty list's call to ask. */\n askAnything: string\n /** \"Ask ARBI anything…\": the chat composer's placeholder. */\n askAnythingPlaceholder: string\n /** \"Ask ARBI...\": a compact composer's placeholder. */\n askPlaceholder: string\n /** \"Ask ARBI about your documents\": the empty chat's heading. */\n askAboutDocuments: string\n /** The files bulk bar's chat tooltip. */\n askAboutSelection: string\n /** \"ARBI is asking\": the heading over a question the assistant asks. */\n isAsking: string\n /** The composer's placeholder while the assistant waits for an answer. */\n answerPlaceholder: string\n /** The empty threads list, with the composer below it. */\n emptyThreadsComposer: string\n /** The empty threads list, with a New Task button. */\n emptyThreadsNewTask: string\n /** The drafting chip's hint while the thread drafts in a document. */\n draftingHint: string\n /** The drafting chip's hint before the document is attached. */\n draftingAttachHint: string\n /** The chat's facts tab note. */\n factsInContext: (facts: string) => string\n /** \"Ask one question — ARBI answers it for each of …\": the AI review's ask step. */\n reviewEach: (count: number, scope: string) => string\n /** The facts bar's note on the chat's facts budget. */\n factsBudgetHint: string\n /** An AI review cell left without an answer. */\n noAnswerHint: string\n /** The new-thread dialog's button that hands the thread to the assistant. */\n startWith: string\n /** The mail action bar's \"Reply with ARBI\". */\n replyWith: string\n /** The Word editor's comment button that @mentions the assistant. */\n include: string\n /** A reply to an email asked for outside a workspace. */\n replyNeedsWorkspace: string\n /** After an upload. */\n uploadedIndexing: string\n /** Before an upload completes. */\n afterUpload: string\n /** The built-in Deep research workflow's description and details. */\n deepResearch: { description: string; details: string }\n /** The built-in AI annotation operation's details. */\n annotate: { details: string; placeholder: string }\n}\n\nconst plural = (n: number) => (n === 1 ? '' : 's')\n\n/** The phrases for one name. `assistantCopy()` is ARBI's own text. */\nexport function assistantCopy(name: string = DEFAULT_ASSISTANT_NAME): AssistantCopy {\n return {\n name,\n ask: `Ask ${name}`,\n askAnything: `Ask ${name} anything`,\n askAnythingPlaceholder: `Ask ${name} anything…`,\n askPlaceholder: `Ask ${name}...`,\n askAboutDocuments: `Ask ${name} about your documents`,\n askAboutSelection: `Ask ${name} about the selected document(s) in a new thread`,\n isAsking: `${name} is asking`,\n answerPlaceholder: `Type your answer to ${name} — or pick an option above`,\n emptyThreadsComposer: `Type below to ask ${name}, bring in people, or both.`,\n emptyThreadsNewTask: `Use New Task to ask ${name}, bring in people, or both.`,\n draftingHint: `This thread works in the document: ${name} reads what it needs and makes its edits as tracked changes you accept or reject.`,\n draftingAttachHint: `Attach the open document to this thread: its questions then edit the document as tracked changes. Until then, ${name} only answers.`,\n factsInContext: (facts) =>\n `${facts} added to this chat are always in ${name}'s context for this chat.`,\n reviewEach: (count, scope) =>\n `Ask one question — ${name} answers it for each of the ${count} ${scope} document${plural(count)}.`,\n factsBudgetHint: `Facts added to this chat are always in ${name}'s context for this chat, so they share one budget. This estimates the tokens they add (≈4 characters per token), capped at ~2,000.`,\n noAnswerHint: `${name} finished this document without an answer for this field. The document may not say, or the request failed. Run it again to retry.`,\n startWith: `Start with ${name}`,\n replyWith: `Reply with ${name}`,\n include: `Include ${name}`,\n replyNeedsWorkspace: `Open a workspace to chat with ${name} about this email`,\n uploadedIndexing: `Files uploaded successfully. ${name} is now indexing them in the background.`,\n afterUpload: `After upload completes, ${name} will index files in the background.`,\n deepResearch: {\n description: `Send ${name} through your files and the web, and get an answer with sources`,\n details: `${name} searches your files and the web, then answers with the sources it used. You’ll see the research unfold in the chat.`,\n },\n annotate: {\n details: `Ask one question — ${name} answers it for every selected file and fills a new column with the answers.`,\n placeholder: `What should ${name} read out? e.g. What currency is the penalty clause denominated in?`,\n },\n }\n}\n\n/** The host's name for its assistant (`ArbiHostConfig.assistantName`), else \"ARBI\". */\nexport function useAssistantName(): string {\n const name = useHostConfigRecord().assistantName\n return (typeof name === 'string' && name.trim()) || DEFAULT_ASSISTANT_NAME\n}\n\n/** The kit phrases for the host's assistant name. */\nexport function useAssistantCopy(): AssistantCopy {\n const name = useAssistantName()\n return useMemo(() => assistantCopy(name), [name])\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone (by any of its labels) is not a message. */\nexport function hasMessageBody(\n value: string,\n recipientLabel: string | ReadonlyArray<string> = 'ARBI'\n): boolean {\n const text = value.trim().toLowerCase()\n const labels = typeof recipientLabel === 'string' ? [recipientLabel] : recipientLabel\n return !!text && !labels.some((label) => text === `@${label}`.toLowerCase())\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the documents open beside the chat, and which one a chat turn drafts in.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`). Being open binds nothing:\n * a turn names a document (`active_artifact_ext_id`, read with `takeDocumentForTurn` as the\n * question is sent) only when its thread is bound to it (`./thread-document`: started from the\n * document, or attached in that thread), when the document was made in that thread, or when the\n * open document is ambient (an email draft open in the composer). The server then binds the live\n * document to the turn: a Word document is read on demand and edited as tracked changes in the\n * open editor, and what the assistant saves becomes a child version of it. The request carries a\n * reference, never the content.\n *\n * The named document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document is on top and closing it hands\n * back to the one before. It is not the session state's viewing document (`useArbiSessionState`):\n * it holds what mounted viewers can draft in (saved documents only, with the callback that shows\n * the live one again), and a turn reads it outside React. A viewer on the session's viewing\n * document passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/** The fields that decide where a document opens. */\nexport interface WordDocumentKind {\n file_name?: string | null\n wp_type?: string | null\n}\n\n/**\n * A document edited in the Word editor: a `.docx`, or a document the assistant wrote (an\n * artifact). The one rule for where a document opens (`openWordEditor` or `openDocument`) and\n * which documents a chat drafts in.\n */\nexport function opensInWord(doc: WordDocumentKind | null | undefined): boolean {\n return !!doc && (doc.wp_type === 'artifact' || !!doc.file_name?.toLowerCase().endsWith('.docx'))\n}\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact or Word\n * document counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (!documentData || !opensInWord(documentData)) return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n /** The thread the document was made in: that thread drafts in it without being bound to it. */\n conversationId?: string | null\n /**\n * Drafted in by whichever chat is beside it, bound or not (an email draft open in the composer:\n * the composer is a drafting surface of its own).\n */\n ambient?: boolean\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n const { documentId, workspaceId, conversationId, ambient } = registration\n useEffect(() => {\n latest.current = registration\n })\n // What decides which chat drafts in it changed (its record loaded): readers re-render.\n useEffect(() => {\n if (documentId) emit()\n }, [documentId, workspaceId, conversationId, ambient])\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id (the most recently opened), or null. Re-renders when it changes. */\nexport function useOpenDocumentId(options?: { workspaceId?: string | null }): string | null {\n const workspaceId = options?.workspaceId ?? null\n return useSyncExternalStore(\n subscribe,\n () => openDocumentId({ workspaceId }),\n () => null\n )\n}\n\n/** The open document's id (the most recently opened); with `workspaceId`, only one of it. */\nexport function openDocumentId(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry || !inWorkspace(entry, options?.workspaceId)) return null\n return entry.documentId\n}\n\nfunction inWorkspace(entry: Entry, workspaceId: string | null | undefined): boolean {\n const own = entry.current().workspaceId\n return !workspaceId || !own || own === workspaceId\n}\n\n/** What a turn is about to be sent in: its conversation and the document its thread is bound to. */\nexport interface TurnDocumentInput {\n /** The thread's bound document (`threadDocumentId` / the session's `newChatDocumentId`). */\n boundDocumentId: string | null | undefined\n /** The conversation (null: a new chat). */\n conversationId: string | null | undefined\n /** The chat's workspace: an open document of another workspace is never picked up. */\n workspaceId?: string | null\n}\n\n/** The document a turn drafts in, and the open viewer showing it (if one is). */\nfunction pickTurnDocument({\n boundDocumentId,\n conversationId,\n workspaceId,\n}: TurnDocumentInput): { documentId: string; entry: Entry | undefined } | null {\n // A bound thread names its document on every turn, open or not.\n if (boundDocumentId) {\n const entry = [...entries].reverse().find((e) => e.documentId === boundDocumentId)\n return { documentId: boundDocumentId, entry }\n }\n // Unbound: only a document made in this thread, or an ambient one (an email draft).\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n if (!inWorkspace(entry, workspaceId)) continue\n const { ambient, conversationId: madeIn } = entry.current()\n if (ambient || (conversationId && madeIn === conversationId))\n return { documentId: entry.documentId, entry }\n }\n return null\n}\n\n/** The document a turn sent now would draft in, or null. Re-renders as documents open and close. */\nexport function useTurnDocumentId(input: TurnDocumentInput): string | null {\n const { boundDocumentId = null, conversationId = null, workspaceId = null } = input\n return useSyncExternalStore(\n subscribe,\n () => pickTurnDocument({ boundDocumentId, conversationId, workspaceId })?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear.\n */\nexport function takeDocumentForTurn(input: TurnDocumentInput): string | null {\n const picked = pickTurnDocument(input)\n if (!picked) return null\n const { documentId, entry } = picked\n if (entry) {\n const { shownId, showLive } = entry.current()\n if (shownId && shownId !== documentId && parseVersionRef(shownId).docId === documentId)\n showLive?.()\n }\n return documentId\n}\n","/**\n * A thread's document: the one document a conversation drafts in, part of the conversation.\n *\n * A thread is bound to a document only when it was started from it (\"Chat about this document\" in\n * the viewer) or the person attached it in that thread. Only that thread names it on its turns\n * (`active_artifact_ext_id`), on every turn and after a reload. A document merely open or docked\n * beside the chat binds nothing: a new chat (the ask bar, the new-chat button, the thread\n * launcher, home) starts unbound, so a question there never becomes an edit of whatever is open.\n *\n * The binding is the server's: the conversation's `bound_document_ext_id`, set by the first turn\n * (`bound_document_ext_id` on the turn that starts it) or by a PATCH, and read under each reader's\n * access (`bound_document_unavailable`: bound to a document this reader cannot open). It follows\n * the person to every device, and a shared thread's members all see it. The query cache holds it\n * (`./thread-binding`); a new chat's binding is the session's `newChatDocumentId` until its first\n * turn creates the conversation.\n *\n * This module is the light half (no query client, no SDK), so the shell entry can carry it.\n */\n\n/** What a conversation row says about its binding. */\nexport interface ThreadBindingRow {\n external_id: string\n bound_document_ext_id?: string | null\n bound_document_unavailable?: boolean | null\n updated_at?: string | null\n}\n\n/** A conversation's binding as this reader sees it. */\nexport interface ThreadBinding {\n /** The bound document, or null (unbound, or bound to one this reader cannot open). */\n documentId: string | null\n /** Bound to a document this reader cannot open (another member's private document, or deleted). */\n unavailable: boolean\n}\n\nexport const UNBOUND: ThreadBinding = { documentId: null, unavailable: false }\n\n/** A row's binding. */\nexport function bindingOfRow(row: ThreadBindingRow | null | undefined): ThreadBinding {\n if (!row) return UNBOUND\n const documentId = row.bound_document_ext_id ?? null\n return { documentId, unavailable: !documentId && row.bound_document_unavailable === true }\n}\n\n/** The most recently active conversation bound to a document, among `conversations`, or null. */\nexport function latestThreadOfDocument(\n conversations: readonly ThreadBindingRow[] | null | undefined,\n documentId: string\n): string | null {\n let latest: ThreadBindingRow | null = null\n for (const row of conversations ?? []) {\n if (row.bound_document_ext_id !== documentId) continue\n if (!latest || (row.updated_at ?? '') > (latest.updated_at ?? '')) latest = row\n }\n return latest?.external_id ?? null\n}\n\n// --------------------------------------------------------------------------------------------- //\n// Bindings this browser kept before the server held them (`localStorage`), moved to the server\n// once (`migrateLegacyThreadDocuments` in `./thread-binding`) and then forgotten.\n// --------------------------------------------------------------------------------------------- //\n\nexport const LEGACY_THREAD_DOCUMENTS_KEY = 'arbi-thread-documents'\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The bindings this browser kept locally (conversation id → document id); empty when none. */\nexport function readLegacyThreadDocuments(): Record<string, string> {\n const out: Record<string, string> = {}\n try {\n const parsed = JSON.parse(storage()?.getItem(LEGACY_THREAD_DOCUMENTS_KEY) ?? 'null') as unknown\n if (parsed && typeof parsed === 'object')\n for (const [conversationId, documentId] of Object.entries(parsed))\n if (typeof documentId === 'string') out[conversationId] = documentId\n } catch {\n // Damaged or blocked: nothing to move.\n }\n return out\n}\n\n/** Forget locally kept bindings (moved to the server); the key goes with the last of them. */\nexport function forgetLegacyThreadDocuments(conversationIds: readonly string[]): void {\n if (conversationIds.length === 0) return\n const rest = readLegacyThreadDocuments()\n conversationIds.forEach((id) => delete rest[id])\n try {\n if (Object.keys(rest).length === 0) storage()?.removeItem(LEGACY_THREAD_DOCUMENTS_KEY)\n else storage()?.setItem(LEGACY_THREAD_DOCUMENTS_KEY, JSON.stringify(rest))\n } catch {\n // Blocked: nothing more to do.\n }\n}\n"]}