Open History to see the last commit
1import {
2 DEFAULT_THREAD_CONTEXT_TOKEN_LIMIT,
3 type OrchestrationThreadActivity,
4} from "@t3tools/contracts";
5export type UsageLimitViolation = { readonly code: "context-limit"; readonly detail: string };
6export function evaluateTurnStartLimits(input: {
7 readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
8 readonly contextTokenLimit?: number;
9}): UsageLimitViolation | undefined {
10 const usedTokens = latestContextTokens(input.activities);
11 const contextTokenLimit = input.contextTokenLimit ?? DEFAULT_THREAD_CONTEXT_TOKEN_LIMIT;
12 if (usedTokens !== undefined && usedTokens >= contextTokenLimit) {
13 return {
14 code: "context-limit",
15 detail: `T3 usage limit: this thread has used ${usedTokens.toLocaleString("en-US")} context tokens. The hard limit is ${contextTokenLimit.toLocaleString("en-US")}. Send /compact to shrink it, or start a new thread so the old conversation is not sent to the provider again.`,
16 };
17 }
18 return undefined;
19}
20
21function latestContextTokens(
22 activities: ReadonlyArray<OrchestrationThreadActivity>,
23): number | undefined {
24 for (let index = activities.length - 1; index >= 0; index -= 1) {
25 const activity = activities[index];
26 if (activity?.kind === "context-compaction") {
27 const payload = activity.payload as Record<string, unknown> | undefined;
28 const afterTokens = payload?.["afterTokens"];
29 return typeof afterTokens === "number" && Number.isFinite(afterTokens) && afterTokens >= 0
30 ? afterTokens
31 : undefined;
32 }
33 if (activity?.kind !== "context-window.updated") continue;
34 const payload = activity.payload as Record<string, unknown> | undefined;
35 const usedTokens = payload?.["usedTokens"];
36 if (typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0) {
37 return usedTokens;
38 }
39 }
40 return undefined;
41}