@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,114 @@
1
+ /**
2
+ * A turn's egress ledger, and which calls could share something (`apps/mcp/src/privacy/egress.js`, which re-exports
3
+ * these and keeps `recordRead`, the one part that judges a note's path).
4
+ *
5
+ * Tex starts a ledger for each turn it sees whole and marks it as it reads; the gateway's dispatcher marks the same
6
+ * ledger as the turn's tool calls read (`tools/session.js`). Pure, so both sides hold one copy.
7
+ */
8
+
9
+ /** The `share` values on `write_note` that mint a link (`notes/write.js`). */
10
+ const SHARE_VALUES = new Set(["members", "anyone", "collect"]);
11
+
12
+ /** A fresh ledger for one turn the gateway sees whole. */
13
+ function newLedger() {
14
+ return { untrusted: false, outside: false, asked: [] };
15
+ }
16
+
17
+ /** Mark the ledger: the turn took in something from outside the workspace. */
18
+ function markUntrusted(ledger) {
19
+ if (ledger) ledger.untrusted = ledger.outside = true;
20
+ }
21
+
22
+ /**
23
+ * Mark a group chat's turn: it carries other people's words, so its sends stay held as any untrusted turn's, but the
24
+ * people in the chat are not outside it (the owner, 2026-11-02), so `outside` is left for what came from beyond the
25
+ * chat: a page, an email, a file. Only a chat's own learned skills read it (`agent/chatSkills.js`).
26
+ */
27
+ function markChatWords(ledger) {
28
+ if (ledger) ledger.untrusted = true;
29
+ }
30
+
31
+ /**
32
+ * A summary is one plain line. It is built from arguments the model wrote (a
33
+ * path, an address) and read by a person who is about to say yes to it, in
34
+ * the gateway's own voice: a line break, a control character or a bidi
35
+ * override in it would let the model add sentences the person takes to be the
36
+ * gateway's, or reorder the ones that are.
37
+ */
38
+ function oneLine(text) {
39
+ return String(text)
40
+ .replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200b\u200e\u200f\u2028\u2029\u202a-\u202e\u2060\u2066-\u2069\ufeff]+/g, " ")
41
+ .replace(/\s+/g, " ")
42
+ .trim();
43
+ }
44
+
45
+ /** The write tools to treat as writes when a caller does not say. */
46
+ const WRITE_TOOLS_THAT_CAN_REACH_ELSEWHERE = new Set([
47
+ "write_note",
48
+ "create_form",
49
+ "set_visibility",
50
+ "set_folder_visibility",
51
+ "save_context",
52
+ "move_note",
53
+ "move_notes",
54
+ "move_folder",
55
+ "remember",
56
+ "submit_form",
57
+ "update_submission",
58
+ ]);
59
+
60
+ /**
61
+ * Whether this call could let more people see something, judged from its tool
62
+ * and arguments alone: the manifest is not read, so this is a superset and
63
+ * errs wide. Tex's housekeeping refuses anything it says yes to
64
+ * (`agent/housekeepingGuard.js`), since nobody is watching while it works.
65
+ *
66
+ * Never true for a dry run, which changes nothing.
67
+ *
68
+ * @param {string} name the tool, already resolved from any alias
69
+ * @param {object} args the arguments, `context` already stripped
70
+ * @param {object} options
71
+ * @param {string|null} options.into the other workspace addressed, as `@name`, or null
72
+ * @param {boolean} [options.writes] the tool changes something; addressed into
73
+ * another workspace it then counts, whatever else it does
74
+ * @returns {boolean}
75
+ */
76
+ function mightWiden(name, args, { into = null, writes } = {}) {
77
+ const a = args && typeof args === "object" ? args : {};
78
+ if (a.dry_run === true) return false;
79
+ if (name === "create_link") return true;
80
+ if (typeof into === "string" && into !== "") return writes ?? WRITE_TOOLS_THAT_CAN_REACH_ELSEWHERE.has(name);
81
+ switch (name) {
82
+ case "write_note":
83
+ return (
84
+ a.site?.action === "publish" ||
85
+ SHARE_VALUES.has(a.share) ||
86
+ (Array.isArray(a.images) && a.images.some((image) => typeof image?.url === "string" && image.url.trim() !== "")) ||
87
+ a.visibility === "team"
88
+ );
89
+ case "create_form":
90
+ return a.visibility === "team";
91
+ // A bot's logo by address is fetched from outside, as write_note's images by url are.
92
+ case "set_area":
93
+ return [a.bot?.avatar?.url, a.bot?.avatar_dark?.url].some((url) => typeof url === "string" && url.trim() !== "");
94
+ case "vault_list":
95
+ return Boolean(a.fetch && typeof a.fetch === "object");
96
+ case "set_visibility":
97
+ return a.visibility === "team" || (a.people !== undefined && a.people !== null);
98
+ case "set_folder_visibility":
99
+ return a.visibility === "team" || a.visibility === "inherit";
100
+ case "save_context":
101
+ return a.visibility === "team" || a.visibility === "public";
102
+ case "move_note":
103
+ case "move_notes":
104
+ case "move_folder":
105
+ return a.confirm_team_publish === true;
106
+ case "create_workspace":
107
+ case "invite_member":
108
+ return true;
109
+ default:
110
+ return false;
111
+ }
112
+ }
113
+
114
+ module.exports = { newLedger, markUntrusted, markChatWords, oneLine, mightWiden };
@@ -0,0 +1,14 @@
1
+ /** Types for `egressLedger.cjs`; see that file. */
2
+
3
+ export interface EgressLedger {
4
+ untrusted: boolean;
5
+ outside: boolean;
6
+ asked: unknown[];
7
+ [key: string]: unknown;
8
+ }
9
+
10
+ export declare function newLedger(): EgressLedger;
11
+ export declare function markUntrusted(ledger: EgressLedger | null | undefined): void;
12
+ export declare function markChatWords(ledger: EgressLedger | null | undefined): void;
13
+ export declare function oneLine(text: unknown): string;
14
+ export declare function mightWiden(name: string, args: unknown, options?: { into?: string | null; writes?: boolean }): boolean;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The email id and refusal contract (`apps/mcp/src/tools/emailRead.js`): an `email:<address>/<id>` id as a search gives it,
3
+ * its parser, and the refusal text the email reader and Tex's readers share. Pure: no store, no network.
4
+ *
5
+ * Plain CommonJS. `REFUSED` reads `AI_ACCESS_STEP` from `googleAiAccess.cjs`, the sentence the Google readers share.
6
+ */
7
+
8
+ const { AI_ACCESS_STEP } = require("./googleAiAccess.cjs");
9
+
10
+ const EMAIL_ID_PREFIX = "email:";
11
+
12
+ const ACCOUNT = /^[^\s@/]{1,64}@[^\s@/]{1,190}$/;
13
+ const MESSAGE_ID = /^[A-Za-z0-9_-]{1,64}$/;
14
+
15
+ const REFUSED = {
16
+ invalid: "That is not a search or an email this can read.",
17
+ not_allowed: "This connection cannot read the person's email: only their own personal workspace's mail, with private access.",
18
+ no_mailbox: "The person has no Gmail connected. They can connect one with manage connect_google.",
19
+ rate_limited: "Too many email reads this hour. Try again later, or look in their synced mail notes by date.",
20
+ reconnect_required: "Their Gmail sign-in stopped working, so it cannot be read and its mail has stopped syncing. They need to reconnect it with manage connect_google.",
21
+ ai_access_needed: `AI access isn't allowed yet for their Gmail, so it can't be read. ${AI_ACCESS_STEP}`,
22
+ not_found: "Gmail no longer has that email, or that attachment.",
23
+ too_large: "That attachment is over the 10 MB a file is read at.",
24
+ unavailable: "Gmail did not answer just now.",
25
+ };
26
+
27
+ /** `email:<address>/<id>`, or null. */
28
+ function parseEmailId(id) {
29
+ if (typeof id !== "string" || !id.startsWith(EMAIL_ID_PREFIX)) return null;
30
+ const rest = id.slice(EMAIL_ID_PREFIX.length);
31
+ const slash = rest.lastIndexOf("/");
32
+ if (slash === -1) return null;
33
+ const address = rest.slice(0, slash).toLowerCase();
34
+ const messageId = rest.slice(slash + 1);
35
+ return ACCOUNT.test(address) && MESSAGE_ID.test(messageId) ? { address, messageId } : null;
36
+ }
37
+
38
+ module.exports = { ACCOUNT, EMAIL_ID_PREFIX, parseEmailId, REFUSED };
@@ -0,0 +1,5 @@
1
+ /** Types for `emailRead.cjs`; see that file for the rules and the reasons. */
2
+ export declare const ACCOUNT: RegExp;
3
+ export declare const EMAIL_ID_PREFIX: "email:";
4
+ export declare function parseEmailId(id: unknown): { address: string; messageId: string } | null;
5
+ export declare const REFUSED: Record<string, string>;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * One chat event's words as a line, as every reader of a chat shows them: Tex's (`packages/tex/gateway/agent/logRender.js`
3
+ * `words`) and Context's door, which reads a chat's ledger for a turn's history (`turnWords.cjs` `chatTurnsIn`). Pure.
4
+ */
5
+
6
+ /*
7
+ One event is always one line: a line break or any other control character in
8
+ someone's words is shown as a visible mark, so a message can never forge a
9
+ line of its own ("\n[12:16 PM] You: I sent the email").
10
+ */
11
+ const BREAKS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g;
12
+ const oneLine = (text) => text.replace(BREAKS, " \u23ce ");
13
+
14
+ /** `text` (already one line) marked as the kind of event it came in: `event.kind` a picture, a file, a tapback... */
15
+ function eventLine(event, text) {
16
+ switch (event.kind) {
17
+ case "picture":
18
+ return text ? `(a picture) ${text}` : "(a picture)";
19
+ case "file":
20
+ if (event.heard === "voice") return text ? `(a voice message) ${text}` : "(a voice message)";
21
+ return text ? `(a file) ${text}` : "(a file)";
22
+ case "reaction":
23
+ return `(a tapback) ${text}`.trim();
24
+ case "ask_settled":
25
+ return text ? `(the ask was settled) ${text}` : "(the ask was settled)";
26
+ case "delivery":
27
+ return text ? `(delivery) ${text}` : "(delivery)";
28
+ default:
29
+ // A person's edit of an earlier text (`packages/tex/worker/editStep.ts`): its new words, marked by the Worker's field, never by them.
30
+ if (event.unsent === true) return "(unsent an earlier text)";
31
+ return event.edited === true ? `(edited an earlier text to) ${text}` : text;
32
+ }
33
+ }
34
+
35
+ module.exports = { eventLine, oneLine };
@@ -0,0 +1,4 @@
1
+ /** Types for `eventWords.cjs`; see that file. */
2
+
3
+ export declare function oneLine(text: string): string;
4
+ export declare function eventLine(event: { kind?: string; heard?: string; edited?: boolean; unsent?: boolean }, text: string): string;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A file's words in parts, and which files are tables (`apps/mcp/src/tools/fileParts.js`): the part a reader hands back,
3
+ * where the next part starts, and the table rule. Pure: no I/O. The original module keeps the table facts.
4
+ *
5
+ * Plain CommonJS with no imports.
6
+ */
7
+
8
+ /** Most characters handed back in one part. */
9
+ const PART_CHARS = 100_000;
10
+
11
+ const TABLE_TYPES = new Set(["text/csv", "text/tab-separated-values"]);
12
+ const TABLE_NAME = /\.(?:csv|tsv)$/i;
13
+
14
+ /** Whether a file is a table whose facts are worked out here. */
15
+ function isTable(name, type) {
16
+ return TABLE_TYPES.has(String(type ?? "").split(";")[0].trim().toLowerCase()) || TABLE_NAME.test(String(name ?? ""));
17
+ }
18
+
19
+ /**
20
+ * One part of `text` from `from`: at most `PART_CHARS`, ending at a line break
21
+ * when there is one, so no row is cut in two. `{ part, from, to, total }`, or
22
+ * null when `from` is past the end.
23
+ */
24
+ function partOf(text, from = 0) {
25
+ const total = text.length;
26
+ const start = Number.isInteger(from) && from > 0 ? from : 0;
27
+ if (start > 0 && start >= total) return null;
28
+ let to = Math.min(total, start + PART_CHARS);
29
+ if (to < total) {
30
+ const lineEnd = text.lastIndexOf("\n", to);
31
+ if (lineEnd > start) to = lineEnd + 1;
32
+ }
33
+ return { part: text.slice(start, to), from: start, to, total };
34
+ }
35
+
36
+ /** The lines that say which part this is and how to read the next one. */
37
+ function partLines(part, next) {
38
+ const lines = [`characters: ${part.from} to ${part.to} of ${part.total}`];
39
+ if (part.to < part.total) lines.push(`more: ${next(part.to)} reads the next part; read every part before you total anything`);
40
+ return lines;
41
+ }
42
+
43
+ module.exports = { PART_CHARS, isTable, partLines, partOf };
@@ -0,0 +1,6 @@
1
+ /** Types for `fileParts.cjs`; see that file for the rules and the reasons. */
2
+ export declare const PART_CHARS: number;
3
+ export declare function isTable(name: unknown, type: unknown): boolean;
4
+ export interface FilePart { part: string; from: number; to: number; total: number }
5
+ export declare function partOf(text: string, from?: number): FilePart | null;
6
+ export declare function partLines(part: FilePart, next: (at: number) => string): string[];
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /**
3
+ * A FILE'S WORDS IN PARTS, AND A TABLE'S FACTS WORKED OUT BY THE GATEWAY
4
+ * (the owner's review of a chat, 2026-10-24).
5
+ *
6
+ * Tex read a bank export of 8,530 rows for a spending breakdown. It saw the
7
+ * first 100,000 characters ("the file was too long for me to read every
8
+ * row"), and it reported rent going out twice a month ($7,700) because the
9
+ * export held every Bank of America row from Aug 1 to Sep 18 twice; it found
10
+ * that only when the person asked "probably duplicate rows? please check your
11
+ * work".
12
+ *
13
+ * So every reader of a file (`read_file`, an email's attachment with
14
+ * `read_email`, a file Tex kept, `agent/keptFiles.js`) hands back:
15
+ *
16
+ * - a part of the words, `MAX_FILE_CHARS` at most, ending at a line break,
17
+ * with where the next part starts (`from`), so a long file is read whole;
18
+ * - for a CSV or TSV, facts counted over the WHOLE file on every part: its
19
+ * rows, the rows that repeat another row exactly (with the first few, by
20
+ * line), and each column of amounts totalled with and without those
21
+ * repeats, so a total can be checked against the gateway's own sum.
22
+ *
23
+ * A table's bytes are read as text here rather than through Workers AI's
24
+ * `toMarkdown`: a CSV is already words, and the facts need its real rows.
25
+ */
26
+ const { PART_CHARS, isTable, partLines, partOf } = require("./fileParts.cjs");
27
+
28
+ /** Duplicate rows named, at most, by line. */
29
+ const MAX_EXAMPLES = 3;
30
+ /** Columns totalled, at most. */
31
+ const MAX_TOTALS = 6;
32
+
33
+
34
+ /** One CSV (or TSV) line's cells, quotes honoured. A quoted cell spanning lines is rare in an export and is read as two rows. */
35
+ function cells(line, delimiter = ",") {
36
+ const out = [];
37
+ let cell = "";
38
+ let quoted = false;
39
+ for (let i = 0; i < line.length; i += 1) {
40
+ const ch = line[i];
41
+ if (quoted) {
42
+ if (ch === '"' && line[i + 1] === '"') {
43
+ cell += '"';
44
+ i += 1;
45
+ } else if (ch === '"') quoted = false;
46
+ else cell += ch;
47
+ } else if (ch === '"' && cell === "") quoted = true;
48
+ else if (ch === delimiter) {
49
+ out.push(cell);
50
+ cell = "";
51
+ } else cell += ch;
52
+ }
53
+ out.push(cell);
54
+ return out.map((value) => value.trim());
55
+ }
56
+
57
+ /** An amount as a number: "-1,234.50", "$82.10", "(45.00)"; null for anything else. */
58
+ function amount(value) {
59
+ const raw = String(value ?? "").trim();
60
+ if (raw === "") return null;
61
+ const negative = /^\(.*\)$/.test(raw) || /^-/.test(raw.replace(/^\$/, ""));
62
+ const digits = raw.replace(/[()$£€,\s]/g, "").replace(/^-/, "");
63
+ if (!/^\d+(?:\.\d+)?$/.test(digits)) return null;
64
+ const n = Number(digits);
65
+ return negative ? -n : n;
66
+ }
67
+
68
+ const money = (n) => (Math.round(n * 100) / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
69
+
70
+ /**
71
+ * The facts of a whole table: `{ rows, header, duplicates, examples, totals }`.
72
+ * A duplicate is a row identical to an earlier one in every cell.
73
+ */
74
+ function tableFacts(text, name = "") {
75
+ const delimiter = /\.tsv$/i.test(name) || (!/,/.test(text.slice(0, 2000)) && /\t/.test(text.slice(0, 2000))) ? "\t" : ",";
76
+ const lines = text.split(/\r?\n/);
77
+ const header = cells(lines[0] ?? "", delimiter);
78
+ const seen = new Map();
79
+ const examples = [];
80
+ // The same payment twice, from two accounts or a reconnected bank: same day, amount and payee, something else different.
81
+ const find = (pattern) => header.findIndex((title) => pattern.test(title));
82
+ const dateAt = find(/^(?:transaction )?date$|^date\b/i);
83
+ const amountAt = find(/amount/i);
84
+ const payeeAt = find(/^(?:name|description|payee|merchant|memo)$/i);
85
+ const likeKeys = dateAt >= 0 && amountAt >= 0 && payeeAt >= 0 ? new Set() : null;
86
+ let alike = 0;
87
+ const all = header.map(() => ({ sum: 0, numbers: 0, filled: 0 }));
88
+ const once = header.map(() => 0);
89
+ let rows = 0;
90
+ let duplicates = 0;
91
+ for (let i = 1; i < lines.length; i += 1) {
92
+ const line = lines[i];
93
+ if (line.trim() === "") continue;
94
+ rows += 1;
95
+ const values = cells(line, delimiter);
96
+ const key = values.join("\u0000");
97
+ const first = seen.get(key);
98
+ const repeat = first !== undefined;
99
+ if (repeat) {
100
+ duplicates += 1;
101
+ if (examples.length < MAX_EXAMPLES) examples.push({ line: i + 1, sameAs: first });
102
+ } else seen.set(key, i + 1);
103
+ if (likeKeys !== null && !repeat) {
104
+ const like = [values[dateAt], values[amountAt], (values[payeeAt] ?? "").toLowerCase()].join("\u0000");
105
+ if (likeKeys.has(like)) alike += 1;
106
+ else likeKeys.add(like);
107
+ }
108
+ header.forEach((_, column) => {
109
+ const value = values[column];
110
+ if (value === undefined || value === "") return;
111
+ all[column].filled += 1;
112
+ const n = amount(value);
113
+ if (n === null) return;
114
+ all[column].numbers += 1;
115
+ all[column].sum += n;
116
+ if (!repeat) once[column] += n;
117
+ });
118
+ }
119
+ // A column of amounts: nearly every filled cell a number, and money-shaped (not a year, an id or a count).
120
+ const totals = header
121
+ .map((title, column) => ({ title: title || `column ${column + 1}`, column, ...all[column], once: once[column] }))
122
+ .filter((entry) => entry.filled > 0 && entry.numbers / entry.filled >= 0.95 && /amount|total|debit|credit|price|cost|balance|value|paid|spent/i.test(entry.title))
123
+ .slice(0, MAX_TOTALS);
124
+ return { rows, header, duplicates, examples, totals, alike, alikeBy: likeKeys === null ? null : [header[dateAt], header[amountAt], header[payeeAt]] };
125
+ }
126
+
127
+ /** The facts as lines above a part. */
128
+ function factLines(facts) {
129
+ const lines = [`rows: ${facts.rows} (not counting the header)`, `header: ${facts.header.join(", ").slice(0, 500)}`];
130
+ if (facts.duplicates > 0) {
131
+ const which = facts.examples.map((example) => `line ${example.line} repeats line ${example.sameAs}`).join("; ");
132
+ lines.push(
133
+ `duplicate rows: ${facts.duplicates} rows repeat an earlier row in every column (${which}${facts.duplicates > facts.examples.length ? "; …" : ""}). ` +
134
+ "An export that repeats rows counts them once: leave the repeats out of every total, and say you did.",
135
+ );
136
+ } else {
137
+ lines.push("duplicate rows: none repeat another row exactly");
138
+ }
139
+ if (facts.alike > 0) {
140
+ lines.push(
141
+ `near-duplicate rows: ${facts.alike} more rows match an earlier row on ${facts.alikeBy.join(", ")} but differ in another column: ` +
142
+ "the same payment seen twice (two accounts, a reconnected bank) or two real payments. Check them before you count them, and say which you decided.",
143
+ );
144
+ }
145
+ for (const total of facts.totals) {
146
+ lines.push(
147
+ facts.duplicates > 0
148
+ ? `total of ${total.title}: ${money(total.once)} with the repeated rows left out (${money(total.sum)} with them)`
149
+ : `total of ${total.title}: ${money(total.sum)}`,
150
+ );
151
+ }
152
+ lines.push(
153
+ `For any total, average or breakdown (by month, by category, one payee), call this again with summary: { by: ["month", "<a column>"], where: [{ column, contains }], dates: { from, to } }: ` +
154
+ "Context adds up every row, repeats left out. Never total rows yourself from a part.",
155
+ );
156
+ return lines;
157
+ }
158
+
159
+
160
+ /** A date cell as `YYYY-MM-DD`: "2026-08-03", "08/03/2026", "8/3/26"; null for anything else. */
161
+ function isoDate(value) {
162
+ const raw = String(value ?? "").trim();
163
+ let m = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(raw);
164
+ if (m) return `${m[1]}-${m[2].padStart(2, "0")}-${m[3].padStart(2, "0")}`;
165
+ m = /^(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})\b/.exec(raw);
166
+ if (m) return `${m[3].length === 2 ? `20${m[3]}` : m[3]}-${m[1].padStart(2, "0")}-${m[2].padStart(2, "0")}`;
167
+ return null;
168
+ }
169
+
170
+ /** Most groups listed in one summary. */
171
+ const MAX_GROUPS = 300;
172
+
173
+ /**
174
+ * Totals over a whole table, worked out here rather than by a model reading
175
+ * every row (8,530 rows do not fit in one turn): rows matching `where` (each
176
+ * `{ column, contains }`: that column's cell contains the text, any case) and dated between `dates.from`
177
+ * and `dates.to`, grouped by `by` (column names; "month" is the date's
178
+ * YYYY-MM), each group's row count and total of the amount column, with the
179
+ * rows that repeat another exactly left out.
180
+ *
181
+ * @returns {{ lines: string[] } | { error: string }}
182
+ */
183
+ function tableSummary(text, name, { by = [], where = {}, dates = {} } = {}) {
184
+ const delimiter = /\.tsv$/i.test(name) ? "\t" : ",";
185
+ const lines = text.split(/\r?\n/);
186
+ const header = cells(lines[0] ?? "", delimiter);
187
+ const at = (title) => header.findIndex((cell) => cell.toLowerCase() === String(title).trim().toLowerCase());
188
+ const dateAt = header.findIndex((title) => /^(?:transaction )?date$|^date\b/i.test(title));
189
+ const amountAt = header.findIndex((title) => /amount/i.test(title));
190
+ if (amountAt < 0) return { error: `no amount column to total; the columns are ${header.join(", ")}` };
191
+ const groups = (Array.isArray(by) ? by : [by]).filter((g) => typeof g === "string" && g.trim()).slice(0, 3);
192
+ const groupAt = groups.map((g) => (g.trim().toLowerCase() === "month" ? "month" : at(g)));
193
+ const missing = groups.filter((_, i) => groupAt[i] === -1 || (groupAt[i] === "month" && dateAt < 0));
194
+ // `[{ column, contains }]`, as the tools take it; `{ column: text }` too.
195
+ const pairs = Array.isArray(where)
196
+ ? where.filter((entry) => entry && typeof entry.column === "string").map((entry) => [entry.column, entry.contains ?? ""])
197
+ : Object.entries(where && typeof where === "object" ? where : {});
198
+ const filters = pairs.slice(0, 5).map(([column, value]) => [at(column), String(value).toLowerCase(), column]);
199
+ const unknown = filters.filter(([column]) => column < 0).map(([, , title]) => title);
200
+ if (missing.length > 0 || unknown.length > 0) return { error: `no such column: ${[...missing, ...unknown].join(", ")}; the columns are ${header.join(", ")}` };
201
+ const from = isoDate(dates?.from);
202
+ const to = isoDate(dates?.to);
203
+ if ((from || to) && dateAt < 0) return { error: "this table has no date column to filter by; leave the dates out" };
204
+ const seen = new Set();
205
+ const totals = new Map();
206
+ let matched = 0;
207
+ let repeats = 0;
208
+ let sum = 0;
209
+ for (let i = 1; i < lines.length; i += 1) {
210
+ if (lines[i].trim() === "") continue;
211
+ const values = cells(lines[i], delimiter);
212
+ const day = dateAt >= 0 ? isoDate(values[dateAt]) : null;
213
+ if ((from && (!day || day < from)) || (to && (!day || day > to))) continue;
214
+ if (filters.some(([column, value]) => !String(values[column] ?? "").toLowerCase().includes(value))) continue;
215
+ const key = values.join("\u0000");
216
+ if (seen.has(key)) {
217
+ repeats += 1;
218
+ continue;
219
+ }
220
+ seen.add(key);
221
+ const n = amount(values[amountAt]);
222
+ if (n === null) continue;
223
+ matched += 1;
224
+ sum += n;
225
+ const group = groupAt.map((column) => (column === "month" ? (day ?? "no date").slice(0, 7) : values[column] || "(blank)")).join(" · ") || "all";
226
+ const entry = totals.get(group) ?? { count: 0, total: 0 };
227
+ entry.count += 1;
228
+ entry.total += n;
229
+ totals.set(group, entry);
230
+ }
231
+ const sorted = [...totals.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
232
+ return {
233
+ lines: [
234
+ `summary of ${header[amountAt]}${groups.length ? ` by ${groups.join(", ")}` : ""}${filters.length ? `, where ${filters.map(([, v, t]) => `${t} contains "${v}"`).join(" and ")}` : ""}${from || to ? `, dated ${from ?? "start"} to ${to ?? "end"}` : ""}:`,
235
+ `${matched} rows, total ${money(sum)}${repeats > 0 ? `; ${repeats} repeated rows left out` : ""}`,
236
+ ...sorted.slice(0, MAX_GROUPS).map(([group, entry]) => `${group}: ${money(entry.total)} (${entry.count} rows)`),
237
+ ...(sorted.length > MAX_GROUPS ? [`… ${sorted.length - MAX_GROUPS} more groups; narrow it with where or dates`] : []),
238
+ "Counted by Context over every row of the file, not by reading it: quote these totals as they are.",
239
+ ],
240
+ };
241
+ }
242
+
243
+ module.exports = { PART_CHARS, isTable, partLines, partOf, cells, tableFacts, factLines, isoDate, tableSummary };