@supa-media/tex-contract 0.0.0-stage → 0.2.7

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 (212) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/package.json +16 -4
  4. package/texContract/aboutLines.cjs +117 -0
  5. package/texContract/aboutLines.d.cts +14 -0
  6. package/texContract/aboutNoteLimits.cjs +41 -0
  7. package/texContract/aboutNoteLimits.d.cts +5 -0
  8. package/texContract/actionManual.cjs +104 -0
  9. package/texContract/activityHint.cjs +40 -0
  10. package/texContract/activityHint.d.cts +4 -0
  11. package/texContract/asks.cjs +16 -0
  12. package/texContract/asks.d.cts +6 -0
  13. package/texContract/asksToFile.cjs +20 -0
  14. package/texContract/asksToFile.d.cts +2 -0
  15. package/texContract/attention.cjs +138 -0
  16. package/texContract/attention.d.cts +20 -0
  17. package/texContract/browserHandback.cjs +13 -0
  18. package/texContract/browserHandback.d.cts +3 -0
  19. package/texContract/browserOwner.cjs +31 -0
  20. package/texContract/browserOwner.d.cts +2 -0
  21. package/texContract/bytes.cjs +12 -0
  22. package/texContract/chatHistoryPath.cjs +38 -0
  23. package/texContract/chatHistoryPath.d.cts +5 -0
  24. package/texContract/chatLedger.cjs +91 -0
  25. package/texContract/chatLedger.d.cts +21 -0
  26. package/texContract/computerTool.cjs +102 -0
  27. package/texContract/computerTool.d.cts +16 -0
  28. package/texContract/consentYes.cjs +22 -0
  29. package/texContract/consentYes.d.cts +5 -0
  30. package/texContract/contextGateway.cjs +52 -0
  31. package/texContract/contextGateway.d.cts +19 -0
  32. package/texContract/deskEligible.cjs +20 -0
  33. package/texContract/deskEligible.d.cts +3 -0
  34. package/texContract/downloads.cjs +129 -0
  35. package/texContract/downloads.d.cts +15 -0
  36. package/texContract/egressLedger.cjs +114 -0
  37. package/texContract/egressLedger.d.cts +14 -0
  38. package/texContract/emailRead.cjs +38 -0
  39. package/texContract/emailRead.d.cts +5 -0
  40. package/texContract/eventWords.cjs +35 -0
  41. package/texContract/eventWords.d.cts +4 -0
  42. package/texContract/fileParts.cjs +43 -0
  43. package/texContract/fileParts.d.cts +6 -0
  44. package/texContract/fileTables.cjs +243 -0
  45. package/texContract/fileWords.cjs +169 -0
  46. package/texContract/folded.cjs +16 -0
  47. package/texContract/folded.d.cts +3 -0
  48. package/texContract/googleAiAccess.cjs +12 -0
  49. package/texContract/googleAiAccess.d.cts +2 -0
  50. package/texContract/graphWires.cjs +18 -0
  51. package/texContract/graphWires.d.cts +5 -0
  52. package/texContract/groupSession.cjs +28 -0
  53. package/texContract/groupSession.d.cts +7 -0
  54. package/texContract/guestNames.cjs +136 -0
  55. package/texContract/guestNames.d.cts +35 -0
  56. package/texContract/heard.cjs +19 -0
  57. package/texContract/heard.d.cts +4 -0
  58. package/texContract/heldOffer.cjs +57 -0
  59. package/texContract/heldOffer.d.cts +8 -0
  60. package/texContract/helperCallers.cjs +29 -0
  61. package/texContract/helperCallers.d.cts +4 -0
  62. package/texContract/identity.cjs +179 -0
  63. package/texContract/identity.d.cts +8 -0
  64. package/texContract/jobLogEntries.cjs +93 -0
  65. package/texContract/jobLogEntries.d.cts +12 -0
  66. package/texContract/judgedActions.cjs +20 -0
  67. package/texContract/judgedActions.d.cts +4 -0
  68. package/texContract/labSandboxGate.cjs +63 -0
  69. package/texContract/labSandboxGate.d.cts +9 -0
  70. package/texContract/ledgerReadChars.cjs +4 -0
  71. package/texContract/ledgerReadChars.d.cts +3 -0
  72. package/texContract/mailCheck.cjs +90 -0
  73. package/texContract/mailCheck.d.cts +12 -0
  74. package/texContract/mailEntries.cjs +64 -0
  75. package/texContract/mailEntries.d.cts +13 -0
  76. package/texContract/mailHealth.cjs +60 -0
  77. package/texContract/mailHealth.d.cts +10 -0
  78. package/texContract/notePath.cjs +99 -0
  79. package/texContract/notePath.d.cts +4 -0
  80. package/texContract/noteRunFacts.cjs +136 -0
  81. package/texContract/noteRunFacts.d.cts +32 -0
  82. package/texContract/objectEtag.cjs +84 -0
  83. package/texContract/objectEtag.d.cts +4 -0
  84. package/texContract/objectPlace.cjs +32 -0
  85. package/texContract/objectPlace.d.cts +5 -0
  86. package/texContract/pageJobs.cjs +226 -0
  87. package/texContract/pageJobs.d.cts +13 -0
  88. package/texContract/pdfLinks.cjs +135 -0
  89. package/texContract/pdfLinks.d.cts +4 -0
  90. package/texContract/personHub.cjs +38 -0
  91. package/texContract/personHub.d.cts +5 -0
  92. package/texContract/personNameText.cjs +18 -0
  93. package/texContract/personNameText.d.cts +3 -0
  94. package/texContract/pinnedContext.cjs +12 -0
  95. package/texContract/pinnedContext.d.cts +3 -0
  96. package/texContract/quietHoursWindow.cjs +36 -0
  97. package/texContract/quietHoursWindow.d.cts +3 -0
  98. package/texContract/scopeClamp.cjs +117 -0
  99. package/texContract/scopeClamp.d.cts +5 -0
  100. package/texContract/scopes.cjs +29 -0
  101. package/texContract/scopes.d.cts +7 -0
  102. package/texContract/searchSettings.cjs +54 -0
  103. package/texContract/searchSettings.d.cts +6 -0
  104. package/texContract/settingHabits.cjs +87 -0
  105. package/texContract/settingHabits.d.cts +20 -0
  106. package/texContract/settingsNotes.cjs +217 -0
  107. package/texContract/settingsNotes.d.cts +26 -0
  108. package/texContract/shownEmail.cjs +181 -0
  109. package/texContract/texClients.cjs +53 -0
  110. package/texContract/texClients.d.cts +12 -0
  111. package/texContract/texGraph.cjs +593 -0
  112. package/texContract/texGraph.d.cts +55 -0
  113. package/texContract/texKeys.cjs +100 -0
  114. package/texContract/texKeys.d.cts +13 -0
  115. package/texContract/texOwnSources.cjs +9 -0
  116. package/texContract/texOwnSources.d.cts +3 -0
  117. package/texContract/texStoreNames.cjs +26 -0
  118. package/texContract/texStoreNames.d.cts +12 -0
  119. package/texContract/texStoreWire.cjs +306 -0
  120. package/texContract/texStoreWire.d.cts +32 -0
  121. package/texContract/threadsFold.cjs +75 -0
  122. package/texContract/threadsFold.d.cts +22 -0
  123. package/texContract/toolActions.cjs +253 -0
  124. package/texContract/toolCatalog.cjs +49 -0
  125. package/texContract/toolCatalog.generated.json +90 -0
  126. package/texContract/toolContract.cjs +52 -0
  127. package/texContract/toolContract.d.cts +12 -0
  128. package/texContract/toolShapes.cjs +14 -0
  129. package/texContract/transcription.cjs +101 -0
  130. package/texContract/transcription.d.cts +3 -0
  131. package/texContract/treeJobs.cjs +31 -0
  132. package/texContract/treeJobs.d.cts +3 -0
  133. package/texContract/turnSession.cjs +90 -0
  134. package/texContract/turnSession.d.cts +19 -0
  135. package/texContract/turnWords.cjs +90 -0
  136. package/texContract/turnWords.d.cts +9 -0
  137. package/texContract/uploadImages.cjs +131 -0
  138. package/texContract/uploadImages.d.cts +13 -0
  139. package/texContract/v2Names.cjs +41 -0
  140. package/texContract/v2SearchFetch.cjs +316 -0
  141. package/texContract/v2Translate.cjs +123 -0
  142. package/texContract/vaultTools.cjs +112 -0
  143. package/texContract/vaultTools.d.cts +15 -0
  144. package/texContract/yesWords.cjs +91 -0
  145. package/texShared/argumentCoercion.cjs +93 -0
  146. package/texShared/cellComments.cjs +122 -0
  147. package/texShared/cellComments.d.cts +21 -0
  148. package/texShared/comments.cjs +586 -0
  149. package/texShared/comments.d.cts +115 -0
  150. package/texShared/contentTypes.cjs +85 -0
  151. package/texShared/fileKinds.cjs +123 -0
  152. package/texShared/flags.cjs +124 -0
  153. package/texShared/flags.d.cts +21 -0
  154. package/texShared/folderJobInfo.cjs +301 -0
  155. package/texShared/folderJobInfo.d.cts +40 -0
  156. package/texShared/folderRoles.cjs +512 -0
  157. package/texShared/folderRoles.d.cts +73 -0
  158. package/texShared/githubOidc.ts +98 -0
  159. package/texShared/groupRunQuestions.cjs +98 -0
  160. package/texShared/groupRunQuestions.d.cts +4 -0
  161. package/texShared/inboxFolders.cjs +49 -0
  162. package/texShared/inboxFolders.d.cts +5 -0
  163. package/texShared/ink/drawing.cjs +474 -0
  164. package/texShared/ink/texFigure.cjs +252 -0
  165. package/texShared/ink/texFigure.d.cts +36 -0
  166. package/texShared/ink/texPoses.cjs +180 -0
  167. package/texShared/ink/texPoses.d.cts +20 -0
  168. package/texShared/jobPartEnd.cjs +133 -0
  169. package/texShared/jobPartEnd.d.cts +13 -0
  170. package/texShared/jobResume.cjs +31 -0
  171. package/texShared/jobResume.d.cts +5 -0
  172. package/texShared/jobSplit.cjs +90 -0
  173. package/texShared/jobSplit.d.cts +6 -0
  174. package/texShared/jobStart.cjs +56 -0
  175. package/texShared/jobStart.d.cts +9 -0
  176. package/texShared/mail.cjs +400 -0
  177. package/texShared/mail.d.cts +56 -0
  178. package/texShared/messageAnchors.cjs +38 -0
  179. package/texShared/models/aiKeys.cjs +137 -0
  180. package/texShared/models/aiKeys.d.cts +42 -0
  181. package/texShared/models/aiKeys.json +56 -0
  182. package/texShared/models/creditRest.cjs +269 -0
  183. package/texShared/models/promptBudget.cjs +295 -0
  184. package/texShared/models/promptSections.cjs +29 -0
  185. package/texShared/noteAppLink.cjs +23 -0
  186. package/texShared/notePreview.cjs +219 -0
  187. package/texShared/notePreview.d.cts +21 -0
  188. package/texShared/pages/blocks.cjs +215 -0
  189. package/texShared/pages/cover.cjs +164 -0
  190. package/texShared/pages/css.cjs +181 -0
  191. package/texShared/pages/cssBlocks.cjs +264 -0
  192. package/texShared/pages/draw.cjs +212 -0
  193. package/texShared/pages/drawRich.cjs +232 -0
  194. package/texShared/pages/html.cjs +168 -0
  195. package/texShared/pages/inline.cjs +251 -0
  196. package/texShared/pages/layout.cjs +76 -0
  197. package/texShared/pages/parse.cjs +418 -0
  198. package/texShared/pages/render.cjs +200 -0
  199. package/texShared/pages/skill.cjs +147 -0
  200. package/texShared/pages/skill.d.cts +5 -0
  201. package/texShared/pages/templates.cjs +336 -0
  202. package/texShared/r2Store.cjs +163 -0
  203. package/texShared/remoteImage.cjs +177 -0
  204. package/texShared/routines.cjs +656 -0
  205. package/texShared/routines.d.cts +86 -0
  206. package/texShared/servedListing.cjs +250 -0
  207. package/texShared/servedListing.d.cts +17 -0
  208. package/texShared/sheetCsv.cjs +566 -0
  209. package/texShared/sheetCsv.d.cts +91 -0
  210. package/texShared/storageLayout.cjs +88 -0
  211. package/texShared/storeKeys.cjs +144 -0
  212. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,295 @@
