@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,100 @@
1
+ /**
2
+ * The shapes of the keys Tex's Durable Objects keep, and whose object each one
3
+ * names: pure rules both the gateway (`apps/mcp/src/store/texRouting.js`,
4
+ * `privacy/engine.js`) and Tex read, so Tex reaches none of the gateway's
5
+ * modules for them (`docs/decisions/texting-assistant/tex-service.md`).
6
+ *
7
+ * Moved verbatim; the gateway's modules re-export these, so every caller and
8
+ * test there is unchanged.
9
+ */
10
+ "use strict";
11
+
12
+ /**
13
+ * The same id key kept in Tex's Durable Object instead of the bucket
14
+ * (`texStore/keys.js`): `tex/<owner>/notes/<noteId>.md`, the owner
15
+ * `person:<workspaceId>` or `chat:<chatId>`. A row whose key has this form
16
+ * keeps its note's text there (decided by the owner, 2026-10-31).
17
+ */
18
+ const TEX_KEY = /^tex\/(?:person|chat):[A-Za-z0-9_-]{1,64}\/(?:notes|files)\/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?:\.[^/]*)?$/;
19
+
20
+ function isTexKey(key) {
21
+ return typeof key === "string" && TEX_KEY.test(key);
22
+ }
23
+
24
+ /**
25
+ * A group chat's own state in its Durable Object, not a note:
26
+ * tex/chat:<chatKey>/state/<64 hex>.json (its memory record, a rebuildable
27
+ * cache of the visible memory note; `agent/chatMemoryRecord.js`). Only a chat
28
+ * owns one, never a person; no row ever names it, so it is plumbing, and never
29
+ * an id key.
30
+ */
31
+ const TEX_STATE_KEY = /^tex\/chat:[A-Za-z0-9_-]{1,64}\/state\/[0-9a-f]{64}\.json$/;
32
+
33
+ function isTexStateKey(key) {
34
+ return typeof key === "string" && TEX_STATE_KEY.test(key);
35
+ }
36
+
37
+ /**
38
+ * Whether `error` is the gateway's refusal of a Tex key it cannot serve (`TexStoreUnavailable` in
39
+ * `apps/mcp/src/store/texRouting.js`: another workspace's owner, or no way to reach the object), by its name.
40
+ */
41
+ function isTexStoreUnavailable(error) {
42
+ return error instanceof Error && error.name === "TexStoreUnavailable";
43
+ }
44
+
45
+ /** The `.context/agent/` folders a person's Tex bookkeeping lives under, in their object. */
46
+ const AGENT_HOME_FOLDERS = ["history", "turns", "running", "cancel", "steer", "go"];
47
+ const AGENT_HOME = /^\.context\/agent\/(history|turns|running|cancel|steer|go)\/((?:[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}\/){0,2}[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127})$/;
48
+ const AGENT_HOME_PREFIX = /^\.context\/agent\/(history|turns|running|cancel|steer|go)\/((?:[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}\/){0,2})$/;
49
+
50
+ /** Whether `key` is a person's Tex bookkeeping, kept in their object (`state/agent/...`). No `..`, no empty segment. */
51
+ function isAgentHomeKey(key) {
52
+ return typeof key === "string" && AGENT_HOME.test(key) && !key.includes("..");
53
+ }
54
+
55
+ /** `{owner, key}` for a Tex key or a chat's state key: whose object, and the key inside it. */
56
+ function splitTexKey(key) {
57
+ if (!isTexKey(key) && !isTexStateKey(key)) return null;
58
+ const cut = key.indexOf("/", "tex/".length);
59
+ return { owner: key.slice("tex/".length, cut), key: key.slice(cut + 1) };
60
+ }
61
+
62
+ /**
63
+ * Whether a call goes to a Tex Durable Object rather than the bucket, by the
64
+ * same rules as `withTexRouting`: a person's bookkeeping key, a Tex or chat
65
+ * state key, or (for a listing, `prefix: true`) a prefix under either. For
66
+ * timing only (`agent/texTiming.js`); the routing itself decides access.
67
+ */
68
+ function goesToObject(key, { prefix = false } = {}) {
69
+ if (typeof key !== "string" || key.includes("..")) return false;
70
+ if (prefix) return AGENT_HOME_PREFIX.test(key) || /^tex\/(?:person|chat):[A-Za-z0-9_-]{1,64}\//.test(key);
71
+ return isAgentHomeKey(key) || splitTexKey(key) !== null;
72
+ }
73
+
74
+ /** The Tex key for an id key kept in `owner`'s object. */
75
+ function texKeyFor(owner, idKey) {
76
+ const key = `tex/${owner}/${idKey}`;
77
+ if (!isTexKey(key)) throw new TypeError("not an id key, or not an owner");
78
+ return key;
79
+ }
80
+
81
+ /** A group chat's state key: `name` is 64 hex (a SHA-256), kept in that chat's object alone. */
82
+ function texStateKeyFor(chat, name) {
83
+ const key = ["tex", `chat:${chat}`, "state", `${name}.json`].join("/");
84
+ if (!isTexStateKey(key)) throw new TypeError("not a chat, or not a state name");
85
+ return key;
86
+ }
87
+
88
+ module.exports = {
89
+ TEX_KEY,
90
+ isTexKey,
91
+ isTexStateKey,
92
+ isTexStoreUnavailable,
93
+ AGENT_HOME_FOLDERS,
94
+ AGENT_HOME_PREFIX,
95
+ isAgentHomeKey,
96
+ splitTexKey,
97
+ goesToObject,
98
+ texKeyFor,
99
+ texStateKeyFor,
100
+ };
@@ -0,0 +1,13 @@
1
+ /** Types for `texKeys.cjs`; see that file. */
2
+
3
+ export declare const TEX_KEY: RegExp;
4
+ export declare function isTexKey(key: unknown): boolean;
5
+ export declare function isTexStateKey(key: unknown): boolean;
6
+ export declare function isTexStoreUnavailable(error: unknown): boolean;
7
+ export declare const AGENT_HOME_FOLDERS: string[];
8
+ export declare const AGENT_HOME_PREFIX: RegExp;
9
+ export declare function isAgentHomeKey(key: unknown): boolean;
10
+ export declare function splitTexKey(key: unknown): { owner: string; key: string } | null;
11
+ export declare function goesToObject(key: unknown, options?: { prefix?: boolean }): boolean;
12
+ export declare function texKeyFor(owner: string, idKey: string): string;
13
+ export declare function texStateKeyFor(chat: string, name: string): string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The `source`s of a text Tex sends on its own (`sentOnItsOwn.js`): each has a gateway note beside it, so readers
3
+ * show the note and drop the linked text event. The gateway's conversations page reads the same set.
4
+ */
5
+
6
+ /** The `source` of a text Tex sent on its own, outside a reply to a text: these have a gateway note beside them. */
7
+ const OWN_SOURCES = new Set(["checkin", "routine", "ping", "update", "job", "new_line", "notice"]);
8
+
9
+ module.exports = { OWN_SOURCES };
@@ -0,0 +1,3 @@
1
+ /** Types for `texOwnSources.cjs`; see that file. */
2
+
3
+ export declare const OWN_SOURCES: Set<string>;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Names both sides of the Tex store read: what a person's texted turn's desk reads from their chat's ledger
3
+ * (`apps/mcp/src/texStore/desk.js`) and the history and conversations files a chat's Tex object answers as views of
4
+ * its ledger (`apps/mcp/src/texStore/historyView.js`). Both of those re-export them; Tex's code reads them here.
5
+ */
6
+
7
+ /** A person's one-to-one chat with Tex is one ledger, whichever line they text on, as their history record is. */
8
+ const ONE_TO_ONE_CHAT = "texts";
9
+ /** The reads whose arguments a slim read keeps: where a page, search or note came from, for the reads index (`agent/readsIndex.js` `INDEXED_READS`). */
10
+ const READ_ARGS_KEPT = Object.freeze(["open_page", "search_web", "browse", "read_note", "read_notes"]);
11
+ /**
12
+ * The newest page of the person's one-to-one chat's ledger, slim, that the
13
+ * desk answers beside the record (`agent/ledgerHistory.js`): the whole chat a
14
+ * texted turn is shown, in the same call.
15
+ */
16
+ const DESK_LEDGER = Object.freeze({ chat: ONE_TO_ONE_CHAT, options: Object.freeze({ before: Number.MAX_SAFE_INTEGER, kinds: Object.freeze(["text", "note", "tool", "reply", "day"]), limit: 2_000, slim: true, keepArgs: READ_ARGS_KEPT }) });
17
+
18
+ /** What the object keeps under the history file's key: this, and nothing of the chat. */
19
+ const HISTORY_VIEW_MARKER = '{"tex-history-view":1}';
20
+ /** The file's name, in a person's `tex/` and in each group chat's home. */
21
+ const HISTORY_FILE = "history.ledger.json";
22
+ /** The chat's conversations, as a second view beside it (`historyView.js`). */
23
+ const CONVERSATIONS_FILE = "conversations.ledger.json";
24
+ const CONVERSATIONS_VIEW_MARKER = '{"tex-conversations-view":1}';
25
+
26
+ module.exports = { ONE_TO_ONE_CHAT, READ_ARGS_KEPT, DESK_LEDGER, HISTORY_VIEW_MARKER, HISTORY_FILE, CONVERSATIONS_FILE, CONVERSATIONS_VIEW_MARKER };
@@ -0,0 +1,12 @@
1
+ /** Types for `texStoreNames.cjs`; see that file. */
2
+
3
+ export declare const ONE_TO_ONE_CHAT: string;
4
+ export declare const READ_ARGS_KEPT: readonly string[];
5
+ export declare const DESK_LEDGER: {
6
+ readonly chat: string;
7
+ readonly options: { readonly before: number; readonly kinds: readonly string[]; readonly limit: number; readonly slim: boolean; readonly keepArgs: readonly string[] };
8
+ };
9
+ export declare const HISTORY_VIEW_MARKER: string;
10
+ export declare const HISTORY_FILE: string;
11
+ export declare const CONVERSATIONS_FILE: string;
12
+ export declare const CONVERSATIONS_VIEW_MARKER: string;
@@ -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[] }>;