@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.
- package/LICENSE +21 -0
- package/README.md +11 -2
- package/package.json +16 -4
- package/texContract/aboutLines.cjs +117 -0
- package/texContract/aboutLines.d.cts +14 -0
- package/texContract/aboutNoteLimits.cjs +41 -0
- package/texContract/aboutNoteLimits.d.cts +5 -0
- package/texContract/actionManual.cjs +104 -0
- package/texContract/activityHint.cjs +40 -0
- package/texContract/activityHint.d.cts +4 -0
- package/texContract/asks.cjs +16 -0
- package/texContract/asks.d.cts +6 -0
- package/texContract/asksToFile.cjs +20 -0
- package/texContract/asksToFile.d.cts +2 -0
- package/texContract/attention.cjs +138 -0
- package/texContract/attention.d.cts +20 -0
- package/texContract/browserHandback.cjs +13 -0
- package/texContract/browserHandback.d.cts +3 -0
- package/texContract/browserOwner.cjs +31 -0
- package/texContract/browserOwner.d.cts +2 -0
- package/texContract/bytes.cjs +12 -0
- package/texContract/chatHistoryPath.cjs +38 -0
- package/texContract/chatHistoryPath.d.cts +5 -0
- package/texContract/chatLedger.cjs +91 -0
- package/texContract/chatLedger.d.cts +21 -0
- package/texContract/computerTool.cjs +102 -0
- package/texContract/computerTool.d.cts +16 -0
- package/texContract/consentYes.cjs +22 -0
- package/texContract/consentYes.d.cts +5 -0
- package/texContract/contextGateway.cjs +52 -0
- package/texContract/contextGateway.d.cts +19 -0
- package/texContract/deskEligible.cjs +20 -0
- package/texContract/deskEligible.d.cts +3 -0
- package/texContract/downloads.cjs +129 -0
- package/texContract/downloads.d.cts +15 -0
- package/texContract/egressLedger.cjs +114 -0
- package/texContract/egressLedger.d.cts +14 -0
- package/texContract/emailRead.cjs +38 -0
- package/texContract/emailRead.d.cts +5 -0
- package/texContract/eventWords.cjs +35 -0
- package/texContract/eventWords.d.cts +4 -0
- package/texContract/fileParts.cjs +43 -0
- package/texContract/fileParts.d.cts +6 -0
- package/texContract/fileTables.cjs +243 -0
- package/texContract/fileWords.cjs +169 -0
- package/texContract/folded.cjs +16 -0
- package/texContract/folded.d.cts +3 -0
- package/texContract/googleAiAccess.cjs +12 -0
- package/texContract/googleAiAccess.d.cts +2 -0
- package/texContract/graphWires.cjs +18 -0
- package/texContract/graphWires.d.cts +5 -0
- package/texContract/groupSession.cjs +28 -0
- package/texContract/groupSession.d.cts +7 -0
- package/texContract/guestNames.cjs +136 -0
- package/texContract/guestNames.d.cts +35 -0
- package/texContract/heard.cjs +19 -0
- package/texContract/heard.d.cts +4 -0
- package/texContract/heldOffer.cjs +57 -0
- package/texContract/heldOffer.d.cts +8 -0
- package/texContract/helperCallers.cjs +29 -0
- package/texContract/helperCallers.d.cts +4 -0
- package/texContract/identity.cjs +179 -0
- package/texContract/identity.d.cts +8 -0
- package/texContract/jobLogEntries.cjs +93 -0
- package/texContract/jobLogEntries.d.cts +12 -0
- package/texContract/judgedActions.cjs +20 -0
- package/texContract/judgedActions.d.cts +4 -0
- package/texContract/labSandboxGate.cjs +63 -0
- package/texContract/labSandboxGate.d.cts +9 -0
- package/texContract/ledgerReadChars.cjs +4 -0
- package/texContract/ledgerReadChars.d.cts +3 -0
- package/texContract/mailCheck.cjs +90 -0
- package/texContract/mailCheck.d.cts +12 -0
- package/texContract/mailEntries.cjs +64 -0
- package/texContract/mailEntries.d.cts +13 -0
- package/texContract/mailHealth.cjs +60 -0
- package/texContract/mailHealth.d.cts +10 -0
- package/texContract/notePath.cjs +99 -0
- package/texContract/notePath.d.cts +4 -0
- package/texContract/noteRunFacts.cjs +136 -0
- package/texContract/noteRunFacts.d.cts +32 -0
- package/texContract/objectEtag.cjs +84 -0
- package/texContract/objectEtag.d.cts +4 -0
- package/texContract/objectPlace.cjs +32 -0
- package/texContract/objectPlace.d.cts +5 -0
- package/texContract/pageJobs.cjs +226 -0
- package/texContract/pageJobs.d.cts +13 -0
- package/texContract/pdfLinks.cjs +135 -0
- package/texContract/pdfLinks.d.cts +4 -0
- package/texContract/personHub.cjs +38 -0
- package/texContract/personHub.d.cts +5 -0
- package/texContract/personNameText.cjs +18 -0
- package/texContract/personNameText.d.cts +3 -0
- package/texContract/pinnedContext.cjs +12 -0
- package/texContract/pinnedContext.d.cts +3 -0
- package/texContract/quietHoursWindow.cjs +36 -0
- package/texContract/quietHoursWindow.d.cts +3 -0
- package/texContract/scopeClamp.cjs +117 -0
- package/texContract/scopeClamp.d.cts +5 -0
- package/texContract/scopes.cjs +29 -0
- package/texContract/scopes.d.cts +7 -0
- package/texContract/searchSettings.cjs +54 -0
- package/texContract/searchSettings.d.cts +6 -0
- package/texContract/settingHabits.cjs +87 -0
- package/texContract/settingHabits.d.cts +20 -0
- package/texContract/settingsNotes.cjs +217 -0
- package/texContract/settingsNotes.d.cts +26 -0
- package/texContract/shownEmail.cjs +181 -0
- package/texContract/texClients.cjs +53 -0
- package/texContract/texClients.d.cts +12 -0
- package/texContract/texGraph.cjs +593 -0
- package/texContract/texGraph.d.cts +55 -0
- package/texContract/texKeys.cjs +100 -0
- package/texContract/texKeys.d.cts +13 -0
- package/texContract/texOwnSources.cjs +9 -0
- package/texContract/texOwnSources.d.cts +3 -0
- package/texContract/texStoreNames.cjs +26 -0
- package/texContract/texStoreNames.d.cts +12 -0
- package/texContract/texStoreWire.cjs +306 -0
- package/texContract/texStoreWire.d.cts +32 -0
- package/texContract/threadsFold.cjs +75 -0
- package/texContract/threadsFold.d.cts +22 -0
- package/texContract/toolActions.cjs +253 -0
- package/texContract/toolCatalog.cjs +49 -0
- package/texContract/toolCatalog.generated.json +90 -0
- package/texContract/toolContract.cjs +52 -0
- package/texContract/toolContract.d.cts +12 -0
- package/texContract/toolShapes.cjs +14 -0
- package/texContract/transcription.cjs +101 -0
- package/texContract/transcription.d.cts +3 -0
- package/texContract/treeJobs.cjs +31 -0
- package/texContract/treeJobs.d.cts +3 -0
- package/texContract/turnSession.cjs +90 -0
- package/texContract/turnSession.d.cts +19 -0
- package/texContract/turnWords.cjs +90 -0
- package/texContract/turnWords.d.cts +9 -0
- package/texContract/uploadImages.cjs +131 -0
- package/texContract/uploadImages.d.cts +13 -0
- package/texContract/v2Names.cjs +41 -0
- package/texContract/v2SearchFetch.cjs +316 -0
- package/texContract/v2Translate.cjs +123 -0
- package/texContract/vaultTools.cjs +112 -0
- package/texContract/vaultTools.d.cts +15 -0
- package/texContract/yesWords.cjs +91 -0
- package/texShared/argumentCoercion.cjs +93 -0
- package/texShared/cellComments.cjs +122 -0
- package/texShared/cellComments.d.cts +21 -0
- package/texShared/comments.cjs +586 -0
- package/texShared/comments.d.cts +115 -0
- package/texShared/contentTypes.cjs +85 -0
- package/texShared/fileKinds.cjs +123 -0
- package/texShared/flags.cjs +124 -0
- package/texShared/flags.d.cts +21 -0
- package/texShared/folderJobInfo.cjs +301 -0
- package/texShared/folderJobInfo.d.cts +40 -0
- package/texShared/folderRoles.cjs +512 -0
- package/texShared/folderRoles.d.cts +73 -0
- package/texShared/githubOidc.ts +98 -0
- package/texShared/groupRunQuestions.cjs +98 -0
- package/texShared/groupRunQuestions.d.cts +4 -0
- package/texShared/inboxFolders.cjs +49 -0
- package/texShared/inboxFolders.d.cts +5 -0
- package/texShared/ink/drawing.cjs +474 -0
- package/texShared/ink/texFigure.cjs +252 -0
- package/texShared/ink/texFigure.d.cts +36 -0
- package/texShared/ink/texPoses.cjs +180 -0
- package/texShared/ink/texPoses.d.cts +20 -0
- package/texShared/jobPartEnd.cjs +133 -0
- package/texShared/jobPartEnd.d.cts +13 -0
- package/texShared/jobResume.cjs +31 -0
- package/texShared/jobResume.d.cts +5 -0
- package/texShared/jobSplit.cjs +90 -0
- package/texShared/jobSplit.d.cts +6 -0
- package/texShared/jobStart.cjs +56 -0
- package/texShared/jobStart.d.cts +9 -0
- package/texShared/mail.cjs +400 -0
- package/texShared/mail.d.cts +56 -0
- package/texShared/messageAnchors.cjs +38 -0
- package/texShared/models/aiKeys.cjs +137 -0
- package/texShared/models/aiKeys.d.cts +42 -0
- package/texShared/models/aiKeys.json +56 -0
- package/texShared/models/creditRest.cjs +269 -0
- package/texShared/models/promptBudget.cjs +295 -0
- package/texShared/models/promptSections.cjs +29 -0
- package/texShared/noteAppLink.cjs +23 -0
- package/texShared/notePreview.cjs +219 -0
- package/texShared/notePreview.d.cts +21 -0
- package/texShared/pages/blocks.cjs +215 -0
- package/texShared/pages/cover.cjs +164 -0
- package/texShared/pages/css.cjs +181 -0
- package/texShared/pages/cssBlocks.cjs +264 -0
- package/texShared/pages/draw.cjs +212 -0
- package/texShared/pages/drawRich.cjs +232 -0
- package/texShared/pages/html.cjs +168 -0
- package/texShared/pages/inline.cjs +251 -0
- package/texShared/pages/layout.cjs +76 -0
- package/texShared/pages/parse.cjs +418 -0
- package/texShared/pages/render.cjs +200 -0
- package/texShared/pages/skill.cjs +147 -0
- package/texShared/pages/skill.d.cts +5 -0
- package/texShared/pages/templates.cjs +336 -0
- package/texShared/r2Store.cjs +163 -0
- package/texShared/remoteImage.cjs +177 -0
- package/texShared/routines.cjs +656 -0
- package/texShared/routines.d.cts +86 -0
- package/texShared/servedListing.cjs +250 -0
- package/texShared/servedListing.d.cts +17 -0
- package/texShared/sheetCsv.cjs +566 -0
- package/texShared/sheetCsv.d.cts +91 -0
- package/texShared/storageLayout.cjs +88 -0
- package/texShared/storeKeys.cjs +144 -0
- package/texShared/toolArguments.cjs +323 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Types for `mailHealth.cjs`; see that file. */
|
|
2
|
+
|
|
3
|
+
export type Mailbox = { address: string; state: string; lastSyncedAt?: number; tell?: boolean };
|
|
4
|
+
|
|
5
|
+
export declare const NEEDS_PERSON: Set<string>;
|
|
6
|
+
export declare const WORTH_SAYING: Set<string>;
|
|
7
|
+
export declare function readMailHealth(store: unknown): Promise<Mailbox[]>;
|
|
8
|
+
export declare function since(at: unknown, now: number): string;
|
|
9
|
+
export declare function mailboxLine(mailbox: Mailbox, now: number, options?: { v2?: boolean }): string | null;
|
|
10
|
+
export declare function orientMailSection(mailboxes: Mailbox[], now: number, options?: { v2?: boolean }): string | null;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A note path as every tool's path argument is normalized (`normalizePath`),
|
|
3
|
+
* and a path segment as the storage layer will finally read it
|
|
4
|
+
* (`decodeSegment`): pure rules the gateway (`apps/mcp/src/notes/paths.js`,
|
|
5
|
+
* `store/index.js`, which re-export them) and Tex both read, so Tex reaches
|
|
6
|
+
* neither gateway module. Moved verbatim.
|
|
7
|
+
*/
|
|
8
|
+
"use strict";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A path segment as the storage layer will finally read it.
|
|
12
|
+
*
|
|
13
|
+
* Exported because the gateway's `normalizePath` needs the same answer at its
|
|
14
|
+
* own door: `encodeRfc3986` leaves "." unencoded, so `%2e%2e` reaches storage
|
|
15
|
+
* as `..` while containing neither dot literally. The DECODING is the subtle
|
|
16
|
+
* half and lives here once; each layer still states its own segment rule, so
|
|
17
|
+
* neither is only covered by the other.
|
|
18
|
+
*/
|
|
19
|
+
function decodeSegment(segment) {
|
|
20
|
+
if (!segment.includes("%")) return segment;
|
|
21
|
+
try {
|
|
22
|
+
return decodeURIComponent(segment);
|
|
23
|
+
} catch {
|
|
24
|
+
// A malformed escape stays literal; it is encoded again on the way out.
|
|
25
|
+
return segment;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function normalizePath(p) {
|
|
30
|
+
if (typeof p !== "string") return null;
|
|
31
|
+
// A trailing slash is stripped rather than rejected. "1-projects/" is a
|
|
32
|
+
// natural way to name a folder — scope_info and search_notes get asked it
|
|
33
|
+
// routinely — and leaving it on produces an empty final segment that the
|
|
34
|
+
// storage adapter refuses, surfacing a reasonable question as an internal
|
|
35
|
+
// error. move_folder already stripped it locally; doing it here covers every
|
|
36
|
+
// caller.
|
|
37
|
+
const clean = p
|
|
38
|
+
.replace(/^\/+/, "")
|
|
39
|
+
.replace(/\/{2,}/g, "/")
|
|
40
|
+
.replace(/\/+$/, "")
|
|
41
|
+
.trim();
|
|
42
|
+
if (!clean || clean.length > 512) return null;
|
|
43
|
+
// No control characters, and a newline is the one that mattered.
|
|
44
|
+
//
|
|
45
|
+
// `privacy.md` is a line-oriented format and `renderPrivacyRulesBlock`
|
|
46
|
+
// interpolates a path into it unescaped. A path carrying `\n` therefore wrote
|
|
47
|
+
// its own extra rules: `write_note` with
|
|
48
|
+
// `path: "1-projects/secret.md: team\n 1-projects/junk.md"` and
|
|
49
|
+
// `visibility: "private"` rendered a SECOND override for the real note, which
|
|
50
|
+
// the parser reads after the first and lets win — publishing a private note
|
|
51
|
+
// while the call declared `private`, so `isPublishing` was false and no
|
|
52
|
+
// confirmation was asked for. `set_folder_visibility` defeated its own impact
|
|
53
|
+
// report the same way, since `visibilityOf` matched the injected prefix
|
|
54
|
+
// exactly and reported `newly_team_visible_notes: 0`.
|
|
55
|
+
//
|
|
56
|
+
// Rejected here, at the one place every tool's path argument arrives, rather
|
|
57
|
+
// than escaped at the renderer: a path with a newline in it is not a path any
|
|
58
|
+
// store can hold, so there is nothing to preserve. `persistExactVisibility`
|
|
59
|
+
// round-trips the rendered rule as well — see `writableAsRule` in the control
|
|
60
|
+
// plane for why a blacklist alone is a guess about a parser.
|
|
61
|
+
if (/[\u0000-\u001F\u007F]/.test(clean)) return null;
|
|
62
|
+
/*
|
|
63
|
+
"." AND ".." ARE SEGMENTS, NOT SUBSTRINGS — AND `%2e` IS BOTH.
|
|
64
|
+
|
|
65
|
+
A "." segment is rejected here on purpose. It was previously caught only as
|
|
66
|
+
a side effect of isPlumbing() hiding dot-prefixed folders, which is not a
|
|
67
|
+
path rule and could be relaxed without anyone noticing.
|
|
68
|
+
|
|
69
|
+
".." used to be refused as a SUBSTRING, which is a different rule and was
|
|
70
|
+
wrong in both directions. It refused a file the gateway could see:
|
|
71
|
+
`v1..v2.md` is an ordinary S3 key, and the customer's bucket is written
|
|
72
|
+
directly by Obsidian sync, rclone and the provider console — the three
|
|
73
|
+
writers `writableAsRule` names — so a name with two dots in it arrives
|
|
74
|
+
without the gateway's involvement. `list_notes` listed it and
|
|
75
|
+
`search_notes` printed its body while every path-taking tool answered
|
|
76
|
+
"invalid path", which left a note its owner could not make private.
|
|
77
|
+
|
|
78
|
+
And it let one through. `encodeRfc3986` leaves "." unencoded, so `%2e%2e`
|
|
79
|
+
contains no ".." literally: it passed this door, reached `assertSafeKey` at
|
|
80
|
+
the storage boundary, and came back as a JSON-RPC **internal error** where
|
|
81
|
+
its plain twin came back as a tool error. The traversal was refused either
|
|
82
|
+
way; a refusal that changes shape with how far the input travelled is a
|
|
83
|
+
refusal that says where the doors are.
|
|
84
|
+
|
|
85
|
+
`decodeSegment` is the adapter's, because decode-then-compare is the subtle
|
|
86
|
+
half and two copies of it would drift. The RULE is stated here anyway, in
|
|
87
|
+
full, rather than by calling `assertSafeKey`: that would have caught control
|
|
88
|
+
characters too, and **measured, it masked them**: with the whole adapter
|
|
89
|
+
check at this door, deleting the newline guard above reddened **0**, where
|
|
90
|
+
on its own it reddens **2**. That guard was installed by a filed defect, so
|
|
91
|
+
a version of this fix that made its removal invisible was not worth the
|
|
92
|
+
lines it saved. A guard whose removal reddens nothing is not a guard.
|
|
93
|
+
*/
|
|
94
|
+
if (clean.split("/").some((segment) => decodeSegment(segment) === ".")) return null;
|
|
95
|
+
if (clean.split("/").some((segment) => decodeSegment(segment) === "..")) return null;
|
|
96
|
+
return clean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { decodeSegment, normalizePath };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE FACTS A RUN OF TEX IN A NOTE IS ASKED WITH, CHECKED THE SAME WAY ON BOTH SIDES
|
|
3
|
+
* (`docs/decisions/texting-assistant/tex-service.md`, "Tex in a note and in mail").
|
|
4
|
+
*
|
|
5
|
+
* Context's routes (`apps/mcp/src/http/noteRunDoor.js`, `mailRunDoor.js`) check who asks and read the note as the
|
|
6
|
+
* person, then hand Tex's Worker the facts; the Lab's run (`packages/tex/gateway/agent/noteRunLab.js`) checks them the
|
|
7
|
+
* same way in-process. Pure: a body's shape, the workspace a session reaches, a `read_note` answer read as a note, and
|
|
8
|
+
* the key a note's run log is kept under.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const { isSheetPath, MAX_SHEET_ROWS } = require("../texShared/sheetCsv.cjs");
|
|
12
|
+
|
|
13
|
+
const MAX_ID = 128;
|
|
14
|
+
const MAX_PATH = 512;
|
|
15
|
+
const MAX_ASK = 4_000;
|
|
16
|
+
const MAX_ANCHOR_TEXT = 20_000;
|
|
17
|
+
const MAX_ANCHOR_CONTEXT = 400;
|
|
18
|
+
const MAX_HISTORY = 20;
|
|
19
|
+
const MAX_HISTORY_BODY = 4_000;
|
|
20
|
+
const MAX_WHO = 200;
|
|
21
|
+
const MAX_PENDING = 20_000;
|
|
22
|
+
/** The longest column name a sheet's cell may name. */
|
|
23
|
+
const MAX_COLUMN_CHARS = 200;
|
|
24
|
+
const ID_TEXT = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
25
|
+
/** The phrase for who a note is shared with, by the visibility its read gave (`read_note`'s `visibility:` line). */
|
|
26
|
+
const AUDIENCE = Object.freeze({ private: "only you", team: "the team it is shared with" });
|
|
27
|
+
const AUDIENCE_OTHER = "the people this note is shared with";
|
|
28
|
+
|
|
29
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
30
|
+
const text = (value, max, min = 0) => typeof value === "string" && value.length >= min && value.length <= max;
|
|
31
|
+
|
|
32
|
+
/** The cell a thread is on: `{ row, column }`, row counted from 0 in the file. */
|
|
33
|
+
function isSheetCell(value) {
|
|
34
|
+
return isObject(value) && Number.isInteger(value.row) && value.row >= 0 && typeof value.column === "string" && value.column.length > 0 && value.column.length <= MAX_COLUMN_CHARS;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The validated body, or the reason it is refused. Nothing in it is trusted past this point: every field is the shape
|
|
39
|
+
* and size the route's contract names (D1 section 3).
|
|
40
|
+
*/
|
|
41
|
+
function parseRunBody(body) {
|
|
42
|
+
if (!isObject(body)) return { error: "The body is not an object. Send a JSON object with workspace, path, thread, anchor, ask, history and pending." };
|
|
43
|
+
const { workspace, noteId, path, thread, anchor, ask, history, pending, cell } = body;
|
|
44
|
+
if (!text(workspace, MAX_ID, 1)) return { error: "workspace is missing. Send the note's workspace id or @name, then try again." };
|
|
45
|
+
// The client's note id is optional and never trusted: the log's key is derived from the note as read (`logKeyOf`).
|
|
46
|
+
if (noteId !== undefined && (!text(noteId, MAX_ID) || (noteId !== "" && !ID_TEXT.test(noteId)))) return { error: "noteId is not a note's id. Send it empty, then try again." };
|
|
47
|
+
if (!text(path, MAX_PATH, 1)) return { error: `path is missing or too long. Send the note's path, up to ${MAX_PATH} characters, then try again.` };
|
|
48
|
+
if (!text(thread, MAX_ID, 1)) return { error: "thread is missing. Send the comment thread's id, then try again." };
|
|
49
|
+
if (!isObject(anchor) || !text(anchor.text, MAX_ANCHOR_TEXT) || !text(anchor.before, MAX_ANCHOR_CONTEXT) || !text(anchor.after, MAX_ANCHOR_CONTEXT)) {
|
|
50
|
+
return { error: `anchor is not right. Send { text (up to ${MAX_ANCHOR_TEXT}), before and after (up to ${MAX_ANCHOR_CONTEXT}) }, then try again.` };
|
|
51
|
+
}
|
|
52
|
+
const words = typeof ask === "string" ? ask.trim() : "";
|
|
53
|
+
if (words === "" || words.length > MAX_ASK) return { error: `The ask is empty or too long. Ask Tex in 1 to ${MAX_ASK} characters, then try again.` };
|
|
54
|
+
if (!Array.isArray(history) || history.length > MAX_HISTORY) return { error: `history is too long. Send up to ${MAX_HISTORY} texts, then try again.` };
|
|
55
|
+
for (const item of history) {
|
|
56
|
+
if (!isObject(item) || !text(item.who, MAX_WHO) || !text(item.body, MAX_HISTORY_BODY)) {
|
|
57
|
+
return { error: `A history text is not right. Send each as { who, body (up to ${MAX_HISTORY_BODY}) }, then try again.` };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (pending !== null && !text(pending, MAX_PENDING)) return { error: `pending is too long. Send null or up to ${MAX_PENDING} characters, then try again.` };
|
|
61
|
+
// A thread on a sheet's cell names its cell: a row of the file (from 0) and a column. Only a sheet has cells.
|
|
62
|
+
if (cell !== undefined && cell !== null && (!isSheetCell(cell) || cell.row >= MAX_SHEET_ROWS || !isSheetPath(path))) {
|
|
63
|
+
return { error: "cell: send { row, column }" };
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
workspace,
|
|
67
|
+
noteId,
|
|
68
|
+
path,
|
|
69
|
+
thread,
|
|
70
|
+
anchor: { text: anchor.text, before: anchor.before, after: anchor.after },
|
|
71
|
+
ask: words,
|
|
72
|
+
history: history.map((item) => ({ who: item.who, body: item.body })),
|
|
73
|
+
pending,
|
|
74
|
+
cell: cell === undefined || cell === null ? null : { row: cell.row, column: cell.column },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The workspace the body names, if the person is a live member of it: an id or an `@name` the control plane's set holds.
|
|
80
|
+
* `context` is what the read names: nothing for the person's own workspace, `@name` for another.
|
|
81
|
+
*/
|
|
82
|
+
function targetOf(session, workspace) {
|
|
83
|
+
const covered = (session?.workspaces ?? []).find(
|
|
84
|
+
(entry) => typeof entry?.workspaceId === "string" && (entry.workspaceId === workspace || (typeof entry.slug === "string" && entry.slug !== "" && `@${entry.slug}` === workspace)),
|
|
85
|
+
);
|
|
86
|
+
if (covered === undefined) return null;
|
|
87
|
+
if (covered.workspaceId === session.workspaceId) return { workspaceId: covered.workspaceId, context: undefined };
|
|
88
|
+
if (typeof covered.slug !== "string" || covered.slug === "") return null;
|
|
89
|
+
return { workspaceId: covered.workspaceId, context: `@${covered.slug}` };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The text of a tool result, as the note reads have it (`texPage/notes.js` reads the same way). */
|
|
93
|
+
function textOf(result) {
|
|
94
|
+
return (Array.isArray(result?.content) ? result.content : []).map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The note as the person can read it: `{ note, audience, noteId }`, or null when `read_note` refuses it, cannot find
|
|
99
|
+
* it, or says it moved. The header lines are the tool's own (`etag`, `path`, `visibility`).
|
|
100
|
+
*/
|
|
101
|
+
async function readNoteAs(dispatch, path, context) {
|
|
102
|
+
let result;
|
|
103
|
+
try {
|
|
104
|
+
result = await dispatch("read_note", { path, ...(context === undefined ? {} : { context }) });
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
if (result?.isError === true) return null;
|
|
109
|
+
const whole = textOf(result);
|
|
110
|
+
const split = whole.indexOf("\n\n");
|
|
111
|
+
const header = split === -1 ? whole : whole.slice(0, split);
|
|
112
|
+
if (/^moved_from:/m.test(header)) return null;
|
|
113
|
+
const visibility = /^visibility: (.+)$/m.exec(header)?.[1]?.trim() ?? null;
|
|
114
|
+
const audience = visibility !== null && Object.hasOwn(AUDIENCE, visibility) ? AUDIENCE[visibility] : AUDIENCE_OTHER;
|
|
115
|
+
const etag = /^etag: (.+)$/m.exec(header)?.[1]?.trim() ?? null;
|
|
116
|
+
// A placed etag is `@workspace/noteId:version` (`apps/mcp/src/tools/etagPlace.js`); a bare one names no note.
|
|
117
|
+
const placed = typeof etag === "string" ? /^@[a-z0-9][a-z0-9-]*\/([A-Za-z0-9_-]+):/.exec(etag) : null;
|
|
118
|
+
return { note: split === -1 ? "" : whole.slice(split + 2), audience, noteId: placed?.[1] ?? null };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The key a note's run log is kept under: the note's own id, as its placed etag names it, or a hash of its path for a
|
|
123
|
+
* note without one. Never the id the client sent: a key it chose could write runs into a note it cannot read.
|
|
124
|
+
*/
|
|
125
|
+
async function logKeyOf(note, path) {
|
|
126
|
+
if (typeof note?.noteId === "string" && ID_TEXT.test(note.noteId)) return note.noteId;
|
|
127
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(path)));
|
|
128
|
+
return `p${[...digest.slice(0, 16)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Whether `key` is one `logKeyOf` could have answered. */
|
|
132
|
+
function isLogKey(key) {
|
|
133
|
+
return typeof key === "string" && ID_TEXT.test(key);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = { MAX_COLUMN_CHARS, isSheetCell, parseRunBody, targetOf, readNoteAs, logKeyOf, isLogKey };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Types for `noteRunFacts.cjs`; see that file. */
|
|
2
|
+
|
|
3
|
+
export interface SheetCell {
|
|
4
|
+
row: number;
|
|
5
|
+
column: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RunBody {
|
|
9
|
+
workspace: string;
|
|
10
|
+
noteId: string | undefined;
|
|
11
|
+
path: string;
|
|
12
|
+
thread: string;
|
|
13
|
+
anchor: { text: string; before: string; after: string };
|
|
14
|
+
ask: string;
|
|
15
|
+
history: { who: string; body: string }[];
|
|
16
|
+
pending: string | null;
|
|
17
|
+
cell: SheetCell | null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface NoteAsRead {
|
|
21
|
+
note: string;
|
|
22
|
+
audience: string;
|
|
23
|
+
noteId: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export declare const MAX_COLUMN_CHARS: number;
|
|
27
|
+
export declare function isSheetCell(value: unknown): value is SheetCell;
|
|
28
|
+
export declare function parseRunBody(body: unknown): RunBody | { error: string };
|
|
29
|
+
export declare function targetOf(session: unknown, workspace: string): { workspaceId: string; context: string | undefined } | null;
|
|
30
|
+
export declare function readNoteAs(dispatch: (name: string, args: object) => Promise<unknown>, path: string, context: string | undefined): Promise<NoteAsRead | null>;
|
|
31
|
+
export declare function logKeyOf(note: { noteId?: string | null } | null, path: string): Promise<string>;
|
|
32
|
+
export declare function isLogKey(key: unknown): key is string;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHA-256 without a promise, so a note's etag can be chosen inside one Durable Object storage transaction
|
|
3
|
+
* (`texStore/objects.js`). `crypto.subtle.digest` is the same digest and an await, and an await there ends the
|
|
4
|
+
* transaction before the bytes are stored. The first 16 bytes, hex, are the etag.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const K = new Uint32Array([
|
|
8
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
9
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
10
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
11
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
12
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
13
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
14
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
15
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
19
|
+
|
|
20
|
+
/** SHA-256 of `bytes`. */
|
|
21
|
+
function sha256(bytes) {
|
|
22
|
+
const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
23
|
+
const bitLen = data.length * 8;
|
|
24
|
+
const pad = (64 - ((data.length + 1 + 8) % 64)) % 64;
|
|
25
|
+
const buf = new Uint8Array(data.length + 1 + pad + 8);
|
|
26
|
+
buf.set(data);
|
|
27
|
+
buf[data.length] = 0x80;
|
|
28
|
+
const view = new DataView(buf.buffer);
|
|
29
|
+
view.setUint32(buf.length - 8, Math.floor(bitLen / 0x100000000));
|
|
30
|
+
view.setUint32(buf.length - 4, bitLen >>> 0);
|
|
31
|
+
|
|
32
|
+
let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
|
|
33
|
+
let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
|
|
34
|
+
const w = new Uint32Array(64);
|
|
35
|
+
|
|
36
|
+
for (let off = 0; off < buf.length; off += 64) {
|
|
37
|
+
for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(off + i * 4);
|
|
38
|
+
for (let i = 16; i < 64; i += 1) {
|
|
39
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
|
40
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
|
41
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
42
|
+
}
|
|
43
|
+
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
|
|
44
|
+
for (let i = 0; i < 64; i += 1) {
|
|
45
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
46
|
+
const ch = (e & f) ^ (~e & g);
|
|
47
|
+
const temp1 = (h + s1 + ch + K[i] + w[i]) >>> 0;
|
|
48
|
+
const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
49
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
50
|
+
const temp2 = (s0 + maj) >>> 0;
|
|
51
|
+
h = g;
|
|
52
|
+
g = f;
|
|
53
|
+
f = e;
|
|
54
|
+
e = (d + temp1) >>> 0;
|
|
55
|
+
d = c;
|
|
56
|
+
c = b;
|
|
57
|
+
b = a;
|
|
58
|
+
a = (temp1 + temp2) >>> 0;
|
|
59
|
+
}
|
|
60
|
+
h0 = (h0 + a) >>> 0;
|
|
61
|
+
h1 = (h1 + b) >>> 0;
|
|
62
|
+
h2 = (h2 + c) >>> 0;
|
|
63
|
+
h3 = (h3 + d) >>> 0;
|
|
64
|
+
h4 = (h4 + e) >>> 0;
|
|
65
|
+
h5 = (h5 + f) >>> 0;
|
|
66
|
+
h6 = (h6 + g) >>> 0;
|
|
67
|
+
h7 = (h7 + h) >>> 0;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const out = new Uint8Array(32);
|
|
71
|
+
const words = new DataView(out.buffer);
|
|
72
|
+
[h0, h1, h2, h3, h4, h5, h6, h7].forEach((word, index) => words.setUint32(index * 4, word));
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The object's etag: the first 16 bytes of SHA-256, as hex. */
|
|
77
|
+
function etagHex(bytes) {
|
|
78
|
+
const digest = sha256(bytes);
|
|
79
|
+
let hex = "";
|
|
80
|
+
for (let index = 0; index < 16; index += 1) hex += digest[index].toString(16).padStart(2, "0");
|
|
81
|
+
return hex;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { sha256, etagHex };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the gateway Worker's Durable Objects are placed: eastern North America,
|
|
3
|
+
* every one of them (decided by the owner, 2026-11-01). Moved from
|
|
4
|
+
* `apps/mcp/src/objectPlace.js`, which re-exports it, so Tex's code makes its
|
|
5
|
+
* own objects' stubs without reaching a gateway module.
|
|
6
|
+
*
|
|
7
|
+
* An object is placed once, near whatever first asks for it, and never moves.
|
|
8
|
+
* Tex's objects had no hint, and the first calls to the six busiest came from
|
|
9
|
+
* gateway requests that ran in London on 2026-10-31, so those objects live in
|
|
10
|
+
* London and Amsterdam while the gateway runs in Virginia, and every call to
|
|
11
|
+
* them crosses the Atlantic. The hint only places an object that does not
|
|
12
|
+
* exist yet; one already placed elsewhere has to be copied to a new name.
|
|
13
|
+
*
|
|
14
|
+
* `scripts/check-durable-object-location.mjs` fails CI on any
|
|
15
|
+
* `idFromName`/`idFromString` outside this file and the other placers it lists.
|
|
16
|
+
*/
|
|
17
|
+
"use strict";
|
|
18
|
+
|
|
19
|
+
/** The one location hint every object in this Worker is created with. */
|
|
20
|
+
const OBJECT_LOCATION = "enam";
|
|
21
|
+
|
|
22
|
+
/** The stub for the object named `name` in `namespace`, placed in eastern North America if it is new. */
|
|
23
|
+
function objectByName(namespace, name) {
|
|
24
|
+
return namespace.get(namespace.idFromName(name), { locationHint: OBJECT_LOCATION });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The id the object named `name` has, as Cloudflare's analytics show it: for logs that tie a name to its object. Makes no stub. */
|
|
28
|
+
function objectIdOf(namespace, name) {
|
|
29
|
+
return String(namespace.idFromName(name));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports = { OBJECT_LOCATION, objectByName, objectIdOf };
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A chat's background jobs, for its Tex page: read from the chat's inbox in
|
|
3
|
+
* the texting Worker over the `TEXTING` binding (`TexRoutines.pageJobs`,
|
|
4
|
+
* `packages/tex/worker/texPage.ts`), and shaped as the page shows them. Used by the
|
|
5
|
+
* page's routes and by the chat's Tex object while a page is open
|
|
6
|
+
* (`texStore/pageLive.js`), so both say the same thing.
|
|
7
|
+
*
|
|
8
|
+
* Every word is Tex's own (a job's title, its status line, its steps: tool and
|
|
9
|
+
* target, never a note's text).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** How many jobs run at once (`MAX_RUNNING_JOBS`, `packages/tex/worker/jobs.ts`): the page's minion slots. */
|
|
13
|
+
const SLOTS = 3;
|
|
14
|
+
/** The finished jobs the overview shows under "Earlier today". */
|
|
15
|
+
const EARLIER_SHOWN = 2;
|
|
16
|
+
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
17
|
+
const MAX_WORDS = 300;
|
|
18
|
+
const MAX_STEPS = 40;
|
|
19
|
+
|
|
20
|
+
const words = (value, max = MAX_WORDS) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, max) : "");
|
|
21
|
+
const instant = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null);
|
|
22
|
+
|
|
23
|
+
/** The page's state words for the inbox's: a stuck job is shown as failed. */
|
|
24
|
+
function stateOf(job) {
|
|
25
|
+
if (job.stopped === true) return "stopped";
|
|
26
|
+
switch (job.state) {
|
|
27
|
+
case "running":
|
|
28
|
+
case "waiting":
|
|
29
|
+
case "done":
|
|
30
|
+
case "failed":
|
|
31
|
+
return job.state;
|
|
32
|
+
case "stuck":
|
|
33
|
+
return "failed";
|
|
34
|
+
default:
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function stepsOf(job) {
|
|
40
|
+
return (Array.isArray(job.steps) ? job.steps : [])
|
|
41
|
+
.flatMap((step) => {
|
|
42
|
+
const at = instant(step?.at);
|
|
43
|
+
const text = words(step?.text);
|
|
44
|
+
if (at === null || !text) return [];
|
|
45
|
+
const failed = step.failed === true;
|
|
46
|
+
const why = failed ? words(step.why, 160) : "";
|
|
47
|
+
return [{ at, text, ...(failed ? { failed: true } : {}), ...(why ? { why } : {}) }];
|
|
48
|
+
})
|
|
49
|
+
.slice(-MAX_STEPS);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** One job as the texting Worker answered it, checked field by field; null when it is not one. */
|
|
53
|
+
function readJob(raw) {
|
|
54
|
+
if (raw === null || typeof raw !== "object" || typeof raw.id !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(raw.id)) return null;
|
|
55
|
+
const title = words(raw.title, 160);
|
|
56
|
+
const startedAt = instant(raw.startedAt);
|
|
57
|
+
const state = stateOf(raw);
|
|
58
|
+
if (!title || startedAt === null || state === null) return null;
|
|
59
|
+
const endedAt = instant(raw.finishedAt);
|
|
60
|
+
const status = words(raw.status, 200);
|
|
61
|
+
const who = words(raw.for, 40);
|
|
62
|
+
const result = words(raw.result, 1500);
|
|
63
|
+
const on = machineOf(raw.on);
|
|
64
|
+
return { id: raw.id, title, state, startedAt, ...(endedAt !== null ? { endedAt } : {}), ...(status ? { status } : {}), ...(who ? { for: who } : {}), ...(result ? { result } : {}), ...(on ? { on } : {}), steps: stepsOf(raw) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const TOOL_NAMES = { claude: "Claude Code", codex: "Codex" };
|
|
68
|
+
|
|
69
|
+
/** The person's computer a job runs on, as the inbox names it (`{id, name, tool?}`); null in Tex's cloud. */
|
|
70
|
+
function machineOf(raw) {
|
|
71
|
+
if (raw === null || typeof raw !== "object" || typeof raw.id !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(raw.id)) return null;
|
|
72
|
+
const name = words(raw.name, 100) || "your computer";
|
|
73
|
+
return { id: raw.id, name, ...(TOOL_NAMES[raw.tool] ? { tool: TOOL_NAMES[raw.tool] } : {}) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The page's `JobSummary` for a read job (`slot` when it holds one). */
|
|
77
|
+
function jobSummary(job, slot = null) {
|
|
78
|
+
const failedSteps = job.steps.filter((step) => step.failed).length;
|
|
79
|
+
const last = job.steps[job.steps.length - 1];
|
|
80
|
+
return {
|
|
81
|
+
id: job.id,
|
|
82
|
+
title: job.title,
|
|
83
|
+
state: job.state,
|
|
84
|
+
startedAt: job.startedAt,
|
|
85
|
+
...(job.endedAt !== undefined ? { endedAt: job.endedAt } : {}),
|
|
86
|
+
failedSteps,
|
|
87
|
+
...(job.state === "waiting" && job.status ? { needs: job.status } : {}),
|
|
88
|
+
...(job.state === "running" && last ? { now: last.text } : {}),
|
|
89
|
+
...(job.for ? { for: job.for } : {}),
|
|
90
|
+
// Where it runs: the page's place key for the computer, and its name in words (`On Cloud VM`).
|
|
91
|
+
...(job.on ? { machine: job.on.id, machineName: job.on.name, ranOn: `On ${job.on.name}`, ...(job.on.tool ? { tool: job.on.tool } : {}) } : {}),
|
|
92
|
+
...(slot !== null ? { slot } : {}),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The job page: the summary, every step, and what it came back with. */
|
|
97
|
+
function jobDetail(job, slot = null) {
|
|
98
|
+
return { ...jobSummary(job, slot), steps: job.steps, ...(job.result ? { result: { summary: job.result } } : {}) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const live = (job) => job.state === "running" || job.state === "waiting";
|
|
102
|
+
|
|
103
|
+
/** Machine jobs a computer's slots are numbered for at most (its owner sets up to eight). */
|
|
104
|
+
const MACHINE_SLOTS = 8;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Which slot each live job holds, numbered from 1 in the place it runs: Tex's
|
|
108
|
+
* cloud's three, or each computer's own (a job on a computer never takes a
|
|
109
|
+
* cloud slot: `packages/tex/worker/jobs.ts`), numbered oldest first, as they were
|
|
110
|
+
* started. When a place has more live jobs than slots, running ones get them
|
|
111
|
+
* before ones waiting on the person: Tex counts only running jobs against its
|
|
112
|
+
* limit (`fits`), so a waiting one must never hide a job that is running.
|
|
113
|
+
*/
|
|
114
|
+
function slotsOf(jobs) {
|
|
115
|
+
const room = (place) => (place === null ? SLOTS : MACHINE_SLOTS);
|
|
116
|
+
const byStart = (a, b) => a.startedAt - b.startedAt;
|
|
117
|
+
const taken = new Map();
|
|
118
|
+
const chosen = [];
|
|
119
|
+
for (const job of [...jobs.filter((job) => job.state === "running").sort(byStart), ...jobs.filter((job) => job.state === "waiting").sort(byStart)]) {
|
|
120
|
+
const place = job.on?.id ?? null;
|
|
121
|
+
if ((taken.get(place) ?? 0) >= room(place)) continue;
|
|
122
|
+
taken.set(place, (taken.get(place) ?? 0) + 1);
|
|
123
|
+
chosen.push(job);
|
|
124
|
+
}
|
|
125
|
+
const held = new Map();
|
|
126
|
+
const numbered = new Map();
|
|
127
|
+
for (const job of chosen.sort(byStart)) {
|
|
128
|
+
const place = job.on?.id ?? null;
|
|
129
|
+
const next = (numbered.get(place) ?? 0) + 1;
|
|
130
|
+
numbered.set(place, next);
|
|
131
|
+
held.set(job.id, next);
|
|
132
|
+
}
|
|
133
|
+
return held;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** `YYYY-MM-DD` in the zone, or in UTC when the zone is not one. */
|
|
137
|
+
function dayOf(ms, timeZone) {
|
|
138
|
+
try {
|
|
139
|
+
return new Intl.DateTimeFormat("en-CA", { timeZone: timeZone || "UTC", year: "numeric", month: "2-digit", day: "2-digit" }).format(ms);
|
|
140
|
+
} catch {
|
|
141
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The overview's job parts: `status` (live jobs, and how many need the
|
|
147
|
+
* person, with `waitingMail` emails waiting for their yes), the three cloud
|
|
148
|
+
* `minions` and each computer's busy ones, `earlier` (the latest jobs finished today) and `earlierWeek`.
|
|
149
|
+
*/
|
|
150
|
+
function jobsOverview(jobs, now, { timeZone = null, waitingMail = 0 } = {}) {
|
|
151
|
+
const slots = slotsOf(jobs);
|
|
152
|
+
const cloud = new Map(jobs.filter((job) => !job.on && slots.has(job.id)).map((job) => [slots.get(job.id), job]));
|
|
153
|
+
const minions = [];
|
|
154
|
+
for (let slot = 1; slot <= SLOTS; slot += 1) {
|
|
155
|
+
const job = cloud.get(slot);
|
|
156
|
+
minions.push({ slot, job: job ? jobSummary(job, slot) : null });
|
|
157
|
+
}
|
|
158
|
+
// A computer's busy slots follow, each with its place (the computer's id); the page draws its free ones from the computer's own count.
|
|
159
|
+
for (const job of jobs.filter((candidate) => candidate.on && slots.has(candidate.id))) {
|
|
160
|
+
minions.push({ slot: slots.get(job.id), place: job.on.id, job: jobSummary(job, slots.get(job.id)) });
|
|
161
|
+
}
|
|
162
|
+
const today = dayOf(now, timeZone);
|
|
163
|
+
const ended = jobs
|
|
164
|
+
.filter((job) => !live(job) && now - (job.endedAt ?? job.startedAt) < WEEK_MS)
|
|
165
|
+
.sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt));
|
|
166
|
+
const endedToday = ended.filter((job) => dayOf(job.endedAt ?? job.startedAt, timeZone) === today);
|
|
167
|
+
const waiting = jobs.filter((job) => job.state === "waiting").length;
|
|
168
|
+
return {
|
|
169
|
+
status: { jobs: slots.size, needsYou: waiting + Math.max(0, waitingMail) },
|
|
170
|
+
minions,
|
|
171
|
+
earlier: endedToday.slice(0, EARLIER_SHOWN).map((job) => jobSummary(job)),
|
|
172
|
+
earlierWeek: ended.length,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The chat's jobs from the texting Worker: `chat` is `{phone}` or `{groupKey}`,
|
|
178
|
+
* and for a group the people hash its browser is tagged by (`people`).
|
|
179
|
+
* `{now, jobs: []}` when there is no binding, no phone, or the Worker fails:
|
|
180
|
+
* the page then shows free slots, never an error.
|
|
181
|
+
*/
|
|
182
|
+
async function fetchPageJobs(env, chat, now = Date.now()) {
|
|
183
|
+
const texting = env?.TEXTING;
|
|
184
|
+
if (!texting || typeof texting.pageJobs !== "function" || chat === null) return { now, jobs: [] };
|
|
185
|
+
try {
|
|
186
|
+
const answer = await texting.pageJobs({ chat });
|
|
187
|
+
const jobs = (Array.isArray(answer?.jobs) ? answer.jobs : []).map(readJob).filter((job) => job !== null);
|
|
188
|
+
// A group's people hash, which its browser is tagged by (`texPage/browser.js`).
|
|
189
|
+
const people = typeof answer?.people === "string" && /^[0-9a-f]{64}$/.test(answer.people) ? answer.people : null;
|
|
190
|
+
return { now: instant(answer?.now) ?? now, jobs, ...(people !== null ? { people } : {}) };
|
|
191
|
+
} catch {
|
|
192
|
+
return { now, jobs: [] };
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Asks the chat's inbox to steer or stop one of its own jobs; true when it took it. */
|
|
197
|
+
async function steerPageJob(env, chat, { id, text, stop = false }) {
|
|
198
|
+
const texting = env?.TEXTING;
|
|
199
|
+
if (!texting || typeof texting.pageSteer !== "function" || chat === null) return false;
|
|
200
|
+
try {
|
|
201
|
+
const answer = await texting.pageSteer({ chat, id, ...(typeof text === "string" ? { text } : {}), ...(stop ? { stop: true } : {}) });
|
|
202
|
+
return answer?.taken === true;
|
|
203
|
+
} catch {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Answers the person's waiting ask in their own chat, yes or no, as the ask card's own Yes or Not now would
|
|
210
|
+
* (`TexRoutines.pageAnswer`). `{ ok: false, error }` names why not: `no_ask` (nothing waiting), `stale` (a newer ask
|
|
211
|
+
* replaced it), `full`, or `unavailable` when the texting Worker could not be reached.
|
|
212
|
+
*/
|
|
213
|
+
async function answerPageAsk(env, chat, ask, yes) {
|
|
214
|
+
const texting = env?.TEXTING;
|
|
215
|
+
if (!texting || typeof texting.pageAnswer !== "function") return { ok: false, error: "unavailable" };
|
|
216
|
+
try {
|
|
217
|
+
const answer = await texting.pageAnswer({ chat, ask, yes });
|
|
218
|
+
if (answer?.taken === true) return { ok: true };
|
|
219
|
+
const why = answer?.why;
|
|
220
|
+
return { ok: false, error: why === "no_ask" || why === "stale" || why === "full" ? why : "unavailable" };
|
|
221
|
+
} catch {
|
|
222
|
+
return { ok: false, error: "unavailable" };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
module.exports = { SLOTS, EARLIER_SHOWN, readJob, jobSummary, jobDetail, slotsOf, dayOf, jobsOverview, fetchPageJobs, steerPageJob, answerPageAsk };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Types for `pageJobs.cjs`; see that file. */
|
|
2
|
+
|
|
3
|
+
export declare const SLOTS: number;
|
|
4
|
+
export declare const EARLIER_SHOWN: number;
|
|
5
|
+
export declare function readJob(raw: unknown): any;
|
|
6
|
+
export declare function jobSummary(job: any, slot?: number | null): any;
|
|
7
|
+
export declare function jobDetail(job: any, slot?: number | null): any;
|
|
8
|
+
export declare function slotsOf(jobs: any[]): Map<string, number>;
|
|
9
|
+
export declare function dayOf(ms: number, timeZone?: string | null): string;
|
|
10
|
+
export declare function jobsOverview(jobs: any[], now: number, options?: { timeZone?: string | null; waitingMail?: number }): any;
|
|
11
|
+
export declare function fetchPageJobs(env: unknown, chat: unknown, now?: number): Promise<{ now: number; jobs: any[]; people?: string }>;
|
|
12
|
+
export declare function steerPageJob(env: unknown, chat: unknown, steer: { id: string; text?: string; stop?: boolean }): Promise<boolean>;
|
|
13
|
+
export declare function answerPageAsk(env: unknown, chat: unknown, ask: unknown, yes: boolean): Promise<{ ok: boolean; error?: string }>;
|