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

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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -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/capabilities.cjs +47 -0
  23. package/texContract/capabilities.d.cts +27 -0
  24. package/texContract/capabilities.generated.json +77 -0
  25. package/texContract/chatHistoryPath.cjs +38 -0
  26. package/texContract/chatHistoryPath.d.cts +5 -0
  27. package/texContract/chatLedger.cjs +91 -0
  28. package/texContract/chatLedger.d.cts +21 -0
  29. package/texContract/computerTool.cjs +102 -0
  30. package/texContract/computerTool.d.cts +16 -0
  31. package/texContract/consentYes.cjs +22 -0
  32. package/texContract/consentYes.d.cts +5 -0
  33. package/texContract/contextGateway.cjs +52 -0
  34. package/texContract/contextGateway.d.cts +19 -0
  35. package/texContract/deskEligible.cjs +20 -0
  36. package/texContract/deskEligible.d.cts +3 -0
  37. package/texContract/downloads.cjs +129 -0
  38. package/texContract/downloads.d.cts +15 -0
  39. package/texContract/egressLedger.cjs +114 -0
  40. package/texContract/egressLedger.d.cts +14 -0
  41. package/texContract/emailRead.cjs +38 -0
  42. package/texContract/emailRead.d.cts +5 -0
  43. package/texContract/eventWords.cjs +35 -0
  44. package/texContract/eventWords.d.cts +4 -0
  45. package/texContract/fileParts.cjs +43 -0
  46. package/texContract/fileParts.d.cts +6 -0
  47. package/texContract/fileTables.cjs +243 -0
  48. package/texContract/fileWords.cjs +169 -0
  49. package/texContract/folded.cjs +16 -0
  50. package/texContract/folded.d.cts +3 -0
  51. package/texContract/googleAiAccess.cjs +12 -0
  52. package/texContract/googleAiAccess.d.cts +2 -0
  53. package/texContract/graphWires.cjs +18 -0
  54. package/texContract/graphWires.d.cts +5 -0
  55. package/texContract/groupSession.cjs +28 -0
  56. package/texContract/groupSession.d.cts +7 -0
  57. package/texContract/guestNames.cjs +136 -0
  58. package/texContract/guestNames.d.cts +35 -0
  59. package/texContract/heard.cjs +19 -0
  60. package/texContract/heard.d.cts +4 -0
  61. package/texContract/heldOffer.cjs +57 -0
  62. package/texContract/heldOffer.d.cts +8 -0
  63. package/texContract/helperCallers.cjs +29 -0
  64. package/texContract/helperCallers.d.cts +4 -0
  65. package/texContract/identity.cjs +179 -0
  66. package/texContract/identity.d.cts +8 -0
  67. package/texContract/jobLogEntries.cjs +93 -0
  68. package/texContract/jobLogEntries.d.cts +12 -0
  69. package/texContract/judgedActions.cjs +20 -0
  70. package/texContract/judgedActions.d.cts +4 -0
  71. package/texContract/labSandboxGate.cjs +63 -0
  72. package/texContract/labSandboxGate.d.cts +9 -0
  73. package/texContract/ledgerReadChars.cjs +4 -0
  74. package/texContract/ledgerReadChars.d.cts +3 -0
  75. package/texContract/mailCheck.cjs +90 -0
  76. package/texContract/mailCheck.d.cts +12 -0
  77. package/texContract/mailEntries.cjs +64 -0
  78. package/texContract/mailEntries.d.cts +13 -0
  79. package/texContract/mailHealth.cjs +60 -0
  80. package/texContract/mailHealth.d.cts +10 -0
  81. package/texContract/notePath.cjs +99 -0
  82. package/texContract/notePath.d.cts +4 -0
  83. package/texContract/noteRunFacts.cjs +136 -0
  84. package/texContract/noteRunFacts.d.cts +32 -0
  85. package/texContract/objectEtag.cjs +84 -0
  86. package/texContract/objectEtag.d.cts +4 -0
  87. package/texContract/objectPlace.cjs +32 -0
  88. package/texContract/objectPlace.d.cts +5 -0
  89. package/texContract/pageJobs.cjs +226 -0
  90. package/texContract/pageJobs.d.cts +13 -0
  91. package/texContract/pdfLinks.cjs +135 -0
  92. package/texContract/pdfLinks.d.cts +4 -0
  93. package/texContract/personHub.cjs +38 -0
  94. package/texContract/personHub.d.cts +5 -0
  95. package/texContract/personNameText.cjs +18 -0
  96. package/texContract/personNameText.d.cts +3 -0
  97. package/texContract/pinnedContext.cjs +12 -0
  98. package/texContract/pinnedContext.d.cts +3 -0
  99. package/texContract/quietHoursWindow.cjs +36 -0
  100. package/texContract/quietHoursWindow.d.cts +3 -0
  101. package/texContract/reactEmoji.cjs +79 -0
  102. package/texContract/reactEmoji.d.cts +2 -0
  103. package/texContract/scopeClamp.cjs +117 -0
  104. package/texContract/scopeClamp.d.cts +5 -0
  105. package/texContract/scopes.cjs +29 -0
  106. package/texContract/scopes.d.cts +7 -0
  107. package/texContract/searchSettings.cjs +54 -0
  108. package/texContract/searchSettings.d.cts +6 -0
  109. package/texContract/settingHabits.cjs +87 -0
  110. package/texContract/settingHabits.d.cts +20 -0
  111. package/texContract/settingsNotes.cjs +217 -0
  112. package/texContract/settingsNotes.d.cts +26 -0
  113. package/texContract/shownEmail.cjs +181 -0
  114. package/texContract/texClients.cjs +53 -0
  115. package/texContract/texClients.d.cts +12 -0
  116. package/texContract/texGraph.cjs +593 -0
  117. package/texContract/texGraph.d.cts +55 -0
  118. package/texContract/texKeys.cjs +100 -0
  119. package/texContract/texKeys.d.cts +13 -0
  120. package/texContract/texNumber.cjs +20 -0
  121. package/texContract/texNumber.d.cts +3 -0
  122. package/texContract/texOwnSources.cjs +9 -0
  123. package/texContract/texOwnSources.d.cts +3 -0
  124. package/texContract/texSettings.cjs +22 -0
  125. package/texContract/texSettings.d.cts +20 -0
  126. package/texContract/texSettings.generated.json +25 -0
  127. package/texContract/texStateFiles.cjs +22 -0
  128. package/texContract/texStateFiles.d.cts +9 -0
  129. package/texContract/texSteps.cjs +27 -0
  130. package/texContract/texSteps.d.cts +14 -0
  131. package/texContract/texSteps.generated.json +41 -0
  132. package/texContract/texStoreNames.cjs +26 -0
  133. package/texContract/texStoreNames.d.cts +12 -0
  134. package/texContract/texStoreWire.cjs +306 -0
  135. package/texContract/texStoreWire.d.cts +32 -0
  136. package/texContract/threadsFold.cjs +75 -0
  137. package/texContract/threadsFold.d.cts +22 -0
  138. package/texContract/toolActions.cjs +253 -0
  139. package/texContract/toolCatalog.cjs +49 -0
  140. package/texContract/toolCatalog.generated.json +90 -0
  141. package/texContract/toolContract.cjs +52 -0
  142. package/texContract/toolContract.d.cts +12 -0
  143. package/texContract/toolShapes.cjs +14 -0
  144. package/texContract/transcription.cjs +101 -0
  145. package/texContract/transcription.d.cts +3 -0
  146. package/texContract/treeJobs.cjs +31 -0
  147. package/texContract/treeJobs.d.cts +3 -0
  148. package/texContract/turnSession.cjs +90 -0
  149. package/texContract/turnSession.d.cts +19 -0
  150. package/texContract/turnWords.cjs +90 -0
  151. package/texContract/turnWords.d.cts +9 -0
  152. package/texContract/uploadImages.cjs +131 -0
  153. package/texContract/uploadImages.d.cts +13 -0
  154. package/texContract/v2Names.cjs +41 -0
  155. package/texContract/v2SearchFetch.cjs +316 -0
  156. package/texContract/v2Translate.cjs +123 -0
  157. package/texContract/vaultTools.cjs +112 -0
  158. package/texContract/vaultTools.d.cts +15 -0
  159. package/texContract/yesWords.cjs +91 -0
  160. package/texShared/argumentCoercion.cjs +93 -0
  161. package/texShared/cellComments.cjs +122 -0
  162. package/texShared/cellComments.d.cts +21 -0
  163. package/texShared/comments.cjs +586 -0
  164. package/texShared/comments.d.cts +115 -0
  165. package/texShared/contentTypes.cjs +85 -0
  166. package/texShared/fileKinds.cjs +123 -0
  167. package/texShared/flags.cjs +159 -0
  168. package/texShared/flags.d.cts +23 -0
  169. package/texShared/folderJobInfo.cjs +301 -0
  170. package/texShared/folderJobInfo.d.cts +40 -0
  171. package/texShared/folderRoles.cjs +512 -0
  172. package/texShared/folderRoles.d.cts +73 -0
  173. package/texShared/githubOidc.ts +98 -0
  174. package/texShared/groupRunQuestions.cjs +98 -0
  175. package/texShared/groupRunQuestions.d.cts +4 -0
  176. package/texShared/inboxFolders.cjs +49 -0
  177. package/texShared/inboxFolders.d.cts +5 -0
  178. package/texShared/ink/drawing.cjs +474 -0
  179. package/texShared/ink/texFigure.cjs +252 -0
  180. package/texShared/ink/texFigure.d.cts +36 -0
  181. package/texShared/ink/texPoses.cjs +180 -0
  182. package/texShared/ink/texPoses.d.cts +20 -0
  183. package/texShared/jobPartEnd.cjs +133 -0
  184. package/texShared/jobPartEnd.d.cts +13 -0
  185. package/texShared/jobResume.cjs +31 -0
  186. package/texShared/jobResume.d.cts +5 -0
  187. package/texShared/jobSplit.cjs +90 -0
  188. package/texShared/jobSplit.d.cts +6 -0
  189. package/texShared/jobStart.cjs +56 -0
  190. package/texShared/jobStart.d.cts +9 -0
  191. package/texShared/mail.cjs +400 -0
  192. package/texShared/mail.d.cts +56 -0
  193. package/texShared/messageAnchors.cjs +38 -0
  194. package/texShared/models/aiKeys.cjs +137 -0
  195. package/texShared/models/aiKeys.d.cts +42 -0
  196. package/texShared/models/aiKeys.json +56 -0
  197. package/texShared/models/creditRest.cjs +269 -0
  198. package/texShared/models/promptBudget.cjs +295 -0
  199. package/texShared/models/promptSections.cjs +29 -0
  200. package/texShared/noteAppLink.cjs +23 -0
  201. package/texShared/notePreview.cjs +219 -0
  202. package/texShared/notePreview.d.cts +21 -0
  203. package/texShared/pages/blocks.cjs +215 -0
  204. package/texShared/pages/cover.cjs +164 -0
  205. package/texShared/pages/css.cjs +181 -0
  206. package/texShared/pages/cssBlocks.cjs +264 -0
  207. package/texShared/pages/draw.cjs +212 -0
  208. package/texShared/pages/drawRich.cjs +232 -0
  209. package/texShared/pages/html.cjs +168 -0
  210. package/texShared/pages/inline.cjs +251 -0
  211. package/texShared/pages/layout.cjs +76 -0
  212. package/texShared/pages/parse.cjs +418 -0
  213. package/texShared/pages/render.cjs +200 -0
  214. package/texShared/pages/skill.cjs +147 -0
  215. package/texShared/pages/skill.d.cts +5 -0
  216. package/texShared/pages/templates.cjs +336 -0
  217. package/texShared/r2Store.cjs +163 -0
  218. package/texShared/remoteImage.cjs +177 -0
  219. package/texShared/routines.cjs +656 -0
  220. package/texShared/routines.d.cts +86 -0
  221. package/texShared/servedListing.cjs +250 -0
  222. package/texShared/servedListing.d.cts +17 -0
  223. package/texShared/sheetCsv.cjs +566 -0
  224. package/texShared/sheetCsv.d.cts +91 -0
  225. package/texShared/storageLayout.cjs +88 -0
  226. package/texShared/storeKeys.cjs +144 -0
  227. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,88 @@
