@jsb188/mday 1.1.10 → 1.1.12

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 (210) hide show
  1. package/package.json +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -0,0 +1,850 @@
1
+ import { calculateExpressionDecimal, parseDecoratedExpressionNumber } from '@jsb188/app/utils/expression.helpers.ts';
2
+ import { AGENT_NOTE_KIND_ENUMS, AGENT_NOTE_LIMITS, AGENT_NOTE_MARKDOWN_ISSUE_ENUMS } from '../constants/agentNote.ts';
3
+ import type {
4
+ AgentNoteACLChecker,
5
+ AgentNoteActivitySource,
6
+ AgentNoteAnswerNumber,
7
+ AgentNoteKindEnum,
8
+ AgentNoteMarkdownIssueEnum,
9
+ AgentNoteMarkdownSanitizeResult,
10
+ } from '../types/agentNote.d.ts';
11
+ import type { ACLPermissionCheck, PermissionCheckFor } from './organization.ts';
12
+
13
+ type AgentNoteMarkdownIssues = Set<AgentNoteMarkdownIssueEnum>;
14
+ type AgentNoteTableAlignment = 'left' | 'center' | 'right' | null;
15
+
16
+ type AgentNoteMarkdownBlock =
17
+ | { kind: 'paragraph' | 'table'; lines: string[] }
18
+ | { kind: 'list'; ordered: boolean; start: number; items: string[] };
19
+
20
+ type AgentNoteMarkdownTable = {
21
+ header: string[];
22
+ alignments: AgentNoteTableAlignment[];
23
+ rows: string[][];
24
+ nextIndex: number;
25
+ };
26
+
27
+ const FILE_CONSTANTS = {
28
+ emojiSegmenter: new Intl.Segmenter(undefined, { granularity: 'grapheme' }),
29
+ ellipsis: '…',
30
+ // Input beyond this many characters is never needed to fill a body
31
+ inputLengthFactor: 4,
32
+ // C0/C1 controls (except tab and newline) plus invisible and bidi controls
33
+ invisibleCharacters: /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g,
34
+ spaceCharacters: /[\u00A0\u2007\u2009\u202F]/g,
35
+ minusCharacters: /[\u2212\u2012\u2013]/g,
36
+ // A whole comment, or an unclosed opener that could pair with a later "-->"
37
+ htmlComment: /<!--(?:[\s\S]*?-->)?/g,
38
+ // Known HTML elements, or any tag with an attribute value; text such as
39
+ // "<M to >L" or "<customer>" is not a tag
40
+ htmlTag:
41
+ /<\/?(?:(?:a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|big|blink|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h[1-6]|head|header|hgroup|hr|html|i|iframe|image|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|marquee|math|menu|meta|meter|nav|nobr|noembed|noframes|noscript|object|ol|optgroup|option|output|p|param|picture|plaintext|pre|progress|q|rp|rt|ruby|s|samp|script|search|section|select|slot|small|source|span|strike|strong|style|sub|summary|sup|svg|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr|xmp)(?=[\s/>])|[a-z][\w:-]*(?=[\s/][^<>]*=))[^<>]*>/gi,
42
+ // A line break separates words, so it becomes a space instead of nothing
43
+ lineBreakTag: /<br\s*\/?>/gi,
44
+ // Untrusted-data markers are three or more angle brackets in a row
45
+ markerOpen: /<{3,}/g,
46
+ markerClose: />{3,}/g,
47
+ autolink: /<(?:https?|ftp|mailto|tel):[^<>\s]*>/gi,
48
+ image: /!\[[^\]\n]*\](?:\([^)\n]*\)|\[[^\]\n]*\])/g,
49
+ link: /\[([^\]\n]*)\](?:\([^)\n]*\)|\[[^\]\n]*\])/g,
50
+ // An explicit link needs "(" right after "]", so splitting the pair stops
51
+ // nested or escaped brackets the link pattern misses from parsing as links
52
+ linkDestinationStart: /\](?=\()/g,
53
+ bareUrl: /\b(?:(?:https?|ftp):\/\/|www\.)[^\s<>()[\]|]+|\b(?:mailto|tel):[^\s<>()[\]|]+/gi,
54
+ inlineCode: /`+/g,
55
+ styleMarker: /~~|\[\/?hl\]/gi,
56
+ // A backtick run followed by another backtick is inline code, not a fence
57
+ fence: /^ *(?:`{3,}(?!.*`)|~{3,})/,
58
+ heading: /^ *#{1,6}(?:[ \t]+|$)/,
59
+ headingClose: /[ \t]+#+[ \t]*$/,
60
+ quote: /^ *>[ \t]?/,
61
+ rule: /^ *(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|={3,}[ \t]*)$/,
62
+ linkDefinition: /^ *\[[^\]]+\]:/,
63
+ listMarker: /^([ \t]*)(?:[-+*•]|(\d{1,9})[.)])(?:[ \t]+|$)/,
64
+ nestedMarker: /^(?:(?:[-+*•]|\d{1,9}[.)])[ \t]+|#{1,6}[ \t]+|>[ \t]?)/,
65
+ tableDelimiterCell: /^:?-+:?$/,
66
+ numberDecorationPrefix: /^[+-]?\s*([$€£¥₹₩]|[A-Za-z]{3})/,
67
+ numberDecorationSuffix: /[\d.]\s*(%|[A-Za-z°]+(?:[ /-][A-Za-z°]+)*)$/,
68
+ currencyCodes: new Set('USD CAD EUR GBP JPY AUD NZD CHF CNY INR KRW MXN'.split(' ')),
69
+ // A number written with a thousands suffix ("10k", "$1.5K", "(2k)"); "10 kg" is a unit, not thousands
70
+ thousandsSuffix: /^(.*\d)\s*[kK](\)?)$/s,
71
+ sourcePermissionsByKind: {
72
+ // Campaign responses and field docs are both gated by product reads
73
+ CAMPAIGN_FORM: [['products', 'READ']],
74
+ // Campaign replies are inbox mail, so the inbox read gate applies too
75
+ CAMPAIGN_EMAIL: [
76
+ ['products', 'READ'],
77
+ ['orgManagement', 'READ'],
78
+ ],
79
+ FIELD_DOC: [['products', 'READ']],
80
+ // Same gate as general_read
81
+ INSIGHT: [['viewData', 'READ']],
82
+ // The server separately enforces reminder ownership for mutations.
83
+ REMINDER: [],
84
+ } as Record<AgentNoteKindEnum, readonly (readonly [PermissionCheckFor, ACLPermissionCheck])[]>,
85
+ };
86
+
87
+ /*
88
+ * Return one display emoji within the database's Unicode code-point limit,
89
+ * or null for missing values, text, multiple emoji or oversized sequences.
90
+ */
91
+ export function normalizeAgentNoteEmoji(value: unknown): string | null {
92
+ if (typeof value !== 'string') return null;
93
+ const emoji = value.trim();
94
+ if (!emoji || [...emoji].length > AGENT_NOTE_LIMITS.emojiMaxLength) return null;
95
+ if ([...FILE_CONSTANTS.emojiSegmenter.segment(emoji)].length !== 1) return null;
96
+ return /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20E3/u.test(emoji) ? emoji : null;
97
+ }
98
+
99
+ /*
100
+ * Display calendar note emojis consistently without changing the saved value.
101
+ */
102
+ export function getAgentNoteDisplayEmoji(emoji: string): string {
103
+ return emoji === '📆' || emoji === '📅' ? '🗓️' : emoji;
104
+ }
105
+
106
+ /*
107
+ * Replace every match of a pattern and record the issue when anything changed.
108
+ */
109
+ function replaceAgentNoteMarkdown(
110
+ text: string,
111
+ pattern: RegExp,
112
+ replacement: string,
113
+ issue: AgentNoteMarkdownIssueEnum,
114
+ issues: AgentNoteMarkdownIssues,
115
+ ) {
116
+ const next = text.replace(pattern, replacement);
117
+ if (next !== text) {
118
+ issues.add(issue);
119
+ }
120
+ return next;
121
+ }
122
+
123
+ /*
124
+ * Normalize line endings and remove control, invisible and bidi characters.
125
+ */
126
+ function normalizeAgentNoteCharacters(text: string) {
127
+ return text
128
+ .replace(/\r\n?/g, '\n')
129
+ .replace(FILE_CONSTANTS.invisibleCharacters, '')
130
+ .replace(FILE_CONSTANTS.spaceCharacters, ' ')
131
+ .replace(/\t/g, ' ');
132
+ }
133
+
134
+ /*
135
+ * Neutralize untrusted-data markers so note text can never close or open an
136
+ * untrusted block when it is printed back into a prompt.
137
+ */
138
+ function neutralizeAgentNoteMarkers(text: string) {
139
+ return text.replace(FILE_CONSTANTS.markerOpen, '‹‹‹').replace(FILE_CONSTANTS.markerClose, '›››');
140
+ }
141
+
142
+ /*
143
+ * Split every bracket directly followed by a parenthesis, so no explicit link
144
+ * can parse from text the link pattern missed or a removal joined.
145
+ */
146
+ function breakAgentNoteExplicitLinks(text: string, issues: AgentNoteMarkdownIssues) {
147
+ return replaceAgentNoteMarkdown(text, FILE_CONSTANTS.linkDestinationStart, '] ', 'LINK_REMOVED', issues);
148
+ }
149
+
150
+ /*
151
+ * Remove links, images, raw HTML, inline code and unsupported styles from one
152
+ * line once, keeping link labels and code text as plain text.
153
+ */
154
+ function removeAgentNoteInlineMarkup(text: string, issues: AgentNoteMarkdownIssues) {
155
+ let next = replaceAgentNoteMarkdown(text, FILE_CONSTANTS.htmlComment, '', 'HTML_REMOVED', issues);
156
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.autolink, '', 'LINK_REMOVED', issues);
157
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.image, '', 'IMAGE_REMOVED', issues);
158
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.link, '$1', 'LINK_REMOVED', issues);
159
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.lineBreakTag, ' ', 'HTML_REMOVED', issues);
160
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.htmlTag, '', 'HTML_REMOVED', issues);
161
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.bareUrl, '', 'LINK_REMOVED', issues);
162
+ next = replaceAgentNoteMarkdown(next, FILE_CONSTANTS.inlineCode, '', 'CODE_REMOVED', issues);
163
+ return replaceAgentNoteMarkdown(next, FILE_CONSTANTS.styleMarker, '', 'STYLE_REMOVED', issues);
164
+ }
165
+
166
+ /*
167
+ * Remove links, images, raw HTML, inline code and unsupported styles from one
168
+ * line until nothing changes, keeping link labels and code text as plain
169
+ * text. Explicit links and untrusted-data markers are broken last, because
170
+ * any removal can join the pieces of one.
171
+ */
172
+ function sanitizeAgentNoteInlineText(text: string, issues: AgentNoteMarkdownIssues) {
173
+ let next = text;
174
+ let previous: string;
175
+ // Every pass removes text or shortens a link to its label, so this ends
176
+ do {
177
+ previous = next;
178
+ next = removeAgentNoteInlineMarkup(next, issues);
179
+ } while (next !== previous);
180
+ next = breakAgentNoteExplicitLinks(next, issues);
181
+ // Collapse inner space runs but keep leading indentation for list nesting
182
+ return neutralizeAgentNoteMarkers(next.replace(/(\S) {2,}/g, '$1 ').trimEnd());
183
+ }
184
+
185
+ /*
186
+ * Sanitize one server-rendered table value without interpreting leading minus signs as lists or truncating numbers.
187
+ */
188
+ export function sanitizeAgentNoteTableCellText(value: string): string {
189
+ const text = normalizeAgentNoteCharacters(value).replace(/[|\r\n]/g, ' ');
190
+ return sanitizeAgentNoteInlineText(text, new Set()).replace(/[`*_[\]\\]/g, ' ').trim();
191
+ }
192
+
193
+ /*
194
+ * Remove every blockquote marker at the start of one line.
195
+ */
196
+ function stripAgentNoteQuoteMarkers(line: string, issues: AgentNoteMarkdownIssues) {
197
+ let next = line;
198
+ while (FILE_CONSTANTS.quote.test(next)) {
199
+ next = next.replace(FILE_CONSTANTS.quote, '');
200
+ issues.add('BLOCK_FLATTENED');
201
+ }
202
+ return next;
203
+ }
204
+
205
+ /*
206
+ * Split a source body into sanitized lines: blockquote markers are flattened,
207
+ * code fence lines become block breaks, and every line is inline-sanitized.
208
+ */
209
+ function getAgentNoteMarkdownLines(source: string, issues: AgentNoteMarkdownIssues) {
210
+ const text = replaceAgentNoteMarkdown(normalizeAgentNoteCharacters(source), FILE_CONSTANTS.htmlComment, '', 'HTML_REMOVED', issues);
211
+
212
+ return text.split('\n').map((rawLine) => {
213
+ const line = stripAgentNoteQuoteMarkers(rawLine, issues);
214
+ if (FILE_CONSTANTS.fence.test(line)) {
215
+ // Fence content stays as plain text; the fence itself only breaks blocks
216
+ issues.add('CODE_REMOVED');
217
+ return '';
218
+ }
219
+ // Inline removals can expose a quote marker ("mailto:x> text")
220
+ return stripAgentNoteQuoteMarkers(sanitizeAgentNoteInlineText(line, issues), issues);
221
+ });
222
+ }
223
+
224
+ /*
225
+ * Split one markdown table row on unescaped pipes, dropping the optional outer
226
+ * pipes, the same way the chat content parser reads table rows.
227
+ */
228
+ function splitAgentNoteTableRow(line: string) {
229
+ const pipes: number[] = [];
230
+ for (let index = 0; index < line.length; index++) {
231
+ if (line[index] === '\\') {
232
+ index++;
233
+ } else if (line[index] === '|') {
234
+ pipes.push(index);
235
+ }
236
+ }
237
+
238
+ const hasPipe = pipes.length > 0;
239
+ let start = 0;
240
+ let end = line.length;
241
+ if (pipes.length && !line.slice(0, pipes[0]).trim()) {
242
+ start = (pipes.shift() as number) + 1;
243
+ }
244
+ if (pipes.length && !line.slice(pipes[pipes.length - 1] + 1).trim()) {
245
+ end = pipes.pop() as number;
246
+ }
247
+
248
+ const cells: string[] = [];
249
+ for (const boundary of [...pipes, end]) {
250
+ cells.push(line.slice(start, boundary).trim());
251
+ start = boundary + 1;
252
+ }
253
+ return { cells, hasPipe };
254
+ }
255
+
256
+ /*
257
+ * Return the alignment one table delimiter cell declares.
258
+ */
259
+ function getAgentNoteTableAlignment(cell: string): AgentNoteTableAlignment {
260
+ if (cell.startsWith(':') && cell.endsWith(':')) {
261
+ return 'center';
262
+ }
263
+ if (cell.endsWith(':')) {
264
+ return 'right';
265
+ }
266
+ return cell.startsWith(':') ? 'left' : null;
267
+ }
268
+
269
+ /*
270
+ * Return whether a line starts a list item. Indentation never matters for
271
+ * block detection: sanitized lines are left-aligned, so a trimmed line must
272
+ * classify the same way on every pass.
273
+ */
274
+ function isAgentNoteListLine(line: string) {
275
+ return FILE_CONSTANTS.listMarker.test(line);
276
+ }
277
+
278
+ /*
279
+ * Read a markdown table that starts at one line: a header row, a delimiter row
280
+ * with the same cell count, then every following row that contains a pipe.
281
+ */
282
+ function readAgentNoteMarkdownTable(lines: string[], index: number): AgentNoteMarkdownTable | null {
283
+ const headerLine = lines[index];
284
+ const delimiterLine = lines[index + 1];
285
+ if (delimiterLine === undefined || !headerLine.trim() || !delimiterLine.trim() || isAgentNoteListLine(headerLine)) {
286
+ return null;
287
+ }
288
+
289
+ const header = splitAgentNoteTableRow(headerLine);
290
+ const delimiter = splitAgentNoteTableRow(delimiterLine);
291
+ if (
292
+ (!header.hasPipe && !delimiter.hasPipe) ||
293
+ header.cells.length !== delimiter.cells.length ||
294
+ !delimiter.cells.every((cell) => FILE_CONSTANTS.tableDelimiterCell.test(cell))
295
+ ) {
296
+ return null;
297
+ }
298
+
299
+ const rows: string[][] = [];
300
+ let nextIndex = index + 2;
301
+ while (nextIndex < lines.length) {
302
+ const line = lines[nextIndex];
303
+ if (!line.trim() || isAgentNoteListLine(line)) {
304
+ break;
305
+ }
306
+ const row = splitAgentNoteTableRow(line);
307
+ if (!row.hasPipe) {
308
+ break;
309
+ }
310
+ rows.push(row.cells);
311
+ nextIndex++;
312
+ }
313
+
314
+ return {
315
+ header: header.cells,
316
+ alignments: delimiter.cells.map(getAgentNoteTableAlignment),
317
+ rows,
318
+ nextIndex,
319
+ };
320
+ }
321
+
322
+ /*
323
+ * Return whether a line ends a paragraph because it starts another block.
324
+ */
325
+ function isAgentNoteBlockBoundary(lines: string[], index: number) {
326
+ const line = lines[index];
327
+ return (
328
+ !line.trim() ||
329
+ FILE_CONSTANTS.rule.test(line) ||
330
+ FILE_CONSTANTS.linkDefinition.test(line) ||
331
+ FILE_CONSTANTS.heading.test(line) ||
332
+ isAgentNoteListLine(line) ||
333
+ !!readAgentNoteMarkdownTable(lines, index)
334
+ );
335
+ }
336
+
337
+ /*
338
+ * Shorten text to a maximum length with an ellipsis, preferring a word break.
339
+ */
340
+ function truncateAgentNoteText(text: string, maxLength: number) {
341
+ if (text.length <= maxLength) {
342
+ return text;
343
+ }
344
+ if (maxLength < 2) {
345
+ return '';
346
+ }
347
+
348
+ let cut = text.slice(0, maxLength - 1);
349
+ const lastSpace = cut.lastIndexOf(' ');
350
+ if (lastSpace > maxLength / 2) {
351
+ cut = cut.slice(0, lastSpace);
352
+ }
353
+ return cut.trimEnd() + FILE_CONSTANTS.ellipsis;
354
+ }
355
+
356
+ /*
357
+ * Normalize one table cell's text to the cell length cap.
358
+ */
359
+ function capAgentNoteTableCell(cell: string, issues: AgentNoteMarkdownIssues) {
360
+ const maxLength = AGENT_NOTE_LIMITS.tableCellMaxLength;
361
+ if (cell.length <= maxLength) {
362
+ return cell;
363
+ }
364
+ issues.add('TABLE_CELL_TRUNCATED');
365
+ return truncateAgentNoteText(cell, maxLength);
366
+ }
367
+
368
+ /*
369
+ * Render one table cell list as a normalized markdown row.
370
+ */
371
+ function renderAgentNoteTableRow(cells: string[]) {
372
+ return `| ${cells.join(' | ')} |`;
373
+ }
374
+
375
+ /*
376
+ * Render a table delimiter row for the given column alignments.
377
+ */
378
+ function renderAgentNoteTableDelimiter(alignments: AgentNoteTableAlignment[]) {
379
+ return renderAgentNoteTableRow(
380
+ alignments.map((alignment) =>
381
+ alignment === 'center' ? ':---:' : alignment === 'right' ? '---:' : alignment === 'left' ? ':---' : '---'
382
+ ),
383
+ );
384
+ }
385
+
386
+ /*
387
+ * Normalize one parsed table to the column, row and cell caps, padding or
388
+ * trimming every row to the header width so the table always renders.
389
+ */
390
+ function buildAgentNoteTableBlock(table: AgentNoteMarkdownTable, issues: AgentNoteMarkdownIssues): AgentNoteMarkdownBlock {
391
+ const width = table.header.length;
392
+ const columnCount = Math.min(width, AGENT_NOTE_LIMITS.tableMaxColumns);
393
+ if (width > columnCount) {
394
+ issues.add('TABLE_COLUMNS_TRUNCATED');
395
+ }
396
+ if (table.rows.length > AGENT_NOTE_LIMITS.tableMaxRows) {
397
+ issues.add('TABLE_ROWS_TRUNCATED');
398
+ }
399
+
400
+ const rows = table.rows.slice(0, AGENT_NOTE_LIMITS.tableMaxRows).map((row) => {
401
+ if (row.length !== width) {
402
+ issues.add('TABLE_ROW_WIDTH_FIXED');
403
+ }
404
+ return Array.from({ length: columnCount }, (_, column) => capAgentNoteTableCell(row[column] || '', issues));
405
+ });
406
+ const header = table.header.slice(0, columnCount).map((cell) => capAgentNoteTableCell(cell, issues));
407
+
408
+ return {
409
+ kind: 'table',
410
+ lines: [
411
+ renderAgentNoteTableRow(header),
412
+ renderAgentNoteTableDelimiter(table.alignments.slice(0, columnCount)),
413
+ ...rows.map(renderAgentNoteTableRow),
414
+ ],
415
+ };
416
+ }
417
+
418
+ /*
419
+ * Flatten a heading into one bold paragraph line, or nothing when it is empty.
420
+ */
421
+ function buildAgentNoteHeadingBlock(line: string, issues: AgentNoteMarkdownIssues): AgentNoteMarkdownBlock | null {
422
+ issues.add('HEADING_FLATTENED');
423
+ const text = line.replace(FILE_CONSTANTS.heading, '').replace(FILE_CONSTANTS.headingClose, '').replace(/\*\*/g, '').trim();
424
+ // Removing "**" can join a link or a marker the inline pass broke apart
425
+ const safe = neutralizeAgentNoteMarkers(breakAgentNoteExplicitLinks(text, issues));
426
+ return safe ? { kind: 'paragraph', lines: [`**${safe}**`] } : null;
427
+ }
428
+
429
+ /*
430
+ * Strip block markers left at the start of a list item's text, so item text
431
+ * can never re-parse as a nested list, heading or quote.
432
+ */
433
+ function stripAgentNoteNestedMarkers(text: string, issues: AgentNoteMarkdownIssues) {
434
+ let next = text.trim();
435
+ while (FILE_CONSTANTS.nestedMarker.test(next)) {
436
+ next = next.replace(FILE_CONSTANTS.nestedMarker, '').trim();
437
+ issues.add('BLOCK_FLATTENED');
438
+ }
439
+ return next;
440
+ }
441
+
442
+ /*
443
+ * Return whether a line is a list item that belongs to a list block of the
444
+ * given type: any nested item, or a top-level item of the same type.
445
+ */
446
+ function isAgentNoteListBlockItem(line: string, ordered: boolean) {
447
+ const marker = FILE_CONSTANTS.listMarker.exec(line);
448
+ return !!marker && (marker[1].length >= 2 || !!marker[2] === ordered);
449
+ }
450
+
451
+ /*
452
+ * Read consecutive list items of one type into one flat list block. Nested
453
+ * items are flattened into the block, and indented continuation lines join
454
+ * their item's text.
455
+ */
456
+ function readAgentNoteListBlock(lines: string[], start: number, issues: AgentNoteMarkdownIssues) {
457
+ const first = FILE_CONSTANTS.listMarker.exec(lines[start]);
458
+ const ordered = !!first?.[2];
459
+ const items: string[] = [];
460
+ let index = start;
461
+ while (index < lines.length) {
462
+ const line = lines[index];
463
+ if (!line.trim()) {
464
+ let next = index + 1;
465
+ while (next < lines.length && !lines[next].trim()) {
466
+ next++;
467
+ }
468
+ // A blank line only continues the list when another of its items follows
469
+ if (next < lines.length && isAgentNoteListBlockItem(lines[next], ordered)) {
470
+ index = next;
471
+ continue;
472
+ }
473
+ break;
474
+ }
475
+
476
+ const marker = FILE_CONSTANTS.listMarker.exec(line);
477
+ if (marker) {
478
+ if (!isAgentNoteListBlockItem(line, ordered)) {
479
+ // A top-level list of the other type starts its own block
480
+ break;
481
+ }
482
+ if (marker[1].length >= 2) {
483
+ issues.add('BLOCK_FLATTENED');
484
+ }
485
+ const text = stripAgentNoteNestedMarkers(line.slice(marker[0].length), issues);
486
+ if (text) {
487
+ items.push(text);
488
+ }
489
+ } else if (/^ {2,}\S/.test(line) && items.length) {
490
+ items[items.length - 1] += ` ${line.trim()}`;
491
+ } else {
492
+ break;
493
+ }
494
+ index++;
495
+ }
496
+
497
+ const block: AgentNoteMarkdownBlock = {
498
+ kind: 'list',
499
+ ordered,
500
+ start: ordered ? Number(first?.[2]) : 0,
501
+ items,
502
+ };
503
+ return { block: items.length ? block : null, nextIndex: index };
504
+ }
505
+
506
+ /*
507
+ * Read one paragraph: consecutive lines until a blank line or another block.
508
+ */
509
+ function readAgentNoteParagraphBlock(lines: string[], start: number) {
510
+ const paragraph = [lines[start].trim()];
511
+ let index = start + 1;
512
+ while (index < lines.length && !isAgentNoteBlockBoundary(lines, index)) {
513
+ paragraph.push(lines[index].trim());
514
+ index++;
515
+ }
516
+ const block: AgentNoteMarkdownBlock = { kind: 'paragraph', lines: paragraph };
517
+ return { block, nextIndex: index };
518
+ }
519
+
520
+ /*
521
+ * Append one block, merging it into a directly preceding list of the same
522
+ * type so lists split only by dropped lines read the same on every pass.
523
+ */
524
+ function pushAgentNoteMarkdownBlock(blocks: AgentNoteMarkdownBlock[], block: AgentNoteMarkdownBlock) {
525
+ const previous = blocks[blocks.length - 1];
526
+ if (block.kind === 'list' && previous?.kind === 'list' && previous.ordered === block.ordered) {
527
+ previous.items.push(...block.items);
528
+ } else {
529
+ blocks.push(block);
530
+ }
531
+ }
532
+
533
+ /*
534
+ * Classify sanitized lines into paragraph, list and table blocks. Rules and
535
+ * link definitions are dropped; tables past the table cap are removed.
536
+ */
537
+ function getAgentNoteMarkdownBlocks(lines: string[], issues: AgentNoteMarkdownIssues) {
538
+ const blocks: AgentNoteMarkdownBlock[] = [];
539
+ let tableCount = 0;
540
+ let index = 0;
541
+ while (index < lines.length) {
542
+ const line = lines[index];
543
+ if (!line.trim()) {
544
+ index++;
545
+ continue;
546
+ }
547
+ if (FILE_CONSTANTS.rule.test(line)) {
548
+ issues.add('BLOCK_FLATTENED');
549
+ index++;
550
+ continue;
551
+ }
552
+ if (FILE_CONSTANTS.linkDefinition.test(line)) {
553
+ issues.add('LINK_REMOVED');
554
+ index++;
555
+ continue;
556
+ }
557
+
558
+ const table = readAgentNoteMarkdownTable(lines, index);
559
+ if (table) {
560
+ tableCount++;
561
+ if (tableCount > AGENT_NOTE_LIMITS.tableMaxCount) {
562
+ issues.add('TABLE_REMOVED');
563
+ } else {
564
+ pushAgentNoteMarkdownBlock(blocks, buildAgentNoteTableBlock(table, issues));
565
+ }
566
+ index = table.nextIndex;
567
+ continue;
568
+ }
569
+
570
+ if (FILE_CONSTANTS.heading.test(line)) {
571
+ const heading = buildAgentNoteHeadingBlock(line, issues);
572
+ if (heading) {
573
+ pushAgentNoteMarkdownBlock(blocks, heading);
574
+ }
575
+ index++;
576
+ continue;
577
+ }
578
+
579
+ const read = isAgentNoteListLine(line) ? readAgentNoteListBlock(lines, index, issues) : readAgentNoteParagraphBlock(lines, index);
580
+ if (read.block) {
581
+ pushAgentNoteMarkdownBlock(blocks, read.block);
582
+ }
583
+ index = read.nextIndex;
584
+ }
585
+ return blocks;
586
+ }
587
+
588
+ /*
589
+ * Return a block's markdown lines; list items get "- " or sequential "N. "
590
+ * markers from the list's first number.
591
+ */
592
+ function getAgentNoteMarkdownBlockLines(block: AgentNoteMarkdownBlock) {
593
+ if (block.kind !== 'list') {
594
+ return block.lines;
595
+ }
596
+ return block.items.map((item, index) => (block.ordered ? `${block.start + index}. ${item}` : `- ${item}`));
597
+ }
598
+
599
+ /*
600
+ * Render blocks within the body length cap. Blocks after the cap are dropped;
601
+ * the block that crosses it keeps its whole lines that fit, and a crossing
602
+ * paragraph or list line is shortened at a word break. A table keeps rows only
603
+ * while its header and delimiter fit.
604
+ */
605
+ function renderAgentNoteMarkdownBlocks(blocks: AgentNoteMarkdownBlock[], issues: AgentNoteMarkdownIssues) {
606
+ const maxLength = AGENT_NOTE_LIMITS.bodyMaxLength;
607
+ const rendered: string[] = [];
608
+ let length = 0;
609
+
610
+ for (const block of blocks) {
611
+ const kept: string[] = [];
612
+ let used = length + (rendered.length ? 2 : 0);
613
+ let truncated = false;
614
+
615
+ for (const line of getAgentNoteMarkdownBlockLines(block)) {
616
+ const separator = kept.length ? 1 : 0;
617
+ if (used + separator + line.length <= maxLength) {
618
+ kept.push(line);
619
+ used += separator + line.length;
620
+ continue;
621
+ }
622
+ truncated = true;
623
+ if (block.kind !== 'table') {
624
+ const shortened = truncateAgentNoteText(line, maxLength - used - separator);
625
+ if (shortened && !/^(?:- |\d+\. )?…$/.test(shortened)) {
626
+ kept.push(shortened);
627
+ used += separator + shortened.length;
628
+ }
629
+ }
630
+ break;
631
+ }
632
+
633
+ if (block.kind === 'table' && kept.length < 2) {
634
+ kept.length = 0;
635
+ }
636
+ if (kept.length) {
637
+ rendered.push(kept.join('\n'));
638
+ length = used;
639
+ }
640
+ if (truncated) {
641
+ issues.add('BODY_TRUNCATED');
642
+ break;
643
+ }
644
+ }
645
+ return rendered.join('\n\n');
646
+ }
647
+
648
+ /*
649
+ * Sanitize an AI-written note body to the supported markdown subset:
650
+ * paragraphs, flat bullet or numbered lists, bold and italic emphasis, and
651
+ * GFM tables. Links keep only their label; images, raw HTML, inline code,
652
+ * code fences, headings, quotes, rules and unsupported styles are removed or
653
+ * flattened, and the length and table caps apply. No explicit link and no
654
+ * untrusted-data marker survives. The output is deterministic and idempotent,
655
+ * and every change is reported as an issue.
656
+ */
657
+ export function sanitizeAgentNoteMarkdown(value: unknown): AgentNoteMarkdownSanitizeResult {
658
+ const issues: AgentNoteMarkdownIssues = new Set();
659
+ let source = typeof value === 'string' ? value : '';
660
+ const inputMaxLength = AGENT_NOTE_LIMITS.bodyMaxLength * FILE_CONSTANTS.inputLengthFactor;
661
+ if (source.length > inputMaxLength) {
662
+ source = source.slice(0, inputMaxLength);
663
+ issues.add('BODY_TRUNCATED');
664
+ }
665
+
666
+ const lines = getAgentNoteMarkdownLines(source, issues);
667
+ // Neutralize the rendered body again so no step after the inline pass can
668
+ // leave a marker; it only shortens runs, so the length cap still holds
669
+ const body = neutralizeAgentNoteMarkers(renderAgentNoteMarkdownBlocks(getAgentNoteMarkdownBlocks(lines, issues), issues));
670
+
671
+ return {
672
+ body,
673
+ issues: AGENT_NOTE_MARKDOWN_ISSUE_ENUMS.filter((issue) => issues.has(issue)),
674
+ };
675
+ }
676
+
677
+ /*
678
+ * Sanitize an AI-written headline to one plain-text line within the headline
679
+ * cap: markdown, links, HTML and line breaks are removed.
680
+ */
681
+ export function sanitizeAgentNoteHeadline(value: unknown): string {
682
+ const issues: AgentNoteMarkdownIssues = new Set();
683
+ const text = sanitizeAgentNoteInlineText(
684
+ normalizeAgentNoteCharacters(typeof value === 'string' ? value : '')
685
+ .replace(FILE_CONSTANTS.htmlComment, '')
686
+ .replace(/\s+/g, ' '),
687
+ issues,
688
+ )
689
+ .replace(/[*~]/g, '')
690
+ .trim()
691
+ .replace(/^(?:#{1,6}|>|[-+•])\s+/, '')
692
+ .trim()
693
+ // Removing emphasis can join a link the inline pass broke apart
694
+ .replace(FILE_CONSTANTS.linkDestinationStart, '] ');
695
+
696
+ // Neutralize after every removal so no marker can be rebuilt
697
+ return truncateAgentNoteText(neutralizeAgentNoteMarkers(text), AGENT_NOTE_LIMITS.headlineMaxLength);
698
+ }
699
+
700
+ /*
701
+ * Turn negative zero into zero so a parsed answer never reads as -0.
702
+ */
703
+ function normalizeAgentNoteZero(value: number) {
704
+ return Object.is(value, -0) ? 0 : value;
705
+ }
706
+
707
+ /*
708
+ * Return the prefix and suffix a decorated number was written with, ignoring
709
+ * accounting parentheses.
710
+ */
711
+ function getAgentNoteNumberAffixes(text: string) {
712
+ const inner = text.replace(/^\((.*)\)$/s, '$1').trim();
713
+ return {
714
+ prefix: FILE_CONSTANTS.numberDecorationPrefix.exec(inner)?.[1] || null,
715
+ suffix: FILE_CONSTANTS.numberDecorationSuffix.exec(inner)?.[1] || null,
716
+ };
717
+ }
718
+
719
+ /*
720
+ * Return whether a parsed decorated number has an ambiguous magnitude: an
721
+ * upper-case "M" or "T" suffix reads as millions or trillions, not meters or
722
+ * tons ("1.2M"), and a currency with a unit suffix is a magnitude or nonsense
723
+ * ("$1.2M", "€2.5m", "$5 kg").
724
+ */
725
+ function isAgentNoteAmbiguousNumberText(text: string) {
726
+ const { prefix, suffix } = getAgentNoteNumberAffixes(text);
727
+ if (!suffix || suffix === '%') {
728
+ return false;
729
+ }
730
+ if (suffix === 'M' || suffix === 'T') {
731
+ return true;
732
+ }
733
+ // A parsed prefix is always a currency symbol or code
734
+ return !!prefix && !FILE_CONSTANTS.currencyCodes.has(suffix.toUpperCase());
735
+ }
736
+
737
+ /*
738
+ * Return the currency, percent sign or unit a decorated number was written
739
+ * with: currency codes upper-cased, units lower-cased.
740
+ */
741
+ function getAgentNoteNumberDecoration(text: string) {
742
+ const { prefix, suffix } = getAgentNoteNumberAffixes(text);
743
+ const decorations = [prefix, suffix]
744
+ .filter((decoration): decoration is string => !!decoration)
745
+ .map((decoration) =>
746
+ FILE_CONSTANTS.currencyCodes.has(decoration.toUpperCase()) ? decoration.toUpperCase() : decoration.toLowerCase()
747
+ );
748
+ return decorations.length ? decorations.join(' ') : null;
749
+ }
750
+
751
+ /*
752
+ * Return an answer's text without its thousands suffix ("10k" -> "10",
753
+ * "(2K)" -> "(2)"), or null when it has none.
754
+ */
755
+ function getAgentNoteThousandsText(text: string) {
756
+ const match = FILE_CONSTANTS.thousandsSuffix.exec(text);
757
+ return match ? `${match[1]}${match[2]}` : null;
758
+ }
759
+
760
+ /*
761
+ * Leniently read one answer as a number: currency, grouping, accounting
762
+ * parentheses, percentages and known units are accepted ("$74.97" -> 74.97),
763
+ * and a "k" or "K" suffix reads as thousands ("10k" -> 10000, "1.5K" -> 1500),
764
+ * while "NA", "n/a", ranges, fractions, booleans, free text and ambiguous
765
+ * magnitudes ("$1.2M", "1.2M", "$5 kg") are non-numeric.
766
+ */
767
+ export function parseAgentNoteAnswerNumber(value: unknown): AgentNoteAnswerNumber {
768
+ const nonNumeric: AgentNoteAnswerNumber = {
769
+ numeric: false,
770
+ value: null,
771
+ decoration: null,
772
+ };
773
+ if (typeof value === 'number') {
774
+ return Number.isFinite(value)
775
+ ? {
776
+ numeric: true,
777
+ value: normalizeAgentNoteZero(value),
778
+ decoration: null,
779
+ }
780
+ : nonNumeric;
781
+ }
782
+ if (typeof value !== 'string') {
783
+ return nonNumeric;
784
+ }
785
+
786
+ const text = value.replace(FILE_CONSTANTS.spaceCharacters, ' ').replace(FILE_CONSTANTS.minusCharacters, '-').trim();
787
+ const thousands = getAgentNoteThousandsText(text);
788
+ const source = thousands ?? text;
789
+ const number = source ? parseDecoratedExpressionNumber(source) : null;
790
+ if (number === null || isAgentNoteAmbiguousNumberText(source)) {
791
+ return nonNumeric;
792
+ }
793
+ // Decimal multiplication keeps "1.1k" at exactly 1100
794
+ const scaled = thousands === null ? number : calculateExpressionDecimal(number, '*', 1000);
795
+ if (scaled === null || !Number.isFinite(scaled)) {
796
+ return nonNumeric;
797
+ }
798
+ return {
799
+ numeric: true,
800
+ value: normalizeAgentNoteZero(scaled),
801
+ decoration: getAgentNoteNumberDecoration(source),
802
+ };
803
+ }
804
+
805
+ /*
806
+ * Convert one activity timestamp to epoch milliseconds, or null when invalid.
807
+ */
808
+ function getAgentNoteActivityTime(value: AgentNoteActivitySource[keyof AgentNoteActivitySource]) {
809
+ if (value === null || value === undefined || value === '') {
810
+ return null;
811
+ }
812
+ const time = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : Date.parse(value);
813
+ return Number.isFinite(time) ? time : null;
814
+ }
815
+
816
+ /*
817
+ * Return a note's newest activity: the latest of its data change, last read,
818
+ * retention and focus change times, ignoring missing ones (SQL GREATEST).
819
+ */
820
+ export function getAgentNoteActivityAt(note: AgentNoteActivitySource): Date | null {
821
+ let latest: number | null = null;
822
+ for (const value of [note.dataChangedAt, note.lastReadAt, note.retainedAt, note.focusUpdatedAt]) {
823
+ const time = getAgentNoteActivityTime(value);
824
+ if (time !== null && (latest === null || time > latest)) {
825
+ latest = time;
826
+ }
827
+ }
828
+ return latest === null ? null : new Date(latest);
829
+ }
830
+
831
+ /*
832
+ * Return whether a viewer may read the source behind a note kind for editing:
833
+ * product reads for campaign forms
834
+ * and field docs, product and inbox reads for campaign email, and general
835
+ * data reads for insights. Unknown kinds are never readable.
836
+ */
837
+ export function canViewerReadAgentNoteSourceKind(kind: unknown, aclChecker: AgentNoteACLChecker): boolean {
838
+ if (!AGENT_NOTE_KIND_ENUMS.includes(kind as AgentNoteKindEnum)) {
839
+ return false;
840
+ }
841
+ const permissions = FILE_CONSTANTS.sourcePermissionsByKind[kind as AgentNoteKindEnum];
842
+ return permissions.every(([check, requiredPermission]) => aclChecker(check, requiredPermission) === true);
843
+ }
844
+
845
+ /*
846
+ * Return note kinds whose underlying sources the viewer can read for editing.
847
+ */
848
+ export function getViewerReadableAgentNoteSourceKinds(aclChecker: AgentNoteACLChecker): AgentNoteKindEnum[] {
849
+ return AGENT_NOTE_KIND_ENUMS.filter((kind) => canViewerReadAgentNoteSourceKind(kind, aclChecker));
850
+ }