(args: {
db: ContextDatabase;
sessionId: string;
message: unknown;
piContextWindow: number;
piTokens?: number;
notifyIssue?: (message: string) => unknown | Promise<unknown>;
})
| 250 | } |
| 251 | |
| 252 | export async function persistPiPressureFromMessageEnd(args: { |
| 253 | db: ContextDatabase; |
| 254 | sessionId: string; |
| 255 | message: unknown; |
| 256 | piContextWindow: number; |
| 257 | piTokens?: number; |
| 258 | notifyIssue?: (message: string) => unknown | Promise<unknown>; |
| 259 | }): Promise<void> { |
| 260 | const { provider, model } = getPiMessageModel(args.message); |
| 261 | const effectiveContextLimit = resolvePiPressureContextLimit({ |
| 262 | db: args.db, |
| 263 | sessionId: args.sessionId, |
| 264 | piContextWindow: args.piContextWindow, |
| 265 | }); |
| 266 | const usage = extractAssistantUsage(args.message); |
| 267 | const pressure = computePiPressure(usage, effectiveContextLimit); |
| 268 | const msg = |
| 269 | args.message && typeof args.message === "object" |
| 270 | ? (args.message as { errorMessage?: unknown }) |
| 271 | : undefined; |
| 272 | const messageHadOverflowError = |
| 273 | typeof msg?.errorMessage === "string" && |
| 274 | detectOverflow(msg.errorMessage).isOverflow; |
| 275 | const updates: Partial<{ |
| 276 | lastResponseTime: number; |
| 277 | lastContextPercentage: number; |
| 278 | lastInputTokens: number; |
| 279 | observedSafeInputTokens: number; |
| 280 | cacheAlertSent: boolean; |
| 281 | }> = { lastResponseTime: Date.now() }; |
| 282 | |
| 283 | if (pressure) { |
| 284 | const percentage = pressure.percentage; |
| 285 | const contextLimit = effectiveContextLimit; |
| 286 | const meta = getOrCreateSessionMeta(args.db, args.sessionId); |
| 287 | const observedSafeInputTokens = meta.observedSafeInputTokens ?? 0; |
| 288 | if ( |
| 289 | percentage > 100 && |
| 290 | observedSafeInputTokens > 0 && |
| 291 | pressure.inputTokens <= observedSafeInputTokens * 2 |
| 292 | ) { |
| 293 | // Pi resolves the window from its own runtime, not a cache we could |
| 294 | // reload — so a >100% reading with a known-good safe baseline means |
| 295 | // Pi's reported contextWindow is genuinely wrong. There's nothing to |
| 296 | // re-fetch; surface the alert (overflow detection still captures a |
| 297 | // real lower cap separately). |
| 298 | if (!meta.cacheAlertSent) { |
| 299 | updates.cacheAlertSent = true; |
| 300 | const safeTokens = Math.max( |
| 301 | observedSafeInputTokens, |
| 302 | pressure.inputTokens, |
| 303 | ); |
| 304 | const modelLabel = |
| 305 | provider && model ? `${provider}/${model}` : "the active model"; |
| 306 | await args.notifyIssue?.( |
| 307 | `⚠️ Magic Context: Pi reports a context limit of ${formatTokens(contextLimit)} tokens for ${modelLabel} but you've successfully sent ${formatTokens(safeTokens)} tokens in this session — the reported limit looks wrong. Restart Pi if you suspect this is incorrect.`, |
| 308 | ); |
| 309 | } |
no test coverage detected