gongxiangp2/apps/detail-agent-pi/src/context-usage.mjs

80 lines
4.3 KiB
JavaScript

import { calculateContextTokens, getLastAssistantUsage } from '@earendil-works/pi-coding-agent';
/** Usage is scoped to one model and one project. Never turn a local safety
* budget, a billing tier or a missing receipt into a claimed model capacity. */
export const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
export function contextLengths(context) {
let imageChars = 0;
const textChars = JSON.stringify(context, (_key, value) => {
if (value?.type !== 'image' || typeof value.data !== 'string') return value;
imageChars += value.data.length;
return {...value, data: ''};
}).length;
return {textChars, totalChars: textChars + imageChars};
}
const productionReads = new Set(['plan_production', 'read_copy_fields', 'review_image_slots']);
export function foldSupersededProductionReads(messages) {
const calls = new Map();
for (const message of messages) {
if (message.role !== 'assistant') continue;
for (const block of message.content) {
if (block.type === 'toolCall' && productionReads.has(block.name)) calls.set(block.id, block.arguments);
}
}
const latest = new Set();
let folded;
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (message.role !== 'toolResult' || message.isError || !productionReads.has(message.toolName)) continue;
const {outputId, variantId} = message.details ?? {};
const args = calls.get(message.toolCallId);
if (!outputId || !variantId || !args) continue;
const {slotIds, pageId, fieldId, includeKnowledge} = args;
const scope = JSON.stringify([message.toolName,outputId,variantId,
[...new Set(slotIds?.map(id=>id.trim()).filter(Boolean))].sort(),
pageId?.trim()||null,fieldId?.trim()||null,Boolean(includeKnowledge)]);
if (!latest.has(scope)) {
latest.add(scope);
continue;
}
folded ??= messages.slice();
folded[index] = {...message, details:undefined, content:[{type:'text',
text:'同范围已有更新回执。旧回执编号:'+message.toolCallId+',可用 memory_search 读取。'}]};
}
return folded ?? messages;
}
export function modelCapacity(model) {
const limit = count(model.contextWindow);
return limit > 0 && typeof model.contextWindowSource === 'string' && model.contextWindowSource.length > 0
? { limit, source: model.contextWindowSource } : { limit: null, source: null };
}
export function piContextUsage(session, model) {
const native = session.getContextUsage();
const manager = session.sessionManager;
const branch = manager.getBranch();
const boundary = branch.findLastIndex(entry => entry.type === 'compaction' || entry.type === 'context_edit');
const eligible = new Set(branch.slice(boundary + 1).map(entry => entry.id));
const entries = manager.buildSessionProjection().entries
.filter(entry => eligible.has(entry.sourceEntry.id))
.flatMap(entry => entry.messages.map(message => ({ type: 'message', message })));
const last = entries.findLast(entry => getLastAssistantUsage([entry]));
// A prior model's receipt is not the current model's context measurement.
if (last && last.message.model !== model.id) return { contextTokens: null, contextSource: 'pi-model-changed' };
if (native) return { contextTokens: count(native.tokens), contextSource: 'pi-session', piContextUsage: native };
// Pi returns undefined when contextWindow <= 0. Preserve
// its real latest assistant usage without fabricating a limit or percentage.
// Exclude receipts invalidated by compaction/context edits, just like Pi.
const usage = getLastAssistantUsage(entries);
return { contextTokens: usage ? count(calculateContextTokens(usage)) : null,
contextSource: usage ? 'pi-last-response' : 'pi-awaiting-usage' };
}
export function contextSnapshot(identity, model, session, previous = null, receipt = null, phase = 'ready') {
const capacity = modelCapacity(model);
const same = previous?.scope === identity.scope && previous?.project === identity.project && previous?.model === model.id;
return { version: 1, ...identity, model: model.id, modelKey: model.key ?? null, protocol: model.protocol,
...piContextUsage(session, model), contextWindow: capacity.limit, capacitySource: capacity.source,
receipt: receipt ?? (same ? previous.receipt : null), phase, at: Date.now() };
}