@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,306 @@
1
+ /**
2
+ * The client half of the Tex store wire: how a caller talks to a Tex store Durable Object (`apps/mcp/src/texStore.js`,
3
+ * or a person's workspace object, `apps/mcp/src/workspaceStore/texHost.js`). One `fetch` per call, the call in a header
4
+ * and a body's bytes as the body, so a note is never base64'd or JSON-escaped on the way.
5
+ *
6
+ * The objects and their answering side (`serveTexStore`) are Context's (`apps/mcp/src/texStore/wire.js`, which
7
+ * re-exports this file). Tex's code keeps one client of them, `packages/tex/gateway/texStoreClient.js`. Pure, with no
8
+ * imports: the stub maker and the store over a bucket take the two gateway pieces they need (`objectByName`, `R2Store`)
9
+ * as arguments.
10
+ */
11
+
12
+ const CALL = "x-tex-call";
13
+ const META = "x-tex-meta";
14
+ const ORIGIN = "https://tex-store.internal";
15
+ /** The header naming the owner (`person:<workspaceId>`, `chat:<chatId>`) on every call to a placed store. */
16
+ const OWNER_HEADER = "x-tex-owner";
17
+ /** The prefix of every placed store's name. */
18
+ const PLACED_PREFIX = "enam:";
19
+ /** A Tex store's owner, as a call names it. */
20
+ const OWNER_PATTERN = /^(person|chat):[A-Za-z0-9_-]{1,64}$/;
21
+ const PERSON = /^person:([A-Za-z0-9_-]{1,64})$/;
22
+
23
+ /** A store write the object refuses: too large, or a key it would not keep. */
24
+ class TexObjectRefused extends Error {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "TexObjectRefused";
28
+ }
29
+ }
30
+
31
+ /** The name the owner's store lives under. */
32
+ function placedName(owner) {
33
+ if (typeof owner !== "string" || !OWNER_PATTERN.test(owner)) throw new TypeError("not a Tex store's owner");
34
+ return `${PLACED_PREFIX}${owner}`;
35
+ }
36
+
37
+ /** The workspace a person owner names (`person:<workspaceId>`), or null. */
38
+ function personWorkspaceOf(owner) {
39
+ const match = typeof owner === "string" ? PERSON.exec(owner) : null;
40
+ return match ? match[1] : null;
41
+ }
42
+
43
+ /** The workspace object's name for a person's Tex: their personal workspace's own object. */
44
+ function mergedName(owner) {
45
+ const workspaceId = personWorkspaceOf(owner);
46
+ if (workspaceId === null) throw new TypeError("only a person's Tex merges into a workspace object");
47
+ return `workspace:${workspaceId}`;
48
+ }
49
+
50
+ /** The one name per owner. Exported so a test can pin that two owners never share one. */
51
+ function ownerName(owner) {
52
+ if (typeof owner?.person === "string" && owner.person !== "" && owner.chat === undefined) return `person:${owner.person}`;
53
+ if (typeof owner?.chat === "string" && owner.chat !== "" && owner.person === undefined) return `chat:${owner.chat}`;
54
+ throw new TypeError("a Tex store belongs to one person or one group chat");
55
+ }
56
+
57
+ /**
58
+ * The Durable Object a person's (`person`: their workspace id) or a group
59
+ * chat's (`chat`: its id) Tex notes live in, with every call naming its owner.
60
+ *
61
+ * A person's is their personal workspace's own object (`workspace:<id>`,
62
+ * `workspaceStore/texHost.js`; decided by the owner, 2026-11-02: one object
63
+ * for the workspace and its Tex), whose first Tex call copies in the store
64
+ * they had before (`texStore/merge.js`). A group chat's is its own Tex store, placed in
65
+ * eastern North America (`placedName`), whose first call copies in the store
66
+ * under the old name (`texStore/move.js`). A deployment without workspace objects keeps
67
+ * a person's in a Tex store too. `null` without the binding. `objectByName` is the gateway's
68
+ * one placer of objects (`apps/mcp/src/objectPlace.js`).
69
+ */
70
+ function texStoreStubWith(objectByName, env, owner) {
71
+ const name = ownerName(owner);
72
+ const workspaces = env?.WORKSPACE_STORE;
73
+ const person = typeof owner?.person === "string" && workspaces && typeof workspaces.idFromName === "function";
74
+ const namespace = person ? workspaces : env?.TEX_STORE;
75
+ if (!namespace || typeof namespace.idFromName !== "function") return null;
76
+ const stub = objectByName(namespace, person ? mergedName(name) : placedName(name));
77
+ return {
78
+ fetch(request) {
79
+ request.headers.set(OWNER_HEADER, name);
80
+ return stub.fetch(request);
81
+ },
82
+ };
83
+ }
84
+
85
+ const pack = (value) => encodeURIComponent(JSON.stringify(value ?? null));
86
+ const unpack = (value) => (value ? JSON.parse(decodeURIComponent(value)) : null);
87
+
88
+ /** A stored object as R2 hands one back: `uploaded` a Date, a quoted `httpEtag`, and the body readers when it has one. */
89
+ function r2Shaped(meta, bytes) {
90
+ if (meta === null) return null;
91
+ const object = { ...meta, uploaded: new Date(meta.uploaded), httpEtag: `"${meta.etag}"`, version: meta.etag };
92
+ if (bytes === undefined) return object;
93
+ let used = false;
94
+ const take = () => {
95
+ if (used) throw new TypeError("body already read");
96
+ used = true;
97
+ return bytes;
98
+ };
99
+ // Defined, not assigned: assigning would read the `body` getter and spend the body.
100
+ Object.defineProperties(object, {
101
+ body: { enumerable: true, get: () => new Response(take()).body },
102
+ bodyUsed: { enumerable: true, get: () => used },
103
+ });
104
+ return Object.assign(object, {
105
+ async arrayBuffer() {
106
+ const view = take();
107
+ return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
108
+ },
109
+ async text() {
110
+ return new TextDecoder().decode(take());
111
+ },
112
+ async json() {
113
+ return JSON.parse(new TextDecoder().decode(take()));
114
+ },
115
+ async blob() {
116
+ return new Blob([take()]);
117
+ },
118
+ });
119
+ }
120
+
121
+ async function wholeBytes(value) {
122
+ if (value === null || value === undefined) return new Uint8Array(0);
123
+ if (typeof value === "string") return new TextEncoder().encode(value);
124
+ if (value instanceof Uint8Array) return value;
125
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
126
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
127
+ // A stream or a Blob: read once, whole, as the object keeps it.
128
+ return new Uint8Array(await new Response(value).arrayBuffer());
129
+ }
130
+
131
+ /**
132
+ * An R2-bucket-shaped client over a Tex store Durable Object's stub.
133
+ *
134
+ * @param {{fetch: (request: Request) => Promise<Response>}} stub
135
+ */
136
+ function texBucket(stub) {
137
+ const call = (op, fields, body) => callTexStore(stub, op, fields, body);
138
+ return {
139
+ async head(key) {
140
+ return r2Shaped(unpack((await call("head", { key })).headers.get(META)), undefined);
141
+ },
142
+ async get(key, options = {}) {
143
+ const response = await call("get", { key, options: { onlyIf: options.onlyIf, range: options.range } });
144
+ const answer = unpack(response.headers.get(META));
145
+ if (answer === null) return null;
146
+ const { hasBody, ...meta } = answer;
147
+ // A failed `onlyIf` answers metadata alone, as R2 does.
148
+ if (hasBody !== true) return r2Shaped(meta, undefined);
149
+ return r2Shaped(meta, new Uint8Array(await response.arrayBuffer()));
150
+ },
151
+ async put(key, value, options = {}) {
152
+ const bytes = await wholeBytes(value);
153
+ const fields = { key, options: { onlyIf: options.onlyIf, httpMetadata: options.httpMetadata, customMetadata: options.customMetadata } };
154
+ return r2Shaped(unpack((await call("put", fields, bytes)).headers.get(META)), undefined);
155
+ },
156
+ async delete(keys) {
157
+ await call("delete", { keys });
158
+ },
159
+ async list(options = {}) {
160
+ const page = await (await call("list", { options })).json();
161
+ return { ...page, objects: page.objects.map((meta) => r2Shaped(meta, undefined)) };
162
+ },
163
+ /** A person's texted turn's reads, in one call (`desk.js`): `{history, notes, ledger}`. */
164
+ async desk() {
165
+ return await (await call("desk")).json();
166
+ },
167
+ /** Add entries to a chat's ledger (`ledger.js`): `{added, seq, kinds}`. */
168
+ async ledgerAppend(chat, entries) {
169
+ return await (await call("ledger_append", { chat }, new TextEncoder().encode(JSON.stringify(entries)))).json();
170
+ },
171
+ /** Entries put before everything a chat's ledger holds (`ledger.js` `prepend`): `{added, kinds}`. */
172
+ async ledgerPrepend(chat, entries) {
173
+ return await (await call("ledger_prepend", { chat }, new TextEncoder().encode(JSON.stringify(entries)))).json();
174
+ },
175
+ /** A chat's oldest ledger entry, `{id, at}`, or null. */
176
+ async ledgerOldest(chat) {
177
+ return (await (await call("ledger_oldest", { chat })).json()).oldest;
178
+ },
179
+ /** A chat's ledger as one document, `{manifest, entries, next?|before?}` (`ledger.js` `read`). */
180
+ async ledgerRead(chat, options = {}) {
181
+ return await (await call("ledger_read", { chat, options })).json();
182
+ },
183
+ /** The chats this object keeps a ledger for, each a manifest. */
184
+ async ledgerChats() {
185
+ return (await (await call("ledger_chats")).json()).chats;
186
+ },
187
+ /** A texted turn's rounds for a try after a crash (`rounds.js`): keep the newest, read it back, forget it once answered. */
188
+ async roundsPut(chat, key, data) {
189
+ await call("rounds_put", { chat, key }, new TextEncoder().encode(JSON.stringify(data)));
190
+ },
191
+ async roundsGet(chat, key) {
192
+ return (await (await call("rounds_get", { chat, key })).json()).rounds ?? null;
193
+ },
194
+ async roundsForget(chat, key) {
195
+ await call("rounds_forget", { chat, key });
196
+ },
197
+ /** A chat's step's prompt modules frozen for the day (`frozen.js`): keep them, read them back. */
198
+ async frozenPut(chat, step, data) {
199
+ await call("frozen_put", { chat, step }, new TextEncoder().encode(JSON.stringify(data)));
200
+ },
201
+ /** A chat's last cached prompt prefix (`warm.js`): keep it, read it back, mark it sent again. */
202
+ async warmPut(chat, data) {
203
+ await call("warm_put", { chat }, new TextEncoder().encode(JSON.stringify(data)));
204
+ },
205
+ async warmGet(chat) {
206
+ return (await (await call("warm_get", { chat })).json()).warm ?? null;
207
+ },
208
+ async warmUsed(chat) {
209
+ await call("warm_used", { chat });
210
+ },
211
+ async frozenGet(chat, step) {
212
+ return (await (await call("frozen_get", { chat, step })).json()).frozen ?? null;
213
+ },
214
+ /** Everything in this Durable Object removed: an account, a phone link or a group chat ending. */
215
+ async wipe() {
216
+ await call("wipe");
217
+ },
218
+ };
219
+ }
220
+
221
+ /** One call to the object: its answer, or a refusal as `TexObjectRefused`. */
222
+ async function callTexStore(stub, op, fields = {}, body = undefined) {
223
+ const response = await stub.fetch(
224
+ new Request(`${ORIGIN}/${op}`, { method: "POST", headers: { [CALL]: pack({ op, ...fields }) }, body }),
225
+ );
226
+ if (response.status === 422) {
227
+ const { message } = await response.json();
228
+ throw new TexObjectRefused(message);
229
+ }
230
+ if (!response.ok) throw new Error(`Tex store ${op} failed (${response.status})`);
231
+ return response;
232
+ }
233
+
234
+ /**
235
+ * The client for a Tex store's routine alarms, over the same stub:
236
+ * `schedule({id, at, payload})` sets one (replacing the id's), `cancel(id)`
237
+ * removes one. Each re-arms the object's alarm (`texStore.js`).
238
+ */
239
+ function texTimers(stub) {
240
+ return {
241
+ async schedule(alarm) {
242
+ await callTexStore(stub, "schedule", {}, new TextEncoder().encode(JSON.stringify(alarm ?? null)));
243
+ },
244
+ async cancel(id) {
245
+ await callTexStore(stub, "cancel", { id });
246
+ },
247
+ };
248
+ }
249
+
250
+ /** A Tex object's store over its bucket-shaped client: notes as R2 (`R2Store`, `apps/mcp/src/store/r2.js`), and the desk and the chat ledgers beside them. */
251
+ function texBucketStoreWith(R2Store, bucket) {
252
+ return Object.assign(new R2Store(bucket), {
253
+ desk: () => bucket.desk(),
254
+ ledger: { append: (chat, entries) => bucket.ledgerAppend(chat, entries), read: (chat, options) => bucket.ledgerRead(chat, options), chats: () => bucket.ledgerChats(), prepend: (chat, entries) => bucket.ledgerPrepend(chat, entries), oldest: (chat) => bucket.ledgerOldest(chat), keepRounds: (chat, key, data) => bucket.roundsPut(chat, key, data), roundsOf: (chat, key) => bucket.roundsGet(chat, key), forgetRounds: (chat, key) => bucket.roundsForget(chat, key), keepFrozen: (chat, step, data) => bucket.frozenPut(chat, step, data), frozenOf: (chat, step) => bucket.frozenGet(chat, step), keepWarm: (chat, data) => bucket.warmPut(chat, data), warmOf: (chat) => bucket.warmGet(chat), warmUsed: (chat) => bucket.warmUsed(chat) },
255
+ });
256
+ }
257
+
258
+ /**
259
+ * The store over an owner's object: `owner` is `person:<workspaceId>` or `chat:<chatId>`, as a Tex key names it
260
+ * (`store/texRouting.js`, which has already checked it is this workspace's). `null` without the binding.
261
+ */
262
+ function gatewayTexStoreWith(objectByName, R2Store, env) {
263
+ return (owner) => {
264
+ const cut = owner.indexOf(":");
265
+ const stub = texStoreStubWith(objectByName, env, { [owner.slice(0, cut)]: owner.slice(cut + 1) });
266
+ if (stub === null) return null;
267
+ // The store, and the desk beside it: one call for what a texted turn reads first (`desk.js`).
268
+ return texBucketStoreWith(R2Store, texBucket(stub));
269
+ };
270
+ }
271
+
272
+ /** Tell a chat's Tex object that sections of its page changed. Never throws. */
273
+ async function pokeTexPageWith(objectByName, env, owner, sections) {
274
+ try {
275
+ const stub = texStoreStubWith(objectByName, env, owner);
276
+ if (stub === null) return false;
277
+ await callTexStore(stub, "page_poke", { sections });
278
+ return true;
279
+ } catch {
280
+ return false;
281
+ }
282
+ }
283
+
284
+ module.exports = {
285
+ CALL,
286
+ META,
287
+ ORIGIN,
288
+ OWNER_HEADER,
289
+ PLACED_PREFIX,
290
+ OWNER_PATTERN,
291
+ TexObjectRefused,
292
+ placedName,
293
+ personWorkspaceOf,
294
+ mergedName,
295
+ ownerName,
296
+ texStoreStubWith,
297
+ pack,
298
+ unpack,
299
+ r2Shaped,
300
+ texBucket,
301
+ callTexStore,
302
+ texTimers,
303
+ texBucketStoreWith,
304
+ gatewayTexStoreWith,
305
+ pokeTexPageWith,
306
+ };
@@ -0,0 +1,32 @@
1
+ /** Types for `texStoreWire.cjs`; see that file. */
2
+
3
+ export interface TexStoreStub {
4
+ fetch(request: Request): Promise<Response>;
5
+ }
6
+ export interface TexOwner {
7
+ person?: string;
8
+ chat?: string;
9
+ }
10
+ export declare const CALL: string;
11
+ export declare const META: string;
12
+ export declare const ORIGIN: string;
13
+ export declare const OWNER_HEADER: string;
14
+ export declare const PLACED_PREFIX: string;
15
+ export declare const OWNER_PATTERN: RegExp;
16
+ export declare class TexObjectRefused extends Error {
17
+ constructor(message: string);
18
+ }
19
+ export declare function placedName(owner: string): string;
20
+ export declare function personWorkspaceOf(owner: unknown): string | null;
21
+ export declare function mergedName(owner: string): string;
22
+ export declare function ownerName(owner: TexOwner): string;
23
+ export declare function texStoreStubWith(objectByName: (namespace: any, name: string) => TexStoreStub, env: any, owner: TexOwner): TexStoreStub | null;
24
+ export declare function pack(value: unknown): string;
25
+ export declare function unpack(value: string | null): any;
26
+ export declare function r2Shaped(meta: any, bytes: Uint8Array | undefined): any;
27
+ export declare function texBucket(stub: TexStoreStub): any;
28
+ export declare function callTexStore(stub: TexStoreStub, op: string, fields?: Record<string, unknown>, body?: BodyInit): Promise<Response>;
29
+ export declare function texTimers(stub: TexStoreStub): { schedule(alarm: unknown): Promise<void>; cancel(id: string): Promise<void> };
30
+ export declare function texBucketStoreWith(R2Store: new (bucket: any) => any, bucket: any): any;
31
+ export declare function gatewayTexStoreWith(objectByName: (namespace: any, name: string) => TexStoreStub, R2Store: new (bucket: any) => any, env: any): (owner: string) => any;
32
+ export declare function pokeTexPageWith(objectByName: (namespace: any, name: string) => TexStoreStub, env: any, owner: TexOwner, sections: string[]): Promise<boolean>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A chat's conversation threads folded from its threads ledger, with no imports: the classifier
3
+ * (`packages/tex/gateway/agent/conversationThreads.js`), the conversations view (`apps/mcp/src/texStore/historyView.js`)
4
+ * and the Tex page's conversations (`apps/mcp/src/http/texPage/conversations.js`) all read threads this way, and the
5
+ * view is bundled by Workers (the email Worker among them) that must not pull in the classifier's model calls.
6
+ */
7
+
8
+ const THREADS_SUFFIX = ".threads";
9
+ /** The most threads the prompt lists; the rest are reached with `read_thread`. */
10
+ const MAX_LISTED = 50;
11
+ const TITLE_CHARS = 60;
12
+ const DESCRIPTION_CHARS = 240;
13
+ const THREAD_ID = /^t[1-9][0-9]{0,5}$/;
14
+ /** The most thread entries one read takes: far more than any chat's threads. */
15
+ const MAX_READ = 5000;
16
+ const MAX_PAGES = 20;
17
+
18
+ /**
19
+ * The threads as they stand, from the ledger's `thread` entries (any order): `{threads, start}`. Each thread
20
+ * `{id, title, description, status, texts, at, last}`: the newest entry's words and status, every entry's texts.
21
+ * `start` is when the first entry was written (null with none).
22
+ */
23
+ function foldThreads(entries) {
24
+ const byId = new Map();
25
+ let start = null;
26
+ const sorted = (Array.isArray(entries) ? entries : []).filter((entry) => entry?.kind === "thread" && typeof entry.thread === "string" && THREAD_ID.test(entry.thread) && Number.isSafeInteger(entry.at)).sort((a, b) => a.at - b.at || (a.seq ?? 0) - (b.seq ?? 0));
27
+ for (const entry of sorted) {
28
+ start = start === null ? entry.at : Math.min(start, entry.at);
29
+ const was = byId.get(entry.thread) ?? { id: entry.thread, title: "", description: "", status: "open", texts: [], at: entry.at, last: entry.at };
30
+ const texts = Array.isArray(entry.texts) ? entry.texts.filter((id) => typeof id === "string") : [];
31
+ byId.set(entry.thread, {
32
+ ...was,
33
+ title: typeof entry.title === "string" && entry.title.trim() !== "" ? entry.title.trim().slice(0, TITLE_CHARS) : was.title,
34
+ description: typeof entry.description === "string" && entry.description.trim() !== "" ? entry.description.trim().slice(0, DESCRIPTION_CHARS) : was.description,
35
+ status: entry.status === "finished" ? "finished" : entry.status === "open" ? "open" : was.status,
36
+ texts: [...new Set([...was.texts, ...texts])],
37
+ last: texts.length > 0 ? entry.at : was.last,
38
+ });
39
+ }
40
+ return { threads: [...byId.values()], start };
41
+ }
42
+
43
+ /** Which threads the prompt lists: open first, newest first, then the most recently finished, `MAX_LISTED` in all. */
44
+ function listedThreads(threads, max = MAX_LISTED) {
45
+ const open = threads.filter((thread) => thread.status === "open").sort((a, b) => b.last - a.last);
46
+ const finished = threads.filter((thread) => thread.status !== "open").sort((a, b) => b.last - a.last);
47
+ return [...open, ...finished].slice(0, max);
48
+ }
49
+
50
+ /** The threads ledger's chat name for a chat. */
51
+ const threadsChat = (chat) => `${chat}${THREADS_SUFFIX}`;
52
+
53
+ /**
54
+ * The chat's threads, read from its threads ledger (`ledger`, the chat's Tex ledger handle), with the entries they were
55
+ * folded from; empty when there is none or it can't be read.
56
+ */
57
+ async function readThreads(ledger, chat) {
58
+ if (ledger === null || typeof ledger?.read !== "function" || typeof chat !== "string") return { ...foldThreads([]), entries: [] };
59
+ try {
60
+ // Paged: a chat replayed from its whole history (`threadsBackfill.js`) can hold more entries than one read.
61
+ const entries = [];
62
+ let after = 0;
63
+ for (let page = 0; page < MAX_PAGES; page += 1) {
64
+ const read = await ledger.read(threadsChat(chat), { after, limit: MAX_READ });
65
+ if (Array.isArray(read?.entries)) entries.push(...read.entries);
66
+ if (!Number.isSafeInteger(read?.next)) break;
67
+ after = read.next;
68
+ }
69
+ return { ...foldThreads(entries), entries };
70
+ } catch {
71
+ return { ...foldThreads([]), entries: [] };
72
+ }
73
+ }
74
+
75
+ module.exports = { THREADS_SUFFIX, MAX_LISTED, TITLE_CHARS, DESCRIPTION_CHARS, foldThreads, listedThreads, threadsChat, readThreads };
@@ -0,0 +1,22 @@
1
+ /** Types for `threadsFold.cjs`; see that file. */
2
+
3
+ export interface FoldedThread {
4
+ id: string;
5
+ title: string;
6
+ description: string;
7
+ status: "open" | "finished";
8
+ texts: string[];
9
+ at: number;
10
+ last: number;
11
+ }
12
+ export declare const THREADS_SUFFIX: string;
13
+ export declare const MAX_LISTED: number;
14
+ export declare const TITLE_CHARS: number;
15
+ export declare const DESCRIPTION_CHARS: number;
16
+ export declare function foldThreads(entries: unknown): { threads: FoldedThread[]; start: number | null };
17
+ export declare function listedThreads(threads: FoldedThread[], max?: number): FoldedThread[];
18
+ export declare function threadsChat(chat: string): string;
19
+ export interface ThreadsLedger {
20
+ read(chat: string, options: { after: number; limit: number }): Promise<{ entries?: unknown[]; next?: number } | null | undefined>;
21
+ }
22
+ export declare function readThreads(ledger: ThreadsLedger | null | undefined, chat: string): Promise<{ threads: FoldedThread[]; start: number | null; entries: unknown[] }>;