1
+ /**
2
+ * EVERY HAIKU CALL STAYS UNDER THE PRICE CLIFF, AND KEEPS ITS CACHE.
3
+ *
4
+ * Haiku 5.5 charges five times for input past 100,000 tokens. The history
5
+ * caps (`weekHistory.js`) bound the week's transcript, and nothing else: a
6
+ * 1:1 stretch replays tool results whole (`stretch.js`, up to 64,000
7
+ * characters each, 60 of them). Those sit outside the caps, so a busy thread
8
+ * still left the worker at about 126,000 tokens after the caps shipped
9
+ * (gateway analytics, 2026-11-17, setups 54bad9c2e0f0 and d51546d21963).
10
+ *
11
+ * This trims the body that is about to be sent. Tool results outside the
12
+ * newest message go first (the model can call them again), then the oldest
13
+ * history text, and only then a tool result in the newest message. The
14
+ * system prompt and the tool list stay until nothing else will do. Images
15
+ * are counted as pictures, not as their base64, so a photo is not mistaken
16
+ * for a novel.
17
+ *
18
+ * It trims in steps, so the cache keeps reading. Recomputing the cut every
19
+ * round from the untrimmed body moved the stub line by one message per text
20
+ * and rewrote everything after it: 368 of 1,047 front-door rounds,
21
+ * 2026-11-19 to 11-24, were trimmed, and each wrote its prefix again. Now a
22
+ * body over the budget is cut to a step below it (`TRIM_STEP`), and the cut is
23
+ * worked out on the shortest run of messages that put the body in its step,
24
+ * so a newer message leaves it exactly as it was until the body has grown by
25
+ * about a step more. See docs/decisions/texting-assistant/week-history.md.
26
+ *
27
+ * Shared by Tex (`aiGateway.js`) and Context's own model client
28
+ * (`apps/mcp/src/models/client.js`): every Haiku call either side makes is fitted the same way.
29
+ */
30
+
31
+ /**
32
+ * The billed-token ceiling. A call estimated here bills at or under it on 9 rounds in 10, and under
33
+ * the 100k cliff (also the `clear_tool_uses` trigger in `aiGateway.js`) on 361 of the 368 logged
34
+ * rounds whose ratio is known (see `TEXT_CHARS_PER_TOKEN`).
35
+ */
36
+ const HAIKU_INPUT_BUDGET = 96_000;
37
+
38
+ /**
39
+ * Measured against billed tokens (input + cache read + cache write), production front-door rounds
40
+ * 2026-11-19 6 PM to 11-24 6 PM ET: at 3.5 the billed count was 1.26 times the estimate at the
41
+ * median and 1.30 at p90 (368 trimmed rounds, whose estimate is logged; the 135 untrimmed rounds
42
+ * billed over 96,000 agree, bounded at 1.08 to 1.35). 3.5 / 1.302 = 2.69, rounded down, so an
43
+ * estimate at the budget bills at or under it at p90.
44
+ */
45
+ const TEXT_CHARS_PER_TOKEN = 2.68;
46
+
47
+ /**
48
+ * How far under the budget a trimmed body is cut, in estimated tokens. A front-door round grew by
49
+ * 724 billed tokens at the median and 6,770 at p90 over the same rounds, so a step outlasts
50
+ * about twenty ordinary rounds and two of the largest before the cut moves again.
51
+ */
52
+ const TRIM_STEP = 16_000;
53
+
54
+ /** A picture or a PDF page, counted once. The base64 is not tokens. */
55
+ const IMAGE_TOKENS = 1_600;
56
+
57
+ const LEFT_OUT = "(Left out for length. Call it again if you need it.)";
58
+
59
+ /** An older turn dropped whole, once its tool results were not enough. */
60
+ const EARLIER = "(Earlier turn left out for length.)";
61
+
62
+ const textTokens = (text) => Math.ceil(String(text ?? "").length / TEXT_CHARS_PER_TOKEN);
63
+
64
+ function blockTokens(block) {
65
+ if (typeof block === "string") return textTokens(block);
66
+ if (!block || typeof block !== "object") return 0;
67
+ // A text document is billed as its words; a picture or a PDF as a picture.
68
+ if (block.type === "document" && block.source?.type === "text") return textTokens(block.source.data);
69
+ if (block.type === "image" || block.type === "document") return IMAGE_TOKENS;
70
+ if (block.type === "tool_result") {
71
+ if (typeof block.content === "string") return textTokens(block.content);
72
+ if (Array.isArray(block.content)) return block.content.reduce((sum, part) => sum + blockTokens(part), 0);
73
+ }
74
+ if (typeof block.text === "string") return textTokens(block.text);
75
+ return textTokens(JSON.stringify(block));
76
+ }
77
+
78
+ function messageTokens(message) {
79
+ if (!message) return 0;
80
+ if (typeof message.content === "string") return textTokens(message.content);
81
+ if (Array.isArray(message.content)) return message.content.reduce((sum, block) => sum + blockTokens(block), 0);
82
+ return 0;
83
+ }
84
+
85
+ /** Tokens in one gateway body: system, tools, and messages. */
86
+ function estimateBodyTokens(body) {
87
+ const system = Array.isArray(body?.system) ? body.system.reduce((sum, block) => sum + blockTokens(block), 0) : textTokens(body?.system);
88
+ const tools = textTokens(JSON.stringify(body?.tools ?? []));
89
+ const messages = (body?.messages ?? []).reduce((sum, message) => sum + messageTokens(message), 0);
90
+ return system + tools + messages;
91
+ }
92
+
93
+ function resultText(block) {
94
+ if (typeof block?.content === "string") return block.content;
95
+ if (Array.isArray(block?.content)) return block.content.filter((part) => part?.type === "text").map((part) => part.text).join("");
96
+ return "";
97
+ }
98
+
99
+ /** The oldest tool result before message `end` that still holds more than the stub, or null. */
100
+ function oldestResult(messages, end) {
101
+ for (let i = 0; i < end; i += 1) {
102
+ const content = messages[i]?.content;
103
+ if (!Array.isArray(content)) continue;
104
+ for (let j = 0; j < content.length; j += 1) {
105
+ const block = content[j];
106
+ if (block?.type === "tool_result" && resultText(block) !== LEFT_OUT) return { message: i, block: j };
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+
112
+ function stubResult(block) {
113
+ return { ...block, content: LEFT_OUT };
114
+ }
115
+
116
+ /** The oldest history text before message `end`, or null. The turn's own messages, from `end` on, stay until nothing else will do. */
117
+ function oldestHistory(messages, end) {
118
+ for (let i = 0; i < end; i += 1) {
119
+ const message = messages[i];
120
+ if (typeof message?.content === "string" && message.content !== EARLIER && message.content.length > EARLIER.length) return { message: i, kind: "string" };
121
+ if (!Array.isArray(message?.content)) continue;
122
+ for (let j = 0; j < message.content.length; j += 1) {
123
+ const block = message.content[j];
124
+ if (block?.type === "text" && typeof block.text === "string" && block.text !== EARLIER && block.text.length > EARLIER.length) return { message: i, block: j, kind: "text" };
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+
130
+ function stubHistory(messages, where) {
131
+ const message = messages[where.message];
132
+ if (where.kind === "string") message.content = EARLIER;
133
+ else message.content[where.block] = { ...message.content[where.block], text: EARLIER };
134
+ }
135
+
136
+ /**
137
+ * Halve the longest remaining text, keeping its end. Used only when stubbing
138
+ * tool results and older turns still leaves the call over the cliff, which
139
+ * is a system prompt or a newest message bigger than the budget on its own.
140
+ * Messages from `end` on are left whole. Returns false when nothing long is
141
+ * left, so the loop stops.
142
+ */
143
+ function clipLargest(body, end = Infinity) {
144
+ const best = largestText(body, end);
145
+ if (!best || best.text.length <= EARLIER.length + 1) return false;
146
+ const tail = Math.max(0, Math.floor(best.text.length / 2) - EARLIER.length - 1);
147
+ const clipped = tail === 0 ? EARLIER : `${EARLIER}\n${best.text.slice(-tail)}`;
148
+ if (clipped.length >= best.text.length) return false;
149
+ best.set(clipped);
150
+ return true;
151
+ }
152
+
153
+ /** The longest text `clipLargest` may clip, as { text, set }, or null. */
154
+ function largestText(body, end = Infinity) {
155
+ let best = null;
156
+ const offer = (text, set) => {
157
+ if (typeof text === "string" && text.length > (best?.text.length ?? EARLIER.length + 1)) best = { text, set };
158
+ };
159
+ if (typeof body.system === "string") offer(body.system, (value) => { body.system = value; });
160
+ else if (Array.isArray(body.system)) {
161
+ body.system.forEach((block, index) => {
162
+ if (typeof block?.text === "string") offer(block.text, (value) => { body.system[index] = { ...block, text: value }; });
163
+ });
164
+ }
165
+ (body.tools ?? []).forEach((tool, index) => {
166
+ if (typeof tool?.description === "string") offer(tool.description, (value) => { body.tools[index] = { ...tool, description: value }; });
167
+ });
168
+ (body.messages ?? []).forEach((message, index) => {
169
+ if (index >= end) return; // the turn's own messages, when the cut keeps them
170
+ if (typeof message?.content === "string") offer(message.content, (value) => { body.messages[index] = { ...message, content: value }; });
171
+ else if (Array.isArray(message?.content)) {
172
+ message.content.forEach((block, blockIndex) => {
173
+ if (typeof block?.text === "string") offer(block.text, (value) => { message.content[blockIndex] = { ...block, text: value }; });
174
+ if (block?.type === "tool_result" && typeof block.content === "string") offer(block.content, (value) => { message.content[blockIndex] = { ...block, content: value }; });
175
+ });
176
+ }
177
+ });
178
+ return best;
179
+ }
180
+
181
+ /** The longest tool result that still holds more than the stub, as { message, block, length }, or null. */
182
+ function largestResult(messages) {
183
+ let best = null;
184
+ messages.forEach((message, i) => {
185
+ if (!Array.isArray(message?.content)) return;
186
+ message.content.forEach((block, j) => {
187
+ const text = block?.type === "tool_result" ? resultText(block) : null;
188
+ if (text !== null && text !== LEFT_OUT && text.length > (best?.length ?? 0)) best = { message: i, block: j, length: text.length };
189
+ });
190
+ });
191
+ return best;
192
+ }
193
+
194
+ const messageList = (body) => (Array.isArray(body?.messages) ? body.messages : []);
195
+
196
+ /**
197
+ * Stubs `body` in the fixed order until its estimate is at or under `target`. `older`: tool results
198
+ * before message `keepFrom`, then history text before it. `newest`: a tool result anywhere, oldest
199
+ * first. `clip`: the longest text, last of all, outside messages from `clipFrom` on. `keepFrom`
200
+ * defaults to the body's last message. Returns how many cuts it made.
201
+ */
202
+ function cut(body, target, { older = true, newest = true, clip = true, keepFrom, clipFrom = Infinity } = {}) {
203
+ const messages = messageList(body);
204
+ const end = Math.max(0, Math.min(keepFrom ?? messages.length - 1, messages.length));
205
+ let shed = 0;
206
+ while (estimateBodyTokens(body) > target) {
207
+ const result = older ? oldestResult(messages, end) : null;
208
+ const history = older && !result ? oldestHistory(messages, end) : null;
209
+ const any = newest && !result && !history ? oldestResult(messages, messages.length) : null;
210
+ const where = result ?? any;
211
+ if (where) messages[where.message].content[where.block] = stubResult(messages[where.message].content[where.block]);
212
+ else if (history) stubHistory(messages, history);
213
+ else if (!clip || !clipLargest(body, clipFrom)) break;
214
+ shed += 1;
215
+ }
216
+ return shed;
217
+ }
218
+
219
+ /** Which step of `TRIM_STEP` over the budget an estimate is in; 0 under it. */
220
+ const stepOf = (tokens) => Math.max(0, Math.ceil((tokens - HAIKU_INPUT_BUDGET) / TRIM_STEP));
221
+
222
+ /**
223
+ * `body` trimmed until a Haiku call stays under `HAIKU_INPUT_BUDGET`.
224
+ * Tool results outside the newest message go first, then older history
225
+ * text, and only then a tool result in the newest message. The turn, from
226
+ * message `turnFrom` (the person's ask) on, is never older history, however
227
+ * many tool rounds followed it; with no `turnFrom` it is the newest message.
228
+ * Returns the same object when it already fits.
229
+ *
230
+ * A body `step` steps over the budget sheds `step` whole steps, so it lands a
231
+ * step under, and grows back to the budget before the next cut. The cut is
232
+ * made on the shortest leading run of messages already in that step (the
233
+ * "frame"), the newest of them standing in for the newest message; the
234
+ * messages after it go as they came. A newer text or tool round in the same
235
+ * step finds the same frame and makes the same cut, byte for byte. Only when
236
+ * stubbing whole older units cannot reach the step does the frame's newest
237
+ * tool result go, and then a clip, and only on the frame.
238
+ */
239
+ function fitHaikuBody(body, { turnFrom } = {}) {
240
+ const before = estimateBodyTokens(body);
241
+ if (before <= HAIKU_INPUT_BUDGET) return { body, before, after: before, shed: 0 };
242
+ const next = JSON.parse(JSON.stringify(body));
243
+ const messages = messageList(next);
244
+ const step = stepOf(before);
245
+ const frame = { ...next, messages: [] };
246
+ let framed = estimateBodyTokens(frame);
247
+ for (const message of messages) {
248
+ if (stepOf(framed) >= step) break;
249
+ frame.messages.push(message);
250
+ framed += messageTokens(message);
251
+ }
252
+ const rest = messages.slice(frame.messages.length);
253
+ const restTokens = before - framed;
254
+ const hasNewest = rest.length === 0; // the frame's last message is the call's newest
255
+ // The turn: from the person's ask (`turnFrom`, the wire index just past the cached history,
256
+ // `aiGateway.js`) to the end, or the newest message alone when the caller has no history. It is
257
+ // never older history: a tool round that pushed the body into a new step once stubbed the ask
258
+ // itself, and the model answered "I only see placeholders" (Lab test chats, 2026-11-26).
259
+ const start = Number.isInteger(turnFrom) && turnFrom >= 0 && turnFrom < messages.length ? turnFrom : messages.length - 1;
260
+ const lastOfFrame = frame.messages.length - 1;
261
+ const keepFrom = Math.min(start, lastOfFrame);
262
+ const low = framed - step * TRIM_STEP;
263
+ // Whole older units, down to a step under: the cut that holds while the body grows. The frame's
264
+ // last message is kept as if it were the newest, whatever follows it, so a newer message cannot
265
+ // change this cut.
266
+ let shed = cut(frame, low, { newest: false, clip: false, keepFrom });
267
+ const over = () => estimateBodyTokens(frame) + restTokens > HAIKU_INPUT_BUDGET;
268
+ // Still over, and newer messages follow the frame with its last message before the ask: that
269
+ // message is older history to them, down to the step.
270
+ const lastIsOlder = !hasNewest && start > lastOfFrame;
271
+ if (over() && lastIsOlder) shed += cut(frame, low, { newest: false, clip: false, keepFrom: frame.messages.length });
272
+ // Then, of a clip of the system prompt, the tool list or older history, and a tool result of this
273
+ // turn, whichever is longer, down to the step so the same clip holds next round; a tool result goes
274
+ // only while the call is over the budget. The turn's words are never clipped here: a lookup of a
275
+ // few thousand characters is no reason to drop it while the system prompt is the overflow.
276
+ if (over()) {
277
+ while (estimateBodyTokens(frame) > low) {
278
+ const clip = largestText(frame, start);
279
+ const result = over() ? largestResult(frame.messages) : null;
280
+ if (result && (!clip || result.length >= clip.text.length)) {
281
+ frame.messages[result.message].content[result.block] = stubResult(frame.messages[result.message].content[result.block]);
282
+ } else if (!clip || !clipLargest(frame, start)) break;
283
+ shed += 1;
284
+ }
285
+ }
286
+ // Last of all, a clip of anything.
287
+ if (over()) shed += cut(frame, HAIKU_INPUT_BUDGET, { older: false, newest: false });
288
+ const fitted = { ...frame, messages: [...frame.messages, ...rest] };
289
+ // A frame too small to give a step (nothing left to stub or clip in it): the whole body, as before,
290
+ // the turn's own messages last.
291
+ if (estimateBodyTokens(fitted) > HAIKU_INPUT_BUDGET) shed += cut(fitted, HAIKU_INPUT_BUDGET, { keepFrom: start });
292
+ return { body: fitted, before, after: estimateBodyTokens(fitted), shed };
293
+ }
294
+
295
+ module.exports = { HAIKU_INPUT_BUDGET, TRIM_STEP, LEFT_OUT, EARLIER, estimateBodyTokens, fitHaikuBody };
@@ -0,0 +1,29 @@
1
+ /** Shared by Tex (`agent/production.js`) and Context's meeting summaries (`apps/mcp/src/meetings/summarize.js`). */
2
+
3
+ /**
4
+ * A setup body cut at its `## <Name>` headings: `{ write: "...", check: "..." }`
5
+ * by lower-cased name. Text before the first heading is the note's own
6
+ * description for people and is never sent. A body with no heading is `{}`.
7
+ *
8
+ * @param {string} prompt a parsed setup's `prompt`
9
+ */
10
+ function promptSections(prompt) {
11
+ const sections = {};
12
+ let name = null;
13
+ let lines = [];
14
+ const close = () => {
15
+ if (name !== null && lines.join("\n").trim() !== "") sections[name] = lines.join("\n").trim();
16
+ };
17
+ for (const line of String(prompt ?? "").split(/\r?\n/)) {
18
+ const heading = /^## +(.+?)\s*$/.exec(line);
19
+ if (heading) {
20
+ close();
21
+ name = heading[1].toLowerCase();
22
+ lines = [];
23
+ } else if (name !== null) lines.push(line);
24
+ }
25
+ close();
26
+ return sections;
27
+ }
28
+
29
+ module.exports = { promptSections };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The one builder of a note's app link, `<APP_ORIGIN>/note/@<slug>/<path>`, for
3
+ * the gateway's MCP answers (`apps/mcp/src/notes/appLink.js`) and Tex's texted
4
+ * ones (`packages/tex/gateway/agent/noteLinks.js`): two builders would drift.
5
+ */
6
+ /** The deployment's https origin, without a trailing slash, or null. */
7
+ function appOriginOf(env) {
8
+ const origin = typeof env?.APP_ORIGIN === "string" ? env.APP_ORIGIN.replace(/\/$/, "") : "";
9
+ return /^https:\/\/[^/]+$/.test(origin) ? origin : null;
10
+ }
11
+
12
+ /**
13
+ * `<origin>/note/@slug/<path>`, every segment encoded and the `@` left
14
+ * readable; a page's is `<origin>/p/@slug/<path>`, which opens the page
15
+ * viewer rather than the app (owner, 2026-11-10; `infra/router/src/pageViewer.ts`).
16
+ */
17
+ function noteLinkUrl(origin, slug, path) {
18
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
19
+ const route = /\.page\.md$/i.test(path) ? "p" : "note";
20
+ return `${origin}/${route}/@${encodeURIComponent(slug)}/${encoded}`;
21
+ }
22
+
23
+ module.exports = { appOriginOf, noteLinkUrl };
@@ -0,0 +1,219 @@
1
+ /**
2
+ * NOTE LINK PREVIEWS: what a note link Tex texts unfurls with
3
+ * (Dev, 2026-11-23; `docs/decisions/privacy-and-sharing/note-link-previews.md`).
4
+ *
5
+ * A note link (`/note/@slug/<path>`, `/p/@slug/<page>`) used to unfurl as one
6
+ * frozen card, "A note in Context", whatever it named: the address is
7
+ * guessable, so a card drawn from it would tell a stranger what a private
8
+ * note is called. Dev chose a key instead: Tex adds the note's name and a key
9
+ * to the links it texts,
10
+ *
11
+ * /note/@seyi/areas/spirit/1-timothy-1.md?t=1%20Timothy%201&k=<22 chars>
12
+ *
13
+ * and only a link whose key matches gets a card with that name on it. The key
14
+ * is an HMAC over the workspace, the path and the name, under a key derived
15
+ * from the gateway's secret, so nobody can make a context.lc card say
16
+ * something Tex did not text. It grants nothing: opening the link is still a
17
+ * sign-in and the app's own permission check.
18
+ *
19
+ * Shared by the three places that touch it: the gateway that signs (Tex's
20
+ * `noteLinks.js`), the control plane that checks a key and draws the card
21
+ * (`apps/convex/functions/lib/publicRoutes/noteLinkCards.ts`), and nothing in between: the
22
+ * router only forwards what the crawler asked for.
23
+ *
24
+ * Also here: what the card shows beside the name, all of it read off the link
25
+ * and nothing else. The folder line is the link's own folders, the backdrop is
26
+ * picked from the address, and Tex's pose from the name and the folders.
27
+ */
28
+
29
+ /** Separates the key's version from what it signs; a new version is a new label. */
30
+ const LABEL = "context.note-preview.v1";
31
+ /** 16 bytes of the HMAC, as 22 base64url characters. */
32
+ const KEY_BYTES = 16;
33
+ const KEY_PATTERN = /^[A-Za-z0-9_-]{22}$/;
34
+ /** The longest name a link carries and a card draws. */
35
+ const MAX_TITLE = 80;
36
+
37
+ const encoder = new TextEncoder();
38
+
39
+ function toBase64Url(bytes) {
40
+ let binary = "";
41
+ for (const byte of bytes) binary += String.fromCharCode(byte);
42
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
43
+ }
44
+
45
+ /** The HMAC key a deployment signs and checks with, derived from its gateway secret; null without one. */
46
+ async function previewSigningKey(secret) {
47
+ if (typeof secret !== "string" || secret.length < 16) return null;
48
+ const root = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
49
+ const derived = new Uint8Array(await crypto.subtle.sign("HMAC", root, encoder.encode(LABEL)));
50
+ return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
51
+ }
52
+
53
+ /** What a key signs: one line each, the workspace lowercased, so `@Seyi` and `@seyi` are one link. */
54
+ function signedText(slug, path, title) {
55
+ return `${LABEL}\n${String(slug).toLowerCase()}\n${path}\n${title}`;
56
+ }
57
+
58
+ /** The key for one link, from a key `previewSigningKey` made. */
59
+ async function previewKey(signingKey, { slug, path, title }) {
60
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", signingKey, encoder.encode(signedText(slug, path, title))));
61
+ return toBase64Url(mac.slice(0, KEY_BYTES));
62
+ }
63
+
64
+ /**
65
+ * Whether `key` is the one this deployment would have made for the link.
66
+ * Compared in constant time over the whole string; any malformed input is false.
67
+ */
68
+ async function isPreviewKey(signingKey, { slug, path, title, key }) {
69
+ if (signingKey === null || typeof key !== "string" || !KEY_PATTERN.test(key)) return false;
70
+ if (typeof slug !== "string" || typeof path !== "string" || typeof title !== "string") return false;
71
+ if (cleanTitle(title) !== title) return false;
72
+ const expected = await previewKey(signingKey, { slug, path, title });
73
+ let difference = 0;
74
+ for (let i = 0; i < expected.length; i += 1) difference |= expected.charCodeAt(i) ^ key.charCodeAt(i);
75
+ return difference === 0;
76
+ }
77
+
78
+ /** A name fit for a card: control and format characters gone, spaces collapsed, at most MAX_TITLE characters. "" when nothing is left. */
79
+ function cleanTitle(value) {
80
+ if (typeof value !== "string") return "";
81
+ const clean = value.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
82
+ return Array.from(clean).slice(0, MAX_TITLE).join("").trim();
83
+ }
84
+
85
+ const SMALL_WORDS = new Set(["a", "an", "and", "at", "by", "for", "in", "of", "on", "or", "the", "to", "with"]);
86
+
87
+ /**
88
+ * A file or folder name read as words: no extension, dashes and underscores as
89
+ * spaces, first letter capital. A folder also loses a PARA number (`1-projects`);
90
+ * a note keeps its own (`1-timothy-1.md` is "1 Timothy 1").
91
+ */
92
+ function humanize(name, { folder = false } = {}) {
93
+ const bare = String(name)
94
+ .replace(/\.page\.md$/i, "")
95
+ .replace(/\.md$/i, "")
96
+ .replace(folder ? /^\d+[-_ ]+(?=\D)/ : /$^/, "");
97
+ // A folder, and a name with spaces, read as a sentence; a dashed note name as a title, each word capitalised but the small ones.
98
+ if (/\s/.test(bare) || folder) {
99
+ const spaced = folder ? bare.replace(/[-_]+/g, " ") : bare;
100
+ const trimmed = spaced.replace(/\s+/g, " ").trim();
101
+ return trimmed === "" ? "" : trimmed[0].toUpperCase() + trimmed.slice(1);
102
+ }
103
+ return bare
104
+ .split(/[-_]+/)
105
+ .filter(Boolean)
106
+ .map((word, i) => (i > 0 && SMALL_WORDS.has(word) ? word : word[0].toUpperCase() + word.slice(1)))
107
+ .join(" ");
108
+ }
109
+
110
+ /**
111
+ * The note's name for its card: its first `# ` heading when `text` (the note's
112
+ * Markdown, front matter allowed) has one near the top, else its file name as
113
+ * words. "" when neither gives one.
114
+ */
115
+ function noteTitleOf(path, text) {
116
+ if (typeof text === "string") {
117
+ const body = text.replace(/^---\n[\s\S]*?\n---\n/, "");
118
+ const heading = /^#[ \t]+(.+?)[ \t#]*$/m.exec(body.split("\n").slice(0, 40).join("\n"));
119
+ const named = heading ? cleanTitle(heading[1].replace(/[*_`]/g, "")) : "";
120
+ if (named !== "") return named;
121
+ }
122
+ const leaf = String(path ?? "").split("/").filter(Boolean).pop() ?? "";
123
+ return cleanTitle(humanize(leaf));
124
+ }
125
+
126
+ /** The card's folder line: the note's last two folders as words, joined by a middle dot. "" for a note at the top. */
127
+ function folderLineOf(path) {
128
+ const folders = String(path ?? "").split("/").filter(Boolean).slice(0, -1).slice(-2);
129
+ return cleanTitle(folders.map((name) => humanize(name, { folder: true })).filter(Boolean).join(" · "));
130
+ }
131
+
132
+ /**
133
+ * The backdrops a card is drawn on, in the order a link's address picks them:
134
+ * round 3's notebook page and ink, then the graph page's five boards
135
+ * (`apps/mobile/features/design/tokens/colors.ts` `boardColors`).
136
+ */
137
+ const BOARDS = Object.freeze(["notebook", "ink", "paper", "graph", "kraft", "chalk", "blueprint"]);
138
+
139
+ /** One backdrop per note, from its address, so the same link always looks the same and a chat of links varies. */
140
+ function boardOf(slug, path) {
141
+ let hash = 0x811c9dc5;
142
+ for (const char of `${String(slug).toLowerCase()}/${path}`) {
143
+ hash ^= char.codePointAt(0);
144
+ hash = Math.imul(hash, 0x01000193) >>> 0;
145
+ }
146
+ return BOARDS[hash % BOARDS.length];
147
+ }
148
+
149
+ /**
150
+ * What Tex is doing on a card, from words in the note's name and folders, or
151
+ * null for no Tex at all (the card then shows the # icon). Tex appears only
152
+ * when a note plainly is one of these (Dev, 2026-11-23: "smaller and didn't
153
+ * appear on every preview card"). Earlier rules win.
154
+ */
155
+ const POSE_RULES = [
156
+ ["checklist", /\b(to-?dos?|checklists?|packing|tasks?|lists?)\b/i],
157
+ ["money", /\b(budgets?|financ\w*|invoices?|receipts?|expenses?|tax(es)?|money|payments?|salary|bills?)\b/i],
158
+ ["cooking", /\b(recipes?|meals?|grocer\w*|dinners?|cook\w*)\b/i],
159
+ ["trip", /\b(trips?|travel\w*|flights?|itinerar\w*|vacations?|holidays?)\b/i],
160
+ ["calendar", /\b(events?|offsites?|schedules?|calendar|deadlines?|retreats?|conferences?|weddings?|birthdays?|party|parties)\b/i],
161
+ ["coffee", /\b(meetings?|catch[- ]?ups?|one[- ]on[- ]ones?|1:1s?|calls? with|standups?|syncs?)\b/i],
162
+ ["reading", /\b(bible|scripture|psalms?|proverbs|gospel|genesis|exodus|romans|timothy|sermons?|devotionals?|books?|reading|study)\b/i],
163
+ ["idea", /\b(ideas?|brainstorm\w*|concepts?|pitch(es)?)\b/i],
164
+ ["painting", /\b(designs?|websites?|mock-?ups?|logos?|brand)\b/i],
165
+ ["waving", /\b(contacts?|people|intros?|introductions?)\b/i],
166
+ ];
167
+
168
+ function poseOf(title, path) {
169
+ const words = `${title ?? ""} ${String(path ?? "").replace(/[-_/]+/g, " ")}`;
170
+ for (const [pose, pattern] of POSE_RULES) if (pattern.test(words)) return pose;
171
+ if (/\.page\.md$/i.test(String(path ?? ""))) return "painting";
172
+ return null;
173
+ }
174
+
175
+ /**
176
+ * `text` with each plain note link Tex was given this turn swapped for its
177
+ * signed one. `signed` maps a link exactly as the tool result gave it to the
178
+ * link with `t` and `k`; a link is swapped only where it stands whole (not as
179
+ * the start of a longer address), and every other word is left as it was.
180
+ */
181
+ function withPreviewLinks(text, signed) {
182
+ if (typeof text !== "string" || !(signed instanceof Map) || signed.size === 0) return text;
183
+ let out = text;
184
+ for (const [plain, withKey] of signed) {
185
+ let from = 0;
186
+ for (;;) {
187
+ const at = out.indexOf(plain, from);
188
+ if (at === -1) break;
189
+ // Already signed (a job's report finished twice): left as it is, never signed again.
190
+ if (out.startsWith(withKey, at)) {
191
+ from = at + withKey.length;
192
+ continue;
193
+ }
194
+ const next = out[at + plain.length];
195
+ if (next !== undefined && !/[\s)\]>.,;:!?'"]/.test(next)) {
196
+ from = at + plain.length;
197
+ continue;
198
+ }
199
+ out = out.slice(0, at) + withKey + out.slice(at + plain.length);
200
+ from = at + withKey.length;
201
+ }
202
+ }
203
+ return out;
204
+ }
205
+
206
+ module.exports = {
207
+ BOARDS,
208
+ KEY_PATTERN,
209
+ MAX_TITLE,
210
+ boardOf,
211
+ cleanTitle,
212
+ folderLineOf,
213
+ isPreviewKey,
214
+ noteTitleOf,
215
+ poseOf,
216
+ previewKey,
217
+ previewSigningKey,
218
+ withPreviewLinks,
219
+ };
@@ -0,0 +1,21 @@
1
+ /** Types for `notePreview.cjs`; see that file for the rules and the reasons. */
2
+
3
+ import type { TexPose } from "./ink/texPoses.cjs";
4
+
5
+ export type NoteBoard = "notebook" | "ink" | "paper" | "graph" | "kraft" | "chalk" | "blueprint";
6
+
7
+ export declare const BOARDS: readonly NoteBoard[];
8
+ export declare const KEY_PATTERN: RegExp;
9
+ export declare const MAX_TITLE: number;
10
+ export declare function previewSigningKey(secret: unknown): Promise<CryptoKey | null>;
11
+ export declare function previewKey(signingKey: CryptoKey, link: { slug: string; path: string; title: string }): Promise<string>;
12
+ export declare function isPreviewKey(
13
+ signingKey: CryptoKey | null,
14
+ link: { slug: unknown; path: unknown; title: unknown; key: unknown },
15
+ ): Promise<boolean>;
16
+ export declare function cleanTitle(value: unknown): string;
17
+ export declare function noteTitleOf(path: string, text?: string | null): string;
18
+ export declare function folderLineOf(path: string): string;
19
+ export declare function boardOf(slug: string, path: string): NoteBoard;
20
+ export declare function poseOf(title: string, path: string): TexPose | null;
21
+ export declare function withPreviewLinks(text: string, signed: Map<string, string>): string;