forked from mem9-ai/mem9
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-state.ts
More file actions
221 lines (194 loc) · 7.7 KB
/
Copy pathruntime-state.ts
File metadata and controls
221 lines (194 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
const WARNING_PERCENT = 80;
const URGENT_PERCENT = 95;
interface RuntimeRecommendedAction {
providerActionCode?: string;
severity?: string;
type?: string;
url?: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === "object" && !Array.isArray(value);
}
function text(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
function numberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function compactNumber(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(1);
}
function meterLabel(meter: string): string {
if (meter === "memory_recall_requests") return "mem9 recall";
if (meter === "memory_write_requests") return "mem9 memory saving";
return "mem9 memory";
}
function budgetLabel(budgetType: string): string {
if (budgetType === "includedQuota") return "included quota";
if (budgetType === "spendingLimit") return "spending limit";
if (budgetType === "credits") return "credit balance";
return "runtime quota";
}
function modeLabel(mode: string): string {
if (mode === "onDemand") return "on-demand usage";
if (mode === "postQuota") return "the post-quota request lane";
return "provider-managed runtime";
}
function warningMessage(detail: string): string {
return `${detail}. In your reply, include this exact mem9 warning detail: ${detail}.`;
}
function normalizeAction(input: unknown): RuntimeRecommendedAction | null {
const action = isRecord(input) ? input : {};
const providerActionCode = text(action.providerActionCode);
const severity = text(action.severity);
const type = text(action.type);
const url = text(action.url);
if (!providerActionCode && !severity && !type && !url) return null;
return {
...(providerActionCode ? { providerActionCode } : {}),
...(severity ? { severity } : {}),
...(type ? { type } : {}),
...(url ? { url } : {}),
};
}
function actionInstruction(action: RuntimeRecommendedAction | null | undefined): string {
const providerActionCode = text(action?.providerActionCode);
const url = text(action?.url);
if (!url) {
return providerActionCode
? " Ask them to open the mem9 console to resolve the account or billing state."
: "";
}
if (providerActionCode === "claimApiKey") {
return ` Ask them to open this link to sign in or create a mem9 account and claim this API key: ${url}. Include the link exactly as written.`;
}
if (providerActionCode === "upgradePlan") {
return ` Ask them to open this link to upgrade their mem9 plan and get more included usage: ${url}. Include the link exactly as written.`;
}
if (providerActionCode === "increaseSpendingLimit") {
return ` Ask them to open this link to increase the mem9 spending limit or adjust billing settings: ${url}. Include the link exactly as written.`;
}
if (providerActionCode === "enableOnDemand") {
return ` Ask them to open this link to enable billing or on-demand usage for mem9: ${url}. Include the link exactly as written.`;
}
return ` Ask them to open this mem9 link to resolve the account or billing state: ${url}. Include the link exactly as written.`;
}
function budgetNumbers(budget: Record<string, unknown>): {
percent: number | null;
remaining: number | null;
capacity: number | null;
} {
const usage = isRecord(budget.usage) ? budget.usage : {};
const capacity = isRecord(budget.capacity) ? budget.capacity : {};
const capacityValue = text(capacity.type) === "limited"
? numberValue(capacity.value)
: null;
return {
percent: numberValue(usage.percent),
remaining: numberValue(usage.remaining),
capacity: capacityValue != null && capacityValue > 0 ? capacityValue : null,
};
}
export function formatRuntimeStateNotice(runtimeState: unknown): string {
if (!isRecord(runtimeState)) return "";
const action = normalizeAction(runtimeState.recommendedAction);
const candidates: Array<{
priority: number;
message: string;
action?: RuntimeRecommendedAction | null;
}> = [];
const mem9ApiKey = isRecord(runtimeState.mem9ApiKey) ? runtimeState.mem9ApiKey : {};
if (text(mem9ApiKey.status) === "inactive") {
const detail = "Mem9 API key is inactive; rerun mem9 setup or create a new mem9 API key before memory access can continue";
candidates.push({
priority: 65,
action,
message: warningMessage(detail),
});
}
if (action && (text(action.severity) || text(action.url))) {
const detail = "Mem9 needs account or billing attention";
candidates.push({
priority: action.severity === "blocking" ? 50 : 20,
action,
message: warningMessage(detail),
});
}
const meters = Array.isArray(runtimeState.meters) ? runtimeState.meters : [];
for (const rawMeter of meters) {
if (!isRecord(rawMeter)) continue;
const feature = meterLabel(text(rawMeter.meter));
const gate = isRecord(rawMeter.quotaGateResult) ? rawMeter.quotaGateResult : {};
const outcome = text(gate.outcome);
const mode = text(gate.mode);
if (outcome === "blocked") {
const detail = `${feature} is blocked by runtime quota and needs attention before memory access can continue`;
candidates.push({
priority: 60,
action,
message: warningMessage(detail),
});
} else if (outcome === "rateLimited") {
const detail = `${feature} has reached its temporary runtime rate limit and needs a retry later`;
candidates.push({
priority: 55,
action,
message: warningMessage(detail),
});
} else if (mode === "onDemand" || mode === "postQuota") {
const detail = `${feature} is in constrained mode and using ${modeLabel(mode)}`;
candidates.push({
priority: 40,
action,
message: warningMessage(detail),
});
}
const budgets = Array.isArray(rawMeter.budgets) ? rawMeter.budgets : [];
for (const rawBudget of budgets) {
if (!isRecord(rawBudget)) continue;
const label = budgetLabel(text(rawBudget.type));
const state = text(rawBudget.state);
const numbers = budgetNumbers(rawBudget);
const absoluteUrgent = numbers.capacity != null
&& numbers.remaining != null
&& numbers.remaining <= Math.max(5, numbers.capacity * 0.02);
if (state === "exhausted") {
const detail = `${feature} has exhausted its ${label} and is in constrained mode`;
candidates.push({
priority: 45,
action,
message: warningMessage(detail),
});
} else if (
(numbers.percent != null && numbers.percent >= URGENT_PERCENT)
|| absoluteUrgent
) {
const usage = numbers.remaining != null
? `has ${compactNumber(numbers.remaining)} units remaining in its ${label}`
: `is at ${compactNumber(numbers.percent ?? URGENT_PERCENT)}% of its ${label}`;
candidates.push({
priority: 35,
action,
message: warningMessage(`${feature} ${usage} and is almost out of runtime quota`),
});
} else if (
state === "warning"
|| (numbers.percent != null && numbers.percent >= WARNING_PERCENT)
) {
const usage = numbers.percent != null
? `is at ${compactNumber(numbers.percent)}% of its ${label}`
: `is nearing its ${label}`;
candidates.push({
priority: 25,
action,
message: warningMessage(`${feature} ${usage} and is nearing its runtime quota`),
});
}
}
}
candidates.sort((left, right) => right.priority - left.priority);
const selected = candidates[0];
return selected
? `${selected.message}${actionInstruction(selected.action)}`
: "";
}