@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,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message's anchor in a channel-day note (`### … {#msg-<hex>}`), and a key that ends in one. Moved from
|
|
3
|
+
* `packages/communications/src/anchors.js` and `apps/mcp/src/search/commsIndex.js`, which re-export them, so the
|
|
4
|
+
* six's `fetch` translation reads an anchored id the same way on both sides (`v2SearchFetch.cjs`).
|
|
5
|
+
*/
|
|
6
|
+
"use strict";
|
|
7
|
+
|
|
8
|
+
/** Anchors are `msg-` plus `ANCHOR_HEX_LENGTH` hex characters. */
|
|
9
|
+
const ANCHOR_PREFIX = "msg-";
|
|
10
|
+
const ANCHOR_HEX_LENGTH = 16;
|
|
11
|
+
|
|
12
|
+
/** Is this string one `messageAnchor` produced? */
|
|
13
|
+
function isMessageAnchor(value) {
|
|
14
|
+
return (
|
|
15
|
+
typeof value === "string" &&
|
|
16
|
+
value.startsWith(ANCHOR_PREFIX) &&
|
|
17
|
+
new RegExp(`^[0-9a-f]{${ANCHOR_HEX_LENGTH}}$`).test(value.slice(ANCHOR_PREFIX.length))
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A key split at a trailing, well-formed message anchor: `{ path, anchor }`, or the key whole with `anchor` null.
|
|
23
|
+
* A `#` anywhere else is an ordinary character in an ordinary key, and a note whose name really ends in one must keep
|
|
24
|
+
* resolving to itself.
|
|
25
|
+
*
|
|
26
|
+
* @param {string} key
|
|
27
|
+
* @returns {{path: string, anchor: string|null}}
|
|
28
|
+
*/
|
|
29
|
+
function splitMessageAnchor(key) {
|
|
30
|
+
if (typeof key !== "string") return { path: key, anchor: null };
|
|
31
|
+
const hash = key.lastIndexOf("#");
|
|
32
|
+
if (hash === -1) return { path: key, anchor: null };
|
|
33
|
+
const anchor = key.slice(hash + 1);
|
|
34
|
+
if (!isMessageAnchor(anchor)) return { path: key, anchor: null };
|
|
35
|
+
return { path: key.slice(0, hash), anchor };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { ANCHOR_PREFIX, ANCHOR_HEX_LENGTH, isMessageAnchor, splitMessageAnchor };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WHOSE ANTHROPIC KEY PAYS FOR A CALL (decided by the owner, 2026-11-26).
|
|
3
|
+
*
|
|
4
|
+
* The keys live on the AI Gateway's Provider Keys page; `aiKeys.json` names
|
|
5
|
+
* them by alias and records, per key, whose it is, its credit (`capUsd`), how
|
|
6
|
+
* much is used (`usedUsd` as of `usedAsOf`), when one-off credit expires
|
|
7
|
+
* (`expires`) or, for use-it-or-lose-it monthly credit (`resetEvery: "month"`),
|
|
8
|
+
* when it lapses and refills (`resets`, then every month after), and
|
|
9
|
+
* `retiredUntil`: skip it until then. Aliases are names, not secrets.
|
|
10
|
+
*
|
|
11
|
+
* Per use (`prod`, `lab`, `evals`) the keys that can still pay are tried by
|
|
12
|
+
* whose credit lapses soonest (a monthly key's period end, or a one-off
|
|
13
|
+
* expiry), so credit that is about to lapse is spent before credit that keeps (Dev2: "smartly always use the expiring key first before
|
|
14
|
+
* we go onto the next"); keys with no expiry follow, in file order. A key is
|
|
15
|
+
* left out while retired, once expired, or once its recorded use reaches its
|
|
16
|
+
* credit. The gateway (`aiGateway.js`) and the benchmark runner
|
|
17
|
+
* (`bench/models.mjs`) read the order at call time, so a retirement ends on
|
|
18
|
+
* its date without a deploy; the console's costs page reads the same file.
|
|
19
|
+
*
|
|
20
|
+
* A run may pick a key first (`AI_KEY_PICK`, from a Lab or eval run's `key`):
|
|
21
|
+
* it goes ahead of the use's order whatever its state, and the order follows
|
|
22
|
+
* it, so a picked key that cannot pay never stops the run.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const FILE = require("./aiKeys.json");
|
|
26
|
+
|
|
27
|
+
/** An alias the gateway's Provider Keys page accepts. */
|
|
28
|
+
const KEY_ALIAS = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
29
|
+
const MAX_KEY_ALIASES = 8;
|
|
30
|
+
|
|
31
|
+
const USES = Object.freeze(Object.keys(FILE.uses));
|
|
32
|
+
const AI_KEYS = Object.freeze(FILE.keys.map((key) => Object.freeze({ ...key, uses: Object.freeze([...key.uses]) })));
|
|
33
|
+
|
|
34
|
+
const time = (iso) => (typeof iso === "string" ? Date.parse(iso) : NaN);
|
|
35
|
+
|
|
36
|
+
/** `iso` moved by `months` calendar months, the day clamped to the month's last. */
|
|
37
|
+
function addMonths(at, months) {
|
|
38
|
+
const d = new Date(at);
|
|
39
|
+
const day = d.getUTCDate();
|
|
40
|
+
d.setUTCDate(1);
|
|
41
|
+
d.setUTCMonth(d.getUTCMonth() + months);
|
|
42
|
+
const last = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate();
|
|
43
|
+
d.setUTCDate(Math.min(day, last));
|
|
44
|
+
return d.getTime();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The current credit period of a monthly key (`resetEvery: "month"`): `{ start, end }`, where `end` is the next
|
|
49
|
+
* monthly anniversary of `resets` after `now` (when the credit lapses and refills). Null for a key that does not reset.
|
|
50
|
+
*/
|
|
51
|
+
function periodOf(key, now = Date.now()) {
|
|
52
|
+
const anchor = time(key.resets);
|
|
53
|
+
if (key.resetEvery !== "month" || !Number.isFinite(anchor)) return null;
|
|
54
|
+
let n = 0;
|
|
55
|
+
if (anchor <= now) while (addMonths(anchor, n) <= now && n < 1200) n += 1;
|
|
56
|
+
else while (addMonths(anchor, n - 1) > now && n > -1200) n -= 1;
|
|
57
|
+
return { start: addMonths(anchor, n - 1), end: addMonths(anchor, n) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** When `key`'s current credit lapses: its period's end, a one-off `expires`, or Infinity. */
|
|
61
|
+
function lapsesAt(key, now = Date.now()) {
|
|
62
|
+
const period = periodOf(key, now);
|
|
63
|
+
if (period) return period.end;
|
|
64
|
+
return Number.isFinite(time(key.expires)) ? time(key.expires) : Infinity;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Why `key` cannot pay at `now` ("retired", "expired", "used up"), or null when it can. A monthly key never expires;
|
|
69
|
+
* its recorded use counts only inside the period it was recorded in, so a refill makes it whole again.
|
|
70
|
+
*/
|
|
71
|
+
function keyState(key, now = Date.now()) {
|
|
72
|
+
if (time(key.retiredUntil) > now) return "retired";
|
|
73
|
+
const period = periodOf(key, now);
|
|
74
|
+
if (!period && time(key.expires) <= now) return "expired";
|
|
75
|
+
const useCounts = !period || time(key.usedAsOf) >= period.start;
|
|
76
|
+
if (useCounts && Number.isFinite(key.capUsd) && Number.isFinite(key.usedUsd) && key.usedUsd >= key.capUsd) return "used up";
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Clean a comma list or array of aliases: trimmed, valid, unique, capped. */
|
|
81
|
+
function cleanAliases(list) {
|
|
82
|
+
const parts = Array.isArray(list) ? list : String(list ?? "").split(",");
|
|
83
|
+
return [...new Set(parts.map((alias) => String(alias).trim()).filter((alias) => KEY_ALIAS.test(alias)))].slice(0, MAX_KEY_ALIASES);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The keys for `use` that can pay at `now`, soonest expiry first, then file order; empty for an unknown use. */
|
|
87
|
+
function keysForUse(use, now = Date.now()) {
|
|
88
|
+
if (!USES.includes(use)) return [];
|
|
89
|
+
return AI_KEYS.map((key, i) => ({ key, i, lapses: lapsesAt(key, now) }))
|
|
90
|
+
.filter(({ key }) => key.uses.includes(use) && keyState(key, now) === null)
|
|
91
|
+
.sort((a, b) => a.lapses - b.lapses || a.i - b.i)
|
|
92
|
+
.map(({ key }) => key);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function aliasesForUse(use, now = Date.now()) {
|
|
96
|
+
return keysForUse(use, now).map((key) => key.alias);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The key a person named, by alias, id or owner ("segun", "Segun's key",
|
|
101
|
+
* "segun-claude-credits"), or null when none matches.
|
|
102
|
+
*/
|
|
103
|
+
function findKey(name) {
|
|
104
|
+
if (typeof name !== "string") return null;
|
|
105
|
+
const said = name.trim().toLowerCase().replace(/['’]s\b/g, "").replace(/\bkey\b/g, "").trim();
|
|
106
|
+
if (!said) return null;
|
|
107
|
+
return AI_KEYS.find((key) => key.alias === said || key.key === said || key.owner.toLowerCase() === said) ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The aliases an environment tries, in order. With `AI_KEY_USE`: a run's pick
|
|
112
|
+
* (`AI_KEY_PICK`) first, then that use's order at `now`. Without it, the
|
|
113
|
+
* older literal list `AI_GATEWAY_KEY_ALIASES`, or none: a self-hosted gateway
|
|
114
|
+
* names no key it does not hold.
|
|
115
|
+
*/
|
|
116
|
+
function keyAliasesOf(env, now = Date.now()) {
|
|
117
|
+
const use = typeof env?.AI_KEY_USE === "string" ? env.AI_KEY_USE.trim() : "";
|
|
118
|
+
if (!use) return cleanAliases(typeof env?.AI_GATEWAY_KEY_ALIASES === "string" ? env.AI_GATEWAY_KEY_ALIASES : []);
|
|
119
|
+
const picked = findKey(typeof env?.AI_KEY_PICK === "string" ? env.AI_KEY_PICK : "");
|
|
120
|
+
return cleanAliases([...(picked ? [picked.alias] : []), ...aliasesForUse(use, now)]);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Every key as `tex_dev keys` shows it: its record, whether it can pay now, and its place in each use's order. */
|
|
124
|
+
function keysReport(now = Date.now()) {
|
|
125
|
+
const orders = Object.fromEntries(USES.map((use) => [use, aliasesForUse(use, now)]));
|
|
126
|
+
return {
|
|
127
|
+
order: orders,
|
|
128
|
+
keys: AI_KEYS.map((key) => ({
|
|
129
|
+
...key,
|
|
130
|
+
leftUsd: Number.isFinite(key.capUsd) && Number.isFinite(key.usedUsd) ? Math.max(0, key.capUsd - key.usedUsd) : null,
|
|
131
|
+
lapses: Number.isFinite(lapsesAt(key, now)) ? new Date(lapsesAt(key, now)).toISOString() : null,
|
|
132
|
+
state: keyState(key, now) ?? "active",
|
|
133
|
+
})),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { AI_KEYS, USES, KEY_ALIAS, MAX_KEY_ALIASES, aliasesForUse, cleanAliases, findKey, keyAliasesOf, keyState, keysForUse, keysReport, lapsesAt, periodOf };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Types for `aiKeys.cjs`; see that file. */
|
|
2
|
+
|
|
3
|
+
export interface AiKeyDef {
|
|
4
|
+
/** Short id. */
|
|
5
|
+
key: string;
|
|
6
|
+
/** The alias on the AI Gateway's Provider Keys page. */
|
|
7
|
+
alias: string;
|
|
8
|
+
/** Whose key it is. */
|
|
9
|
+
owner: string;
|
|
10
|
+
/** The credit it holds, when known. */
|
|
11
|
+
capUsd: number | null;
|
|
12
|
+
/** How much of it is used, as of `usedAsOf`, when known. */
|
|
13
|
+
usedUsd: number | null;
|
|
14
|
+
usedAsOf: string | null;
|
|
15
|
+
/** When it began paying (ISO). */
|
|
16
|
+
since: string;
|
|
17
|
+
/** When its credit lapses (ISO), or null. */
|
|
18
|
+
expires: string | null;
|
|
19
|
+
/** When it refills (ISO), or null; with `resetEvery`, the anchor of its monthly period. */
|
|
20
|
+
resets: string | null;
|
|
21
|
+
/** "month": use-it-or-lose-it credit that lapses and refills each month on `resets`' anniversary. */
|
|
22
|
+
resetEvery: "month" | null;
|
|
23
|
+
/** Skipped until then (ISO), or null. */
|
|
24
|
+
retiredUntil: string | null;
|
|
25
|
+
note?: string;
|
|
26
|
+
/** The uses it is tried for. */
|
|
27
|
+
uses: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export declare const AI_KEYS: readonly AiKeyDef[];
|
|
31
|
+
export declare const USES: readonly string[];
|
|
32
|
+
export declare const KEY_ALIAS: RegExp;
|
|
33
|
+
export declare const MAX_KEY_ALIASES: number;
|
|
34
|
+
export declare function keyState(key: AiKeyDef, now?: number): "retired" | "expired" | "used up" | null;
|
|
35
|
+
export declare function keysForUse(use: string, now?: number): AiKeyDef[];
|
|
36
|
+
export declare function aliasesForUse(use: string, now?: number): string[];
|
|
37
|
+
export declare function cleanAliases(list: string | readonly string[] | null | undefined): string[];
|
|
38
|
+
export declare function findKey(name: unknown): AiKeyDef | null;
|
|
39
|
+
export declare function keyAliasesOf(env: Record<string, unknown> | null | undefined, now?: number): string[];
|
|
40
|
+
export declare function periodOf(key: AiKeyDef, now?: number): { start: number; end: number } | null;
|
|
41
|
+
export declare function lapsesAt(key: AiKeyDef, now?: number): number;
|
|
42
|
+
export declare function keysReport(now?: number): { order: Record<string, string[]>; keys: Array<AiKeyDef & { leftUsd: number | null; state: string }> };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"aiKeys": 3,
|
|
3
|
+
"about": "Whose Anthropic key pays for a Claude call (aiKeys.cjs). Each key is stored on the AI Gateway's Provider Keys page under its alias; nothing here is secret. A key with resetEvery \"month\" holds use-it-or-lose-it credit that lapses and refills on each monthly anniversary of resets; a key without it lapses for good at expires. Per use, the keys still able to pay are tried by whose credit lapses soonest (the current period's end, or expires), then file order. A key is skipped while retiredUntil is in the future, after a one-off expires, or once usedUsd (as of usedAsOf, within the current period) reaches capUsd. The gateway also rests a key on its own when Anthropic refuses it (credit spent or usage limit).",
|
|
4
|
+
"uses": {
|
|
5
|
+
"prod": "People's texts and everything the deployed gateway runs (production, staging, previews, Lab test chats)",
|
|
6
|
+
"lab": "Lab runs, the Tex test set and replay",
|
|
7
|
+
"evals": "Eval runs and benchmarks, nightly included"
|
|
8
|
+
},
|
|
9
|
+
"keys": [
|
|
10
|
+
{
|
|
11
|
+
"key": "dev",
|
|
12
|
+
"alias": "dev-claude-credits",
|
|
13
|
+
"owner": "Dev",
|
|
14
|
+
"capUsd": 100,
|
|
15
|
+
"usedUsd": null,
|
|
16
|
+
"usedAsOf": null,
|
|
17
|
+
"since": "2026-11-13T16:57:00Z",
|
|
18
|
+
"expires": null,
|
|
19
|
+
"resets": "2026-11-27T23:59:00Z",
|
|
20
|
+
"resetEvery": "month",
|
|
21
|
+
"retiredUntil": "2026-12-01T00:00:00Z",
|
|
22
|
+
"note": "Monthly credit, assumed to lapse and refill like Segun's (to confirm). Hit its Anthropic usage limit 2026-11-26 20:52Z; Anthropic says access returns 2026-12-01.",
|
|
23
|
+
"uses": ["prod", "lab", "evals"]
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"key": "dev2",
|
|
27
|
+
"alias": "dev2-claude-credits",
|
|
28
|
+
"owner": "Dev2",
|
|
29
|
+
"capUsd": 200,
|
|
30
|
+
"usedUsd": 27,
|
|
31
|
+
"usedAsOf": "2026-11-26T22:18:00Z",
|
|
32
|
+
"since": "2026-11-13T16:57:00Z",
|
|
33
|
+
"expires": null,
|
|
34
|
+
"resets": "2026-12-23T05:00:00Z",
|
|
35
|
+
"resetEvery": "month",
|
|
36
|
+
"retiredUntil": null,
|
|
37
|
+
"note": "$200 a month, use it or lose it; about $173 left on 2026-11-26, refills 2026-12-23 and monthly after, per Dev2.",
|
|
38
|
+
"uses": ["prod", "lab", "evals"]
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"key": "segun",
|
|
42
|
+
"alias": "segun-claude-credits",
|
|
43
|
+
"owner": "Segun",
|
|
44
|
+
"capUsd": 200,
|
|
45
|
+
"usedUsd": 100,
|
|
46
|
+
"usedAsOf": "2026-11-26T22:17:00Z",
|
|
47
|
+
"since": "2026-11-26T21:00:00Z",
|
|
48
|
+
"expires": null,
|
|
49
|
+
"resets": "2026-11-28T04:59:00Z",
|
|
50
|
+
"resetEvery": "month",
|
|
51
|
+
"retiredUntil": null,
|
|
52
|
+
"note": "$200 a month, use it or lose it, refilled 2026-11-27 (end of day US Eastern) and monthly after, per Dev2 2026-11-26. About $100 left in the period ending then.",
|
|
53
|
+
"uses": ["prod", "lab", "evals"]
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ONE RECORD OF WHICH PAYER'S CREDIT IS SPENT, shared by every isolate.
|
|
3
|
+
*
|
|
4
|
+
* The plan key is tried before Unified Billing (`aiGateway.js`). When Anthropic
|
|
5
|
+
* says that credit is gone, the payer rests for `CREDIT_REST_MS` and later
|
|
6
|
+
* calls skip it. That rest used to live in the isolate's memory, so every
|
|
7
|
+
* other isolate learned by sending the spent key itself and then the call
|
|
8
|
+
* again on Unified Billing (production, 2026-11-12: one failed 400 plus one
|
|
9
|
+
* paid call, about $8.80 a day). This object is that rest for the whole
|
|
10
|
+
* gateway: one Durable Object, payer names and a timestamp, never a key and
|
|
11
|
+
* never a prompt.
|
|
12
|
+
*
|
|
13
|
+
* A call reads it at most every `FRESH_MS` while a payer looks available, and
|
|
14
|
+
* not at all while the local copy of the rest is still in the future. When
|
|
15
|
+
* the rest expires, one caller probes the key; the others skip it until that
|
|
16
|
+
* probe lands. A read that fails or takes longer than `STORE_WAIT_MS` tries
|
|
17
|
+
* the key, so a stuck object costs one extra attempt, never a dropped turn.
|
|
18
|
+
*
|
|
19
|
+
* The rest is fifteen minutes, the same as before. The next probe after it
|
|
20
|
+
* clears the record when the credit answers, which is how a monthly refill
|
|
21
|
+
* (the plan's credit returns on the 21st) starts being spent again without
|
|
22
|
+
* anyone clearing the record by hand.
|
|
23
|
+
*
|
|
24
|
+
* Self-hosting on the free tier: leave the `CREDIT_REST` binding out. Each
|
|
25
|
+
* isolate then keeps its own rest, as it did before this object existed.
|
|
26
|
+
*
|
|
27
|
+
* Shared by Tex (`packages/tex/gateway/agent/aiGateway.js`) and Context's own
|
|
28
|
+
* model client (`apps/mcp/src/models/client.js`), so both read one rest and one
|
|
29
|
+
* process cache. `place` is how the caller's Worker gets a Durable Object stub
|
|
30
|
+
* (`apps/mcp/src/objectPlace.js` `objectByName`), passed in so the location hint
|
|
31
|
+
* stays the only way an object is placed.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
/** How long a spent payer is skipped before one caller tries it again. */
|
|
36
|
+
const CREDIT_REST_MS = 15 * 60_000;
|
|
37
|
+
|
|
38
|
+
/** How long an isolate trusts "this payer is available" before asking the object again. */
|
|
39
|
+
const FRESH_MS = 15_000;
|
|
40
|
+
|
|
41
|
+
/** How long other callers skip a payer while one of them is probing it. */
|
|
42
|
+
const PROBE_MS = 30_000;
|
|
43
|
+
|
|
44
|
+
/** A hung object must not hold the model call. */
|
|
45
|
+
const STORE_WAIT_MS = 400;
|
|
46
|
+
|
|
47
|
+
/** The one object's name. A new name would be a new, empty rest. */
|
|
48
|
+
const CREDIT_REST_OBJECT = "ai-gateway-credit-rest:v1";
|
|
49
|
+
|
|
50
|
+
/** The gateway route a benchmark runner uses to read and write this object. It has no Durable Object binding of its own. */
|
|
51
|
+
const CREDIT_REST_PATH = "/credit-rest";
|
|
52
|
+
|
|
53
|
+
/** `plan`, or `alias:<name>` as `aiGateway.js` labels a stored key. */
|
|
54
|
+
const PAYER = /^(plan|alias:[a-z0-9][a-z0-9_-]{0,63})$/;
|
|
55
|
+
|
|
56
|
+
const payerName = (name) => (typeof name === "string" && PAYER.test(name) ? name : null);
|
|
57
|
+
|
|
58
|
+
function json(body, status = 200) {
|
|
59
|
+
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The one object. `book` is `{ [payer]: { until, probeUntil } }`. `until` is
|
|
64
|
+
* when the rest ends; `probeUntil` is when the single in-flight probe gives up.
|
|
65
|
+
*/
|
|
66
|
+
class CreditRestObject {
|
|
67
|
+
constructor(state) {
|
|
68
|
+
this.storage = state.storage;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async fetch(request) {
|
|
72
|
+
if (request.method !== "POST") return new Response(null, { status: 405 });
|
|
73
|
+
const action = new URL(request.url).pathname;
|
|
74
|
+
let body = {};
|
|
75
|
+
try {
|
|
76
|
+
body = await request.json();
|
|
77
|
+
} catch {
|
|
78
|
+
body = {};
|
|
79
|
+
}
|
|
80
|
+
const name = payerName(body?.name);
|
|
81
|
+
const now = Number(body?.now);
|
|
82
|
+
const book = (await this.storage.get("book")) ?? {};
|
|
83
|
+
const row = name ? book[name] ?? null : null;
|
|
84
|
+
|
|
85
|
+
if (action === "/claim") {
|
|
86
|
+
if (!name || !Number.isFinite(now)) return json({ try: true });
|
|
87
|
+
if (row && now < row.until) return json({ try: false, until: row.until });
|
|
88
|
+
if (row && now < (row.probeUntil ?? 0)) return json({ try: false, until: row.probeUntil });
|
|
89
|
+
if (row && row.until > 0) {
|
|
90
|
+
book[name] = { ...row, probeUntil: now + PROBE_MS };
|
|
91
|
+
await this.storage.put("book", book);
|
|
92
|
+
return json({ try: true, probe: true });
|
|
93
|
+
}
|
|
94
|
+
return json({ try: true });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (action === "/spent") {
|
|
98
|
+
const until = Number(body?.until);
|
|
99
|
+
if (!name || !Number.isFinite(until)) return new Response(null, { status: 400 });
|
|
100
|
+
book[name] = { until: Math.max(row?.until ?? 0, until), probeUntil: 0 };
|
|
101
|
+
await this.storage.put("book", book);
|
|
102
|
+
return json({ until: book[name].until });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (action === "/clear") {
|
|
106
|
+
if (!name) return new Response(null, { status: 400 });
|
|
107
|
+
delete book[name];
|
|
108
|
+
await this.storage.put("book", book);
|
|
109
|
+
return json({ ok: true });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return new Response(null, { status: 404 });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The object as the gateway calls it, or null when the binding is absent. Never throws. */
|
|
117
|
+
function creditStoreOf(env, place) {
|
|
118
|
+
const namespace = env?.CREDIT_REST;
|
|
119
|
+
if (!namespace || typeof namespace.idFromName !== "function" || typeof namespace.get !== "function" || typeof place !== "function") return null;
|
|
120
|
+
const call = async (action, body) => {
|
|
121
|
+
const response = await place(namespace, CREDIT_REST_OBJECT).fetch(
|
|
122
|
+
new Request(`https://credit-rest.invalid${action}`, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: { "content-type": "application/json" },
|
|
125
|
+
body: JSON.stringify(body),
|
|
126
|
+
}),
|
|
127
|
+
);
|
|
128
|
+
if (!response.ok) throw new Error("credit rest refused");
|
|
129
|
+
return response.json();
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
claim: (name, now) => call("/claim", { name, now }),
|
|
133
|
+
spent: (name, until) => call("/spent", { name, until }),
|
|
134
|
+
clear: (name) => call("/clear", { name }),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** One isolate's copy of the rest. Tests pass their own; the process keeps one. */
|
|
139
|
+
function createCreditCache() {
|
|
140
|
+
return { until: new Map(), fresh: new Map(), probing: new Set() };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const processCache = createCreditCache();
|
|
144
|
+
|
|
145
|
+
function sameSecret(a, b) {
|
|
146
|
+
if (typeof a !== "string" || typeof b !== "string" || a.length === 0 || a.length !== b.length) return false;
|
|
147
|
+
let diff = 0;
|
|
148
|
+
for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
149
|
+
return diff === 0;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* `POST /credit-rest` for the benchmark runner. The bearer is the gateway
|
|
154
|
+
* token the runner already holds. A wrong token is a 404, the same as a
|
|
155
|
+
* worker with no such route. The body is an op and a payer name, never a key
|
|
156
|
+
* and never a prompt.
|
|
157
|
+
*
|
|
158
|
+
* The runner's clock is not this worker's. A claim uses `Date.now()` here,
|
|
159
|
+
* and a spent mark is kept at most `CREDIT_REST_MS` ahead of it. A larger
|
|
160
|
+
* finite `until` is clamped and logged. A non-finite `until` is forwarded
|
|
161
|
+
* unchanged, the same as before this bound. Callers inside this worker do
|
|
162
|
+
* not come through here, and the object still stores the timestamp they send.
|
|
163
|
+
*/
|
|
164
|
+
async function handleCreditRest(request, env, place) {
|
|
165
|
+
if (request.method !== "POST") return new Response(null, { status: 405 });
|
|
166
|
+
const header = request.headers.get("authorization") ?? "";
|
|
167
|
+
const bearer = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : "";
|
|
168
|
+
if (!sameSecret(bearer, env?.AI_GATEWAY_TOKEN)) return new Response(null, { status: 404 });
|
|
169
|
+
const store = creditStoreOf(env, place);
|
|
170
|
+
if (!store) return new Response(null, { status: 404 });
|
|
171
|
+
let body = {};
|
|
172
|
+
try {
|
|
173
|
+
body = await request.json();
|
|
174
|
+
} catch {
|
|
175
|
+
body = {};
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
if (body?.op === "claim") return json(await store.claim(body.name, Date.now()));
|
|
179
|
+
if (body?.op === "spent") {
|
|
180
|
+
const bound = clampedUntil(body);
|
|
181
|
+
const result = await store.spent(body.name, bound.until);
|
|
182
|
+
if (bound.clamped) {
|
|
183
|
+
const payer = typeof body.name === "string" ? body.name.slice(0, 80) : null;
|
|
184
|
+
console.log(JSON.stringify({ event: "credit_rest_clamped", payer, asked: bound.asked, kept: bound.until }));
|
|
185
|
+
}
|
|
186
|
+
return json(result);
|
|
187
|
+
}
|
|
188
|
+
if (body?.op === "clear") return json(await store.clear(body.name));
|
|
189
|
+
} catch {
|
|
190
|
+
return new Response(null, { status: 502 });
|
|
191
|
+
}
|
|
192
|
+
return new Response(null, { status: 400 });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The runner's `until`, at most one rest ahead of this worker. A non-finite value is unchanged. */
|
|
196
|
+
function clampedUntil(body) {
|
|
197
|
+
const asked = Number(body?.until);
|
|
198
|
+
const cap = Date.now() + CREDIT_REST_MS;
|
|
199
|
+
if (!Number.isFinite(asked) || asked <= cap) return { until: asked, clamped: false };
|
|
200
|
+
return { until: cap, clamped: true, asked };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** For tests: forget the process-wide copy. A store the test holds is its own. */
|
|
204
|
+
function resetCreditCache() {
|
|
205
|
+
processCache.until.clear();
|
|
206
|
+
processCache.fresh.clear();
|
|
207
|
+
processCache.probing.clear();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Ask the store, and give up after `STORE_WAIT_MS` so a stuck object never holds the call. */
|
|
211
|
+
async function ask(work) {
|
|
212
|
+
let timer;
|
|
213
|
+
try {
|
|
214
|
+
return await Promise.race([
|
|
215
|
+
work,
|
|
216
|
+
new Promise((_, reject) => {
|
|
217
|
+
timer = setTimeout(() => reject(new Error("timeout")), STORE_WAIT_MS);
|
|
218
|
+
}),
|
|
219
|
+
]);
|
|
220
|
+
} catch {
|
|
221
|
+
return null;
|
|
222
|
+
} finally {
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Whether to skip `name` and let the next payer (or Unified Billing) pay.
|
|
229
|
+
* True while this isolate, or any other, already knows the credit is spent.
|
|
230
|
+
*/
|
|
231
|
+
async function payerSkipped(name, now, { store = null, cache = processCache } = {}) {
|
|
232
|
+
if (now < (cache.until.get(name) ?? 0)) return true;
|
|
233
|
+
if (!store) return false;
|
|
234
|
+
if (now < (cache.fresh.get(name) ?? 0)) return false;
|
|
235
|
+
const claim = await ask(store.claim(name, now));
|
|
236
|
+
if (!claim || claim.try !== false) {
|
|
237
|
+
cache.fresh.set(name, now + FRESH_MS);
|
|
238
|
+
if (claim?.probe === true) cache.probing.add(name);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
const until = Number(claim.until);
|
|
242
|
+
if (Number.isFinite(until) && until > now) cache.until.set(name, until);
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** `name`'s credit is spent until `until`. Remembered here and, when there is one, in the object. */
|
|
247
|
+
async function noteCreditSpent(name, until, { store = null, cache = processCache } = {}) {
|
|
248
|
+
cache.until.set(name, until);
|
|
249
|
+
cache.fresh.delete(name);
|
|
250
|
+
cache.probing.delete(name);
|
|
251
|
+
if (store) await ask(store.spent(name, until));
|
|
252
|
+
console.log(JSON.stringify({ event: "ai_gateway_credit_rest", payer: name, until }));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* `name` just paid. A probe that found the credit back, or a rest this isolate
|
|
257
|
+
* was holding, is cleared so the next call tries the key. A normal success
|
|
258
|
+
* writes nothing.
|
|
259
|
+
*/
|
|
260
|
+
async function noteCreditPaid(name, { store = null, cache = processCache } = {}) {
|
|
261
|
+
const probing = cache.probing.has(name);
|
|
262
|
+
const resting = (cache.until.get(name) ?? 0) > 0;
|
|
263
|
+
cache.until.delete(name);
|
|
264
|
+
cache.fresh.delete(name);
|
|
265
|
+
cache.probing.delete(name);
|
|
266
|
+
if (store && (probing || resting)) await ask(store.clear(name));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = { CREDIT_REST_MS, FRESH_MS, CREDIT_REST_OBJECT, CREDIT_REST_PATH, CreditRestObject, creditStoreOf, createCreditCache, handleCreditRest, resetCreditCache, payerSkipped, noteCreditSpent, noteCreditPaid };
|