1
+ /** Context-owned on-bucket storage layout, shared by every producer. */
2
+ const CONTEXT_ROOT = ".context/";
3
+ const STORAGE_LAYOUT_VERSION = 1;
4
+ const STORAGE_LAYOUT_MANIFEST_KEY = `${CONTEXT_ROOT}manifest.json`;
5
+ const STORAGE_LAYOUT_MIGRATION_KEY = `${CONTEXT_ROOT}migrations/storage-layout-v1.json`;
6
+
7
+ const AUDIT_PREFIX = `${CONTEXT_ROOT}audit/`;
8
+ const HISTORY_PREFIX = `${CONTEXT_ROOT}history/`;
9
+ const IMAGE_PREFIX = `${CONTEXT_ROOT}assets/images/`;
10
+ const SEARCH_PREFIX = `${CONTEXT_ROOT}search/`;
11
+ const MEETING_PREFIX = `${CONTEXT_ROOT}meetings/sessions/`;
12
+ const NOTE_ACL_PREFIX = `${CONTEXT_ROOT}access/note-acl/`;
13
+ const GRANOLA_EVENTS_PREFIX = `${CONTEXT_ROOT}integrations/granola/events/`;
14
+ const PROPOSAL_PREFIX = `${CONTEXT_ROOT}proposals/`;
15
+ const PROBE_PREFIX = `${CONTEXT_ROOT}probes/`;
16
+ const WEBSITE_RELEASE_PREFIX = `${CONTEXT_ROOT}website/releases/`;
17
+ /**
18
+ * What AI clients read: one object per read under a UTC day, plus a
19
+ * rebuildable roll-up of each day beside it. New with no legacy location.
20
+ */
21
+ const READS_PREFIX = `${CONTEXT_ROOT}reads/`;
22
+ /**
23
+ * Sealed logins Tex fills into web pages, one object per entry. New with no
24
+ * legacy location (`apps/mcp/src/vault/`).
25
+ */
26
+ const VAULT_PREFIX = `${CONTEXT_ROOT}vault/`;
27
+
28
+ const LEGACY_STORAGE_PREFIXES = Object.freeze([
29
+ [".audit/", AUDIT_PREFIX],
30
+ [".history/", HISTORY_PREFIX],
31
+ [".images/", IMAGE_PREFIX],
32
+ [".index/", SEARCH_PREFIX],
33
+ [".meetings/sessions/", MEETING_PREFIX],
34
+ [".note-acl/", NOTE_ACL_PREFIX],
35
+ [".granola-events/", GRANOLA_EVENTS_PREFIX],
36
+ [".proposals/", PROPOSAL_PREFIX],
37
+ [".context-probe/", PROBE_PREFIX],
38
+ ]);
39
+
40
+ function currentStorageKey(key) {
41
+ for (const [legacy, current] of LEGACY_STORAGE_PREFIXES) {
42
+ if (key.startsWith(legacy)) return `${current}${key.slice(legacy.length)}`;
43
+ }
44
+ return key;
45
+ }
46
+
47
+ function legacyStorageKey(key) {
48
+ for (const [legacy, current] of LEGACY_STORAGE_PREFIXES) {
49
+ if (key.startsWith(current)) return `${legacy}${key.slice(current.length)}`;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * A plumbing object at its v1 key, or its pre-v1 copy when the v1 key misses: over the store it is handed, so the
56
+ * gateway (`apps/mcp/src/storageLayout.js`, which re-exports it) and Tex read it alike.
57
+ */
58
+ async function getWithLegacyFallback(store, key, options = {}) {
59
+ const current = await store.get(key);
60
+ if (current) return current;
61
+ const legacy = legacyStorageKey(key);
62
+ if (!legacy) return null;
63
+ if (options.beforeFallback && options.beforeFallback() === false) return null;
64
+ return store.get(legacy);
65
+ }
66
+
67
+ module.exports = {
68
+ CONTEXT_ROOT,
69
+ STORAGE_LAYOUT_VERSION,
70
+ STORAGE_LAYOUT_MANIFEST_KEY,
71
+ STORAGE_LAYOUT_MIGRATION_KEY,
72
+ AUDIT_PREFIX,
73
+ HISTORY_PREFIX,
74
+ IMAGE_PREFIX,
75
+ SEARCH_PREFIX,
76
+ MEETING_PREFIX,
77
+ NOTE_ACL_PREFIX,
78
+ GRANOLA_EVENTS_PREFIX,
79
+ PROPOSAL_PREFIX,
80
+ PROBE_PREFIX,
81
+ WEBSITE_RELEASE_PREFIX,
82
+ READS_PREFIX,
83
+ VAULT_PREFIX,
84
+ LEGACY_STORAGE_PREFIXES,
85
+ currentStorageKey,
86
+ legacyStorageKey,
87
+ getWithLegacyFallback,
88
+ };
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ /**
3
+ * The keys and etags a store adapter accepts, and its root prefix: the checks every adapter runs at its boundary, so
4
+ * `S3Store`, `R2Store` and Tex's store over its object accept and reject exactly the same keys. Moved from
5
+ * `apps/mcp/src/store/index.js`, which re-exports them, into the shared code Tex's tree takes with it.
6
+ */
7
+
8
+ // The decoding lives with `normalizePath` in a pure contract Tex reads too (`../texContract/notePath.cjs`).
9
+ const { decodeSegment } = require("../texContract/notePath.cjs");
10
+
11
+ const MAX_ETAG_LENGTH = 256;
12
+ /** Normalize an etag so S3's quoted form compares equal to R2's bare form. */
13
+ function normalizeEtag(value) {
14
+ if (typeof value !== "string") return value;
15
+ return value
16
+ .trim()
17
+ .replace(/^W\//i, "")
18
+ .replace(/^"(.*)"$/, "$1");
19
+ }
20
+
21
+ /**
22
+ * An etag is about to be interpolated into an `If-Match` header. RFC 7232
23
+ * allows `%x21 / %x23-7E` inside an entity-tag, which excludes the quote we add
24
+ * ourselves and every control character — so a CR/LF can never split the header
25
+ * and a quote can never terminate it early.
26
+ */
27
+ function assertSafeEtag(value) {
28
+ if (typeof value !== "string" || !value || value.length > MAX_ETAG_LENGTH) {
29
+ throw new Error("unsafe etag: an etag must be a non-empty string of at most 256 characters");
30
+ }
31
+ if (!/^[\x21\x23-\x7e]+$/.test(value)) {
32
+ throw new Error("unsafe etag: an etag must not contain quotes, control characters, or non-ASCII");
33
+ }
34
+ return value;
35
+ }
36
+
37
+ /** S3 caps object keys at 1024 characters; anything longer is a bug or an attack. */
38
+ const MAX_KEY_LENGTH = 1024;
39
+ /** NUL and other control characters, plus the backslash some backends fold to "/". */
40
+ const FORBIDDEN_KEY_CHARS = /[\u0000-\u001f\u007f\\]/;
41
+
42
+
43
+
44
+ /**
45
+ * Why the adapter validates at all: `encodeRfc3986` does not encode "." (it is
46
+ * RFC 3986 unreserved), so a literal ".." survives encoding and the WHATWG URL
47
+ * parser removes dot segments when `url.pathname` is assigned — silently
48
+ * rewriting the key, escaping the rootPrefix, and even dropping the bucket
49
+ * segment. The signature is computed after that rewrite, so the request is
50
+ * valid, correctly signed, and pointed somewhere the caller never asked for.
51
+ * Reject instead of normalizing: a caller that meant "a/../b.md" has a bug.
52
+ */
53
+ function describeKeyProblem(key, { allowTrailingSlash }) {
54
+ if (typeof key !== "string") return "must be a string";
55
+ if (!key) return "must not be empty";
56
+ if (key.length > MAX_KEY_LENGTH) return `must be at most ${MAX_KEY_LENGTH} characters`;
57
+ if (FORBIDDEN_KEY_CHARS.test(key)) return "must not contain control characters or backslashes";
58
+ const segments = key.split("/");
59
+ for (let index = 0; index < segments.length; index += 1) {
60
+ const segment = segments[index];
61
+ const isLast = index === segments.length - 1;
62
+ if (segment === "") {
63
+ if (isLast && allowTrailingSlash && segments.length > 1) continue;
64
+ return "must not contain an empty path segment";
65
+ }
66
+ const decoded = decodeSegment(segment);
67
+ if (segment === "." || decoded === ".") return 'must not contain a "." path segment';
68
+ if (segment === ".." || decoded === "..") return 'must not contain a ".." path segment';
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /**
74
+ * Guard an object key at the adapter boundary, so `S3Store` and `R2Store` agree
75
+ * on exactly which keys are addressable. The message never echoes the key:
76
+ * keys are the customer's own note paths and gateway logs do not carry them.
77
+ */
78
+ function assertSafeKey(key) {
79
+ const problem = describeKeyProblem(key, { allowTrailingSlash: false });
80
+ if (problem) throw new Error(`unsafe storage key: a key ${problem}`);
81
+ return key;
82
+ }
83
+
84
+ /** Same rules as a key, but "" means the whole bucket and a trailing "/" is normal. */
85
+ function assertSafePrefix(prefix) {
86
+ if (prefix === undefined || prefix === null || prefix === "") return "";
87
+ const problem = describeKeyProblem(prefix, { allowTrailingSlash: true });
88
+ if (problem) throw new Error(`unsafe storage prefix: a prefix ${problem}`);
89
+ return prefix;
90
+ }
91
+
92
+ /**
93
+ * "" or a prefix guaranteed to end in exactly one "/".
94
+ *
95
+ * Validated like any other prefix: a rootPrefix is configuration, but it is
96
+ * still a path, and `".."` in it would escape the bucket on every request.
97
+ */
98
+ function normalizeRootPrefix(value) {
99
+ if (!value) return "";
100
+ const trimmed = String(value).replace(/^\/+/, "").replace(/\/+$/, "");
101
+ if (!trimmed) return "";
102
+ assertSafePrefix(trimmed);
103
+ return `${trimmed}/`;
104
+ }
105
+
106
+ /** Caller key → backend key. */
107
+ function applyRootPrefix(rootPrefix, key) {
108
+ return rootPrefix ? `${rootPrefix}${key}` : key;
109
+ }
110
+
111
+ /** Backend key → caller key. Returns null for anything outside the prefix. */
112
+ function stripRootPrefix(rootPrefix, key) {
113
+ if (!rootPrefix) return key;
114
+ return key.startsWith(rootPrefix) ? key.slice(rootPrefix.length) : null;
115
+ }
116
+
117
+ /**
118
+ * Re-key a backend list page into caller-visible keys.
119
+ *
120
+ * One honest exception to "nothing above the adapter sees the rootPrefix":
121
+ * `page.cursor` is passed through verbatim, and an S3 continuation token is
122
+ * base64 of the last backend key — prefix included. It is not rewritten
123
+ * because it is an opaque token the same adapter must hand back to the same
124
+ * backend unchanged; re-encoding it would only obfuscate. It is safe because
125
+ * the cursor never escapes the pagination loops in `src/index.js`: it is never
126
+ * returned by a tool, never logged, and never stored. If a cursor ever becomes
127
+ * caller-visible, that claim has to be re-examined.
128
+ */
129
+ function stripListResult(rootPrefix, page) {
130
+ if (!rootPrefix) return page;
131
+ const objects = [];
132
+ for (const object of page.objects || []) {
133
+ const key = stripRootPrefix(rootPrefix, object.key);
134
+ if (key !== null) objects.push({ ...object, key });
135
+ }
136
+ const delimitedPrefixes = [];
137
+ for (const prefix of page.delimitedPrefixes || []) {
138
+ const stripped = stripRootPrefix(rootPrefix, prefix);
139
+ if (stripped !== null) delimitedPrefixes.push(stripped);
140
+ }
141
+ return { ...page, objects, delimitedPrefixes };
142
+ }
143
+
144
+ module.exports = { MAX_ETAG_LENGTH, MAX_KEY_LENGTH, normalizeEtag, assertSafeEtag, assertSafeKey, assertSafePrefix, normalizeRootPrefix, applyRootPrefix, stripRootPrefix, stripListResult };
@@ -0,0 +1,323 @@
1
+ "use strict";
2
+ /**
3
+ * Tool-call arguments, checked against the schema the gateway advertised.
4
+ *
5
+ * `tools/list` publishes an `inputSchema` for every tool. Until this file
6
+ * existed nothing enforced one: `callTool` took the whole arguments object and
7
+ * each handler read the properties it happened to know about, so the only
8
+ * reason "this tool takes no arguments" was true of `export_encryption_keys`
9
+ * is that its two implementing functions do not declare an `args` parameter.
10
+ * An argument the schema does not describe reached a handler unexamined, and
11
+ * the callers here are AI clients driven by text other people wrote — an email
12
+ * body, a meeting transcript, a shared note. Extra properties are how a
13
+ * prompt-injected client turns a read into something else, and the schema is
14
+ * the only place that says what a tool actually takes.
15
+ *
16
+ * **Written by hand, against the subset the tools use.** The gateway takes no
17
+ * npm dependencies and runs on the Workers runtime; a JSON Schema library is
18
+ * neither available nor wanted for a handful of keywords. What the tool
19
+ * definitions in `index.js` actually use, and therefore all this supports:
20
+ *
21
+ * - `type: "object"` with `properties`, `required` and
22
+ * `additionalProperties: false` — at the root and, for `move_notes`, one
23
+ * level down inside `items`.
24
+ * - property types `string`, `boolean`, `integer`, `array`, `object`.
25
+ * - `enum` on strings, `minimum`/`maximum` on integers, and `items`,
26
+ * `minItems` and `maxItems` on arrays.
27
+ *
28
+ * A keyword a schema uses and this file does not know is a silent hole, so
29
+ * `unsupportedKeywords` names them and the census test fails the build rather
30
+ * than letting a schema quietly mean less than it says.
31
+ *
32
+ * **The refusal is about the caller's own request and nothing else.** No
33
+ * message here reads storage, names a workspace, or varies with what exists:
34
+ * every string it can produce is a function of the arguments the caller sent
35
+ * and the schema that is already public in `tools/list`. That is what makes
36
+ * `{path: "x.md", workspaceId: "…"}` refused identically whether that
37
+ * workspace exists or not — the refusal happens before anything is looked up.
38
+ */
39
+
40
+ /**
41
+ * How much of an arguments object this will walk before giving up.
42
+ *
43
+ * Not a business rule — `move_notes` has its own `BATCH_MOVE_CAP`, and
44
+ * duplicating it here would give two numbers that can drift. This is a work
45
+ * budget, so that a caller cannot spend the Worker's CPU inside the validator
46
+ * with a million-element array or an object with a million keys. Every key
47
+ * examined and every array element entered costs one unit. The largest legal
48
+ * call today is a 100-move batch at three properties each, a little over 400
49
+ * units; 10,000 leaves two orders of magnitude of headroom and still refuses
50
+ * in microseconds.
51
+ *
52
+ * Recursion depth needs no separate ceiling: the walk is driven by the schema,
53
+ * never by the value, so it can only descend where a schema says `object` or
54
+ * `array` — and the deepest schema here is two levels. A value nested a
55
+ * thousand deep under a property declared `string` fails one `typeof` check
56
+ * without ever being entered.
57
+ */
58
+ const VALIDATION_NODE_BUDGET = 10000;
59
+
60
+ /** The message a caller gets when its arguments outrun that budget. */
61
+ const TOO_LARGE = "arguments are too large to check";
62
+
63
+ /** The keywords this validator implements. Anything else is a hole. */
64
+ const KNOWN_KEYWORDS = new Set([
65
+ "type",
66
+ "properties",
67
+ "required",
68
+ "additionalProperties",
69
+ "items",
70
+ "enum",
71
+ "minimum",
72
+ "maximum",
73
+ "minItems",
74
+ "maxItems",
75
+ "minLength",
76
+ "maxLength",
77
+ "description",
78
+ "title",
79
+ "default",
80
+ ]);
81
+
82
+ /**
83
+ * Every schema keyword in `schema` this file would ignore.
84
+ *
85
+ * The census test asserts this is empty across all advertised tools. Adding
86
+ * `pattern` or `minLength` to a tool definition without teaching this file
87
+ * about it would otherwise advertise a constraint nothing enforces, which is
88
+ * worse than not advertising it: a reviewer reads the schema and believes it.
89
+ */
90
+ function unsupportedKeywords(schema, seen = new Set()) {
91
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return [...seen];
92
+ for (const key of Object.keys(schema)) {
93
+ if (!KNOWN_KEYWORDS.has(key)) seen.add(key);
94
+ }
95
+ for (const child of Object.values(schema.properties || {})) {
96
+ unsupportedKeywords(child, seen);
97
+ }
98
+ if (schema.items) unsupportedKeywords(schema.items, seen);
99
+ return [...seen];
100
+ }
101
+
102
+ /**
103
+ * A caller-supplied name, rendered so a reviewer and an agent can both read it.
104
+ *
105
+ * Two reasons this is not plain interpolation. A property name arrives from a
106
+ * client driven by somebody else's text, so it can carry control characters,
107
+ * bidi overrides or zero-width joiners that would make the refusal itself
108
+ * unreadable — `docs/decisions/testing.md`'s "an invisible character in source
109
+ * is a fixture nobody can review", one layer out. And the attack this guard is
110
+ * for includes a name that differs from a real one only by a confusable, where
111
+ * echoing the bytes back verbatim produces a message that appears to complain
112
+ * about the correct spelling. Everything outside printable ASCII is escaped,
113
+ * so a Cyrillic a in place of an ASCII one comes back as `\u0430` and the
114
+ * caller can see what it actually sent.
115
+ */
116
+ function describeName(name) {
117
+ const text = typeof name === "string" ? name : String(name);
118
+ const clipped = text.length > 64 ? `${text.slice(0, 64)}...` : text;
119
+ let out = "";
120
+ for (const char of clipped) {
121
+ const code = char.codePointAt(0);
122
+ if (code >= 0x20 && code <= 0x7e && char !== '"' && char !== "\\") {
123
+ out += char;
124
+ } else if (code > 0xffff) {
125
+ out += `\\u{${code.toString(16)}}`;
126
+ } else {
127
+ out += `\\u${code.toString(16).padStart(4, "0")}`;
128
+ }
129
+ }
130
+ return `"${out}"`;
131
+ }
132
+
133
+ /** The type name to say in a refusal, for a value of unknown shape. */
134
+ function typeNameOf(value) {
135
+ if (value === null) return "null";
136
+ if (Array.isArray(value)) return "array";
137
+ return typeof value;
138
+ }
139
+
140
+ /** `a string`, `an integer` — the article the message needs. */
141
+ function withArticle(type) {
142
+ return /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
143
+ }
144
+
145
+ /** Does `value` satisfy the JSON Schema `type` keyword `expected`? */
146
+ function matchesType(expected, value) {
147
+ switch (expected) {
148
+ case "string":
149
+ return typeof value === "string";
150
+ case "boolean":
151
+ return typeof value === "boolean";
152
+ case "integer":
153
+ return typeof value === "number" && Number.isInteger(value);
154
+ case "number":
155
+ return typeof value === "number" && Number.isFinite(value);
156
+ case "array":
157
+ return Array.isArray(value);
158
+ case "object":
159
+ return value !== null && typeof value === "object" && !Array.isArray(value);
160
+ default:
161
+ // A schema with no `type` constrains nothing; that is the schema's
162
+ // choice, not a gap here.
163
+ return true;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Check one value against one schema.
169
+ *
170
+ * Returns `null` when it is acceptable, or a sentence naming what is wrong.
171
+ * `path` is the raw, unescaped address of this value — `path`,
172
+ * `moves[0].source` — and is escaped once, at the moment a message is built.
173
+ */
174
+ function checkValue(schema, value, path, budget) {
175
+ if (budget.spent > VALIDATION_NODE_BUDGET) return TOO_LARGE;
176
+
177
+ if (schema.type && !matchesType(schema.type, value)) {
178
+ return `argument ${describeName(path)} must be ${withArticle(schema.type)}, not ${typeNameOf(value)}`;
179
+ }
180
+
181
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
182
+ // The permitted values are already in `tools/list`; repeating them here
183
+ // discloses nothing and saves the caller a round trip.
184
+ return `argument ${describeName(path)} must be one of: ${schema.enum.join(", ")}`;
185
+ }
186
+
187
+ if (typeof schema.minimum === "number" && typeof value === "number" && value < schema.minimum) {
188
+ return `argument ${describeName(path)} must be at least ${schema.minimum}`;
189
+ }
190
+ if (typeof schema.maximum === "number" && typeof value === "number" && value > schema.maximum) {
191
+ return `argument ${describeName(path)} must be at most ${schema.maximum}`;
192
+ }
193
+
194
+ /*
195
+ A string's advertised length, enforced because `tools/list` states it.
196
+
197
+ These two were absent from `KNOWN_KEYWORDS`, which made them exactly what
198
+ the comment there warns of: a bound a reviewer reads in the schema and
199
+ believes, with nothing behind it. The connector endpoints build their own
200
+ schemas (`mcp/chatgpt/tools.js`), the `save_context` they advertise to a
201
+ directory scan says `maxLength: 12000` on the words it carries, and a
202
+ 200,000-character call passed.
203
+
204
+ Counted with `.length`, so in UTF-16 units rather than the code points JSON
205
+ Schema specifies: an astral character counts twice and is refused slightly
206
+ sooner than the letter of the spec would. That is the direction a bound may
207
+ err in, it costs no scan of the string, and no schema here is near enough to
208
+ its bound for the difference to decide a call. Spelled out because the next
209
+ schema to carry a bound might be.
210
+
211
+ Length before the object walk below, as with `maxItems`: a megabyte of
212
+ string is refused after reading one integer.
213
+ */
214
+ if (typeof value === "string") {
215
+ if (typeof schema.minLength === "number" && value.length < schema.minLength) {
216
+ return `argument ${describeName(path)} must be at least ${schema.minLength} character${schema.minLength === 1 ? "" : "s"}`;
217
+ }
218
+ if (typeof schema.maxLength === "number" && value.length > schema.maxLength) {
219
+ return `argument ${describeName(path)} must be at most ${schema.maxLength} character${schema.maxLength === 1 ? "" : "s"}`;
220
+ }
221
+ }
222
+
223
+ if (Array.isArray(value)) {
224
+ /*
225
+ Length before contents, deliberately. `move_notes` advertises
226
+ `maxItems: 100` and its handler carries the same bound in
227
+ `BATCH_MOVE_CAP`; enforcing the advertised one here means a batch of a
228
+ million elements is refused after reading one integer rather than after
229
+ a million type checks. The handler keeps its own bound — it is the
230
+ business rule, and this is what the schema said.
231
+ */
232
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) {
233
+ return `argument ${describeName(path)} must have at least ${schema.minItems} item${
234
+ schema.minItems === 1 ? "" : "s"
235
+ }`;
236
+ }
237
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
238
+ return `argument ${describeName(path)} must have at most ${schema.maxItems} items`;
239
+ }
240
+ }
241
+
242
+ if (schema.type === "array" && schema.items && Array.isArray(value)) {
243
+ for (let i = 0; i < value.length; i += 1) {
244
+ budget.spent += 1;
245
+ if (budget.spent > VALIDATION_NODE_BUDGET) return TOO_LARGE;
246
+ const failure = checkValue(schema.items, value[i], `${path}[${i}]`, budget);
247
+ if (failure) return failure;
248
+ }
249
+ }
250
+
251
+ if (schema.type === "object" && schema.properties) {
252
+ return checkObject(schema, value, path, budget);
253
+ }
254
+
255
+ return null;
256
+ }
257
+
258
+ /**
259
+ * Check an object against an object schema: unknown out, required in, types.
260
+ *
261
+ * The order is deliberate. Unknown properties are refused first, because that
262
+ * is the finding this file exists for and because a call carrying one should
263
+ * never be told anything else about itself — an argument the schema does not
264
+ * describe is not a nearly-right call, it is a different call.
265
+ */
266
+ function checkObject(schema, value, path, budget) {
267
+ const properties = schema.properties || {};
268
+ const permitted = Object.keys(properties);
269
+ const allowsExtra = schema.additionalProperties !== false;
270
+
271
+ if (!allowsExtra) {
272
+ for (const key of Object.keys(value)) {
273
+ budget.spent += 1;
274
+ if (budget.spent > VALIDATION_NODE_BUDGET) return TOO_LARGE;
275
+ if (Object.prototype.hasOwnProperty.call(properties, key)) continue;
276
+ const name = describeName(path ? `${path}.${key}` : key);
277
+ return permitted.length
278
+ ? `unknown argument ${name}; permitted here: ${permitted.join(", ")}`
279
+ : `unknown argument ${name}; this takes no arguments`;
280
+ }
281
+ }
282
+
283
+ for (const key of schema.required || []) {
284
+ if (!Object.prototype.hasOwnProperty.call(value, key) || value[key] === undefined) {
285
+ return `missing required argument ${describeName(path ? `${path}.${key}` : key)}`;
286
+ }
287
+ }
288
+
289
+ for (const [key, propertySchema] of Object.entries(properties)) {
290
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
291
+ if (value[key] === undefined) continue;
292
+ const failure = checkValue(propertySchema, value[key], path ? `${path}.${key}` : key, budget);
293
+ if (failure) return failure;
294
+ }
295
+
296
+ return null;
297
+ }
298
+
299
+ /**
300
+ * Validate a tool call's arguments against that tool's advertised schema.
301
+ *
302
+ * `args` is what the client sent, before anything is stripped from it: the
303
+ * addressing argument `context` is part of what was advertised (see
304
+ * `CONTEXT_ARGUMENT` in `index.js`) and is checked like any other property, so
305
+ * the two tools that deliberately do not advertise it — ChatGPT's `search` and
306
+ * `fetch`, whose schema is somebody else's contract — refuse it like any other
307
+ * property they do not take.
308
+ *
309
+ * Returns `null` when the call may proceed, or the sentence to refuse it with.
310
+ * Absent arguments are an empty object: a client that omits `arguments`
311
+ * entirely on a tool that requires nothing is a normal, correct client, and
312
+ * every era of the MCP spec lets it.
313
+ */
314
+ function validateArguments(schema, args) {
315
+ const supplied = args === undefined || args === null ? {} : args;
316
+ if (typeof supplied !== "object" || Array.isArray(supplied)) {
317
+ return `arguments must be a JSON object, not ${typeNameOf(supplied)}`;
318
+ }
319
+ if (!schema || typeof schema !== "object") return null;
320
+ return checkObject(schema, supplied, "", { spent: 0 });
321
+ }
322
+
323
+ module.exports = { VALIDATION_NODE_BUDGET, unsupportedKeywords, describeName, validateArguments };