@oh-my-pi/pi-agent-core 19.2.0 → 19.3.0
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/CHANGELOG.md +33 -0
- package/dist/types/agent-loop.d.ts +3 -0
- package/dist/types/agent.d.ts +25 -3
- package/dist/types/append-only-context.d.ts +3 -0
- package/dist/types/compaction/compaction.d.ts +19 -2
- package/dist/types/compaction/messages.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/inherited-tool-descriptions.d.ts +23 -0
- package/dist/types/types.d.ts +16 -2
- package/package.json +12 -12
- package/src/agent-loop.ts +72 -7
- package/src/agent.ts +83 -42
- package/src/append-only-context.ts +9 -1
- package/src/compaction/compaction.ts +125 -99
- package/src/compaction/messages.ts +2 -0
- package/src/compaction/shake.ts +3 -1
- package/src/index.ts +2 -0
- package/src/inherited-tool-descriptions.ts +43 -0
- package/src/telemetry.ts +6 -5
- package/src/tokenizer.ts +69 -19
- package/src/types.ts +20 -2
|
@@ -24,7 +24,6 @@ import {
|
|
|
24
24
|
type Usage,
|
|
25
25
|
withAuth,
|
|
26
26
|
} from "@oh-my-pi/pi-ai";
|
|
27
|
-
import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
|
|
28
27
|
import * as AIError from "@oh-my-pi/pi-ai/error";
|
|
29
28
|
import { createOpenAICodexCompactionRequestContext } from "@oh-my-pi/pi-ai/providers/openai-codex-compaction";
|
|
30
29
|
import type { OpenAICodexCompactionBody } from "@oh-my-pi/pi-ai/providers/openai-codex-responses";
|
|
@@ -190,6 +189,13 @@ export interface CompactionSettings {
|
|
|
190
189
|
* explicit value — even one equal to the default — is always honored.
|
|
191
190
|
*/
|
|
192
191
|
reserveTokens?: number;
|
|
192
|
+
/**
|
|
193
|
+
* Opt-in output budget for regular history summaries, replacing the default
|
|
194
|
+
* `min(floor(0.8 × reserveTokens), MAX_SUMMARY_TOKENS)` and clamped to the
|
|
195
|
+
* summarizer's own output limit. Turn-prefix and provider-native summaries
|
|
196
|
+
* keep their defaults. Unset keeps the default budget.
|
|
197
|
+
*/
|
|
198
|
+
summaryMaxTokens?: number;
|
|
193
199
|
keepRecentTokens: number;
|
|
194
200
|
autoContinue?: boolean;
|
|
195
201
|
remoteEnabled?: boolean;
|
|
@@ -201,6 +207,15 @@ export interface CompactionSettings {
|
|
|
201
207
|
/** Reserve applied when {@link CompactionSettings.reserveTokens} is unset. */
|
|
202
208
|
export const DEFAULT_RESERVE_TOKENS = 16384;
|
|
203
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Ceiling on the default compaction trigger (`thresholdPercent`/`thresholdTokens`
|
|
212
|
+
* unset). Every request re-reads the whole context from the prompt cache, so the
|
|
213
|
+
* cost of a long cycle grows with absolute size, not with the window's share:
|
|
214
|
+
* 1M-class windows (past ~812K, where 85% would land above this) compact here.
|
|
215
|
+
* A configured percentage, fixed trigger, or model base is not capped.
|
|
216
|
+
*/
|
|
217
|
+
export const DEFAULT_THRESHOLD_CEILING_TOKENS = 690_000;
|
|
218
|
+
|
|
204
219
|
/**
|
|
205
220
|
* Hysteresis band under the compaction trigger. Maintenance counts as having
|
|
206
221
|
* resolved threshold pressure only when residual context lands at or below
|
|
@@ -226,6 +241,19 @@ export const COMPACTION_RECOVERY_BAND = 0.8;
|
|
|
226
241
|
*/
|
|
227
242
|
export const MAX_SUMMARY_TOKENS = DEFAULT_RESERVE_TOKENS;
|
|
228
243
|
|
|
244
|
+
/**
|
|
245
|
+
* Output budget for one regular history summary. The default is the reserve
|
|
246
|
+
* fraction under {@link MAX_SUMMARY_TOKENS}; a positive configured
|
|
247
|
+
* `summaryMaxTokens` replaces it, bounded by the summarizer's output limit.
|
|
248
|
+
*/
|
|
249
|
+
function regularSummaryMaxTokens(model: Model, reserveTokens: number, summaryMaxTokens: number | undefined): number {
|
|
250
|
+
if (summaryMaxTokens === undefined || !Number.isFinite(summaryMaxTokens) || summaryMaxTokens <= 0) {
|
|
251
|
+
return Math.min(Math.floor(0.8 * reserveTokens), MAX_SUMMARY_TOKENS);
|
|
252
|
+
}
|
|
253
|
+
const requested = Math.floor(summaryMaxTokens);
|
|
254
|
+
return model.maxTokens && model.maxTokens > 0 ? Math.min(requested, model.maxTokens) : requested;
|
|
255
|
+
}
|
|
256
|
+
|
|
229
257
|
// reserveTokens is deliberately absent: an unset reserve is what marks it as
|
|
230
258
|
// defaulted, which resolveBudgetReserveTokens needs to distinguish "user never
|
|
231
259
|
// chose a reserve" from "user explicitly configured the default value".
|
|
@@ -419,9 +447,9 @@ export function resolveThresholdTokens(contextWindow: number, settings: Compacti
|
|
|
419
447
|
return Math.min(contextWindow - 1, Math.max(1, thresholdTokens));
|
|
420
448
|
}
|
|
421
449
|
const baseWindowTokens = settings.baseWindowTokens;
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
450
|
+
const scaledFromBase =
|
|
451
|
+
typeof baseWindowTokens === "number" && Number.isFinite(baseWindowTokens) && baseWindowTokens > 0;
|
|
452
|
+
if (scaledFromBase) contextWindow = Math.min(contextWindow, baseWindowTokens);
|
|
425
453
|
|
|
426
454
|
// Percentage-based threshold. The default absolute reserve can exceed bundled
|
|
427
455
|
// small-context windows, or nearly consume a 16k-class window; in those
|
|
@@ -430,7 +458,9 @@ export function resolveThresholdTokens(contextWindow: number, settings: Compacti
|
|
|
430
458
|
// configured reserves still define the usable prompt budget.
|
|
431
459
|
const thresholdPercent = settings.thresholdPercent;
|
|
432
460
|
if (typeof thresholdPercent !== "number" || !Number.isFinite(thresholdPercent) || thresholdPercent <= 0) {
|
|
433
|
-
|
|
461
|
+
const budget = promptBudgetTokens(contextWindow, settings);
|
|
462
|
+
// A model entry's base is a window the user chose to scale from; only the bare default stops at the ceiling.
|
|
463
|
+
return scaledFromBase ? budget : Math.min(budget, DEFAULT_THRESHOLD_CEILING_TOKENS);
|
|
434
464
|
}
|
|
435
465
|
const clampedThresholdPercent = Math.min(99, Math.max(1, thresholdPercent));
|
|
436
466
|
return Math.floor(contextWindow * (clampedThresholdPercent / 100));
|
|
@@ -708,6 +738,8 @@ export interface SummaryOptions {
|
|
|
708
738
|
/** Additional summary context fetched only when a compaction request consumes it. */
|
|
709
739
|
loadExtraContext?: () => Promise<string[] | undefined>;
|
|
710
740
|
remoteEndpoint?: string;
|
|
741
|
+
/** Configured regular-summary output budget; see {@link CompactionSettings.summaryMaxTokens}. */
|
|
742
|
+
summaryMaxTokens?: number;
|
|
711
743
|
/** Stable system-prompt segments from the live turn, preserved for provider cache reuse. */
|
|
712
744
|
remoteSystemPrompt?: string[];
|
|
713
745
|
initiatorOverride?: MessageAttribution;
|
|
@@ -891,9 +923,8 @@ function createSnapcompactArchiveMigrationMessage(archiveText: string): Message
|
|
|
891
923
|
const DEFAULT_SUMMARY_INPUT_WINDOW = 200_000;
|
|
892
924
|
|
|
893
925
|
/**
|
|
894
|
-
*
|
|
895
|
-
* Scaled down (never below 1k) for
|
|
896
|
-
* floor next to the carried summary and output reserves.
|
|
926
|
+
* Smallest conversation window worth retrying after a provider overflow.
|
|
927
|
+
* Scaled down (never below 1k) for small-context summarizers.
|
|
897
928
|
*/
|
|
898
929
|
const MIN_SUMMARY_INPUT_TOKENS = 16_384;
|
|
899
930
|
|
|
@@ -904,17 +935,16 @@ function minSummaryInputTokens(model: Model): number {
|
|
|
904
935
|
}
|
|
905
936
|
|
|
906
937
|
/**
|
|
907
|
-
*
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
* estimate, so the window is discounted before the fixed reserves come off.
|
|
938
|
+
* Input available for the conversation and carried summary together, after
|
|
939
|
+
* reserving output and discounting the window for prompt scaffolding and
|
|
940
|
+
* differences between provider and local tokenizer counts.
|
|
911
941
|
*/
|
|
912
942
|
function summaryInputBudgetTokens(model: Model, maxTokens: number): number {
|
|
913
943
|
const window = model.contextWindow && model.contextWindow > 0 ? model.contextWindow : DEFAULT_SUMMARY_INPUT_WINDOW;
|
|
914
944
|
// 0.8, not "window minus reserves": provider tokenizers disagree with the
|
|
915
945
|
// local cl100k estimate by a few percent, and being wrong here is a hard
|
|
916
946
|
// 400 on the one call that is supposed to rescue an oversized session.
|
|
917
|
-
return Math.max(
|
|
947
|
+
return Math.max(1, Math.floor(window * 0.8) - maxTokens);
|
|
918
948
|
}
|
|
919
949
|
|
|
920
950
|
/**
|
|
@@ -930,43 +960,6 @@ function clampConversationToBudget(text: string, budgetTokens: number, tokens: n
|
|
|
930
960
|
return `${text.slice(0, keep)}\n\n[... ${text.length - keep} more characters truncated]`;
|
|
931
961
|
}
|
|
932
962
|
|
|
933
|
-
/** One planned summarization call: its messages and the budget they were packed for. */
|
|
934
|
-
interface SummaryWindow {
|
|
935
|
-
messages: Message[];
|
|
936
|
-
budgetTokens: number;
|
|
937
|
-
/** Serialization reused from the fit check, so the common path serializes once. */
|
|
938
|
-
text?: string;
|
|
939
|
-
}
|
|
940
|
-
|
|
941
|
-
/**
|
|
942
|
-
* Partition a conversation into windows that each fit `budgetTokens`, splitting
|
|
943
|
-
* on message boundaries. Only called when the whole conversation does not fit —
|
|
944
|
-
* the common single-window path never pays this per-message sizing pass.
|
|
945
|
-
*/
|
|
946
|
-
function planSummaryWindows(
|
|
947
|
-
messages: Message[],
|
|
948
|
-
tokenizer: Tokenizer,
|
|
949
|
-
dialect: Dialect | undefined,
|
|
950
|
-
dropThinking: boolean,
|
|
951
|
-
budgetTokens: number,
|
|
952
|
-
): Message[][] {
|
|
953
|
-
const windows: Message[][] = [];
|
|
954
|
-
let current: Message[] = [];
|
|
955
|
-
let currentTokens = 0;
|
|
956
|
-
for (const message of messages) {
|
|
957
|
-
const tokens = tokenizer.countTokens(serializeConversationForSummary([message], dialect, dropThinking));
|
|
958
|
-
if (currentTokens > 0 && currentTokens + tokens > budgetTokens) {
|
|
959
|
-
windows.push(current);
|
|
960
|
-
current = [];
|
|
961
|
-
currentTokens = 0;
|
|
962
|
-
}
|
|
963
|
-
current.push(message);
|
|
964
|
-
currentTokens += tokens;
|
|
965
|
-
}
|
|
966
|
-
if (current.length > 0) windows.push(current);
|
|
967
|
-
return windows;
|
|
968
|
-
}
|
|
969
|
-
|
|
970
963
|
export async function generateSummary(
|
|
971
964
|
currentMessages: AgentMessage[],
|
|
972
965
|
model: Model,
|
|
@@ -977,7 +970,7 @@ export async function generateSummary(
|
|
|
977
970
|
previousSummary?: string,
|
|
978
971
|
options?: SummaryOptions,
|
|
979
972
|
): Promise<string> {
|
|
980
|
-
const maxTokens =
|
|
973
|
+
const maxTokens = regularSummaryMaxTokens(model, reserveTokens, options?.summaryMaxTokens);
|
|
981
974
|
|
|
982
975
|
// Serialize conversation to text so model doesn't try to continue it
|
|
983
976
|
// Convert to LLM messages first (handles custom app messages when caller provides a transformer).
|
|
@@ -985,34 +978,52 @@ export async function generateSummary(
|
|
|
985
978
|
const dialect = preferredDialect(model.id);
|
|
986
979
|
const dropThinking = resolveCatalogPolicy(model).classifierCotExtraction === true;
|
|
987
980
|
const tokenizer = new Tokenizer(model);
|
|
988
|
-
const wholeConversation = serializeConversationForSummary(llmMessages, dialect, dropThinking);
|
|
989
|
-
const budgetTokens = summaryInputBudgetTokens(model, maxTokens);
|
|
990
|
-
// A span that outgrew the summarizer's window is summarized as a fold: each
|
|
991
|
-
// window updates the summary carried out of the previous one, which is the
|
|
992
|
-
// same contract the update prompt already implements for iterative
|
|
993
|
-
// compaction. The alternative is a hard provider rejection on a prompt no
|
|
994
|
-
// retry can shrink — the state a cross-provider compaction boundary
|
|
995
|
-
// (see `prepareCompaction`) puts a long session into. One window is the
|
|
996
|
-
// common case and costs exactly the one call it always did.
|
|
997
|
-
const pending: SummaryWindow[] = tokenizer.checkTokenBudget(wholeConversation, budgetTokens).fits
|
|
998
|
-
? [{ messages: llmMessages, budgetTokens, text: wholeConversation }]
|
|
999
|
-
: planSummaryWindows(llmMessages, tokenizer, dialect, dropThinking, budgetTokens).map(messages => ({
|
|
1000
|
-
messages,
|
|
1001
|
-
budgetTokens,
|
|
1002
|
-
}));
|
|
1003
|
-
|
|
1004
981
|
let carriedSummary = previousSummary;
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
//
|
|
1011
|
-
|
|
982
|
+
let start = 0;
|
|
983
|
+
const catalogBudget = summaryInputBudgetTokens(model, maxTokens);
|
|
984
|
+
let inputBudget = catalogBudget;
|
|
985
|
+
let messageTokens: number[] | undefined;
|
|
986
|
+
function nextWindow(budgetTokens: number) {
|
|
987
|
+
// Most histories fit without a per-message sizing pass.
|
|
988
|
+
if (start === 0 && inputBudget === catalogBudget) {
|
|
989
|
+
const text = serializeConversationForSummary(llmMessages, dialect, dropThinking);
|
|
990
|
+
const budget = tokenizer.checkTokenBudget(text, budgetTokens);
|
|
991
|
+
if (budget.fits || llmMessages.length <= 1) return { text, budget, end: llmMessages.length };
|
|
992
|
+
}
|
|
993
|
+
messageTokens ??= [];
|
|
994
|
+
let tokens = 0;
|
|
995
|
+
let end = start;
|
|
996
|
+
while (end < llmMessages.length) {
|
|
997
|
+
const count = (messageTokens[end] ??= tokenizer.countTokens(
|
|
998
|
+
serializeConversationForSummary([llmMessages[end]], dialect, dropThinking),
|
|
999
|
+
"strict",
|
|
1000
|
+
));
|
|
1001
|
+
if (end > start && tokens + count > budgetTokens) break;
|
|
1002
|
+
tokens += count;
|
|
1003
|
+
end++;
|
|
1004
|
+
}
|
|
1005
|
+
// Separators can make the packed conversation larger than the sum of
|
|
1006
|
+
// its parts. Split at a message boundary rather than discard its tail.
|
|
1007
|
+
for (;;) {
|
|
1008
|
+
const text = serializeConversationForSummary(llmMessages.slice(start, end), dialect, dropThinking);
|
|
1009
|
+
const budget = tokenizer.checkTokenBudget(text, budgetTokens);
|
|
1010
|
+
if (budget.fits || end <= start + 1) return { text, budget, end };
|
|
1011
|
+
end--;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
do {
|
|
1015
|
+
// Cancellation ends the fold: no window starts on an aborted signal.
|
|
1016
|
+
if (signal?.aborted) throw new AIError.AbortError("Summarization aborted", { cause: signal.reason });
|
|
1017
|
+
// The previous call's actual output is input to this one. Pack only
|
|
1018
|
+
// this window, not the remaining windows against a hypothetical cap.
|
|
1019
|
+
const escapedSummary = carriedSummary && escapeSummaryBoundaryTags(carriedSummary);
|
|
1020
|
+
const carriedTokens = escapedSummary ? tokenizer.countTokens(escapedSummary, "strict") : 0;
|
|
1021
|
+
const budgetTokens = Math.max(1, inputBudget - carriedTokens);
|
|
1022
|
+
const { text, budget, end } = nextWindow(budgetTokens);
|
|
1012
1023
|
try {
|
|
1013
1024
|
carriedSummary = await summarizeConversationWindow(
|
|
1014
|
-
budget.fits ? text : clampConversationToBudget(text,
|
|
1015
|
-
|
|
1025
|
+
budget.fits ? text : clampConversationToBudget(text, budgetTokens, budget.tokens),
|
|
1026
|
+
escapedSummary,
|
|
1016
1027
|
model,
|
|
1017
1028
|
maxTokens,
|
|
1018
1029
|
apiKey,
|
|
@@ -1032,32 +1043,25 @@ export async function generateSummary(
|
|
|
1032
1043
|
// fit path never counted this window, so pay for the exact size here —
|
|
1033
1044
|
// one tokenization is nothing against the provider round trip already lost.
|
|
1034
1045
|
const sentTokens = budget.exact ? budget.tokens : tokenizer.countTokens(text, "strict");
|
|
1035
|
-
const
|
|
1046
|
+
const sent = Math.min(budgetTokens, sentTokens);
|
|
1036
1047
|
if (
|
|
1037
1048
|
!AIError.is(AIError.classify(error), AIError.Flag.ContextOverflow) ||
|
|
1038
|
-
|
|
1049
|
+
sent <= minSummaryInputTokens(model)
|
|
1039
1050
|
) {
|
|
1040
1051
|
throw error;
|
|
1041
1052
|
}
|
|
1042
|
-
|
|
1043
|
-
0,
|
|
1044
|
-
1,
|
|
1045
|
-
...planSummaryWindows(window.messages, tokenizer, dialect, dropThinking, halved).map(messages => ({
|
|
1046
|
-
messages,
|
|
1047
|
-
budgetTokens: halved,
|
|
1048
|
-
})),
|
|
1049
|
-
);
|
|
1053
|
+
inputBudget = carriedTokens + Math.max(minSummaryInputTokens(model), Math.floor(sent / 2));
|
|
1050
1054
|
continue;
|
|
1051
1055
|
}
|
|
1052
|
-
|
|
1053
|
-
}
|
|
1056
|
+
start = end;
|
|
1057
|
+
} while (start < llmMessages.length);
|
|
1054
1058
|
return carriedSummary ?? "";
|
|
1055
1059
|
}
|
|
1056
1060
|
|
|
1057
1061
|
/** One summarization call over a single conversation window. */
|
|
1058
1062
|
async function summarizeConversationWindow(
|
|
1059
1063
|
conversationText: string,
|
|
1060
|
-
|
|
1064
|
+
escapedPreviousSummary: string | undefined,
|
|
1061
1065
|
model: Model,
|
|
1062
1066
|
maxTokens: number,
|
|
1063
1067
|
apiKey: ApiKey,
|
|
@@ -1066,7 +1070,7 @@ async function summarizeConversationWindow(
|
|
|
1066
1070
|
options: SummaryOptions | undefined,
|
|
1067
1071
|
): Promise<string> {
|
|
1068
1072
|
// Use update prompt if we have a previous summary, otherwise initial prompt
|
|
1069
|
-
let basePrompt =
|
|
1073
|
+
let basePrompt = escapedPreviousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
|
|
1070
1074
|
if (options?.promptOverride) {
|
|
1071
1075
|
basePrompt = options.promptOverride;
|
|
1072
1076
|
}
|
|
@@ -1076,8 +1080,8 @@ async function summarizeConversationWindow(
|
|
|
1076
1080
|
|
|
1077
1081
|
// Build the prompt with conversation wrapped in tags
|
|
1078
1082
|
let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
|
|
1079
|
-
if (
|
|
1080
|
-
promptText += `<previous-summary>\n${
|
|
1083
|
+
if (escapedPreviousSummary) {
|
|
1084
|
+
promptText += `<previous-summary>\n${escapedPreviousSummary}\n</previous-summary>\n\n`;
|
|
1081
1085
|
}
|
|
1082
1086
|
promptText += formatAdditionalContext(options?.extraContext);
|
|
1083
1087
|
promptText += basePrompt;
|
|
@@ -1130,6 +1134,11 @@ async function summarizeConversationWindow(
|
|
|
1130
1134
|
},
|
|
1131
1135
|
);
|
|
1132
1136
|
|
|
1137
|
+
// Providers report cancellation as a resolved message with partial output.
|
|
1138
|
+
// It is no summary, and the next window would start on the same aborted signal.
|
|
1139
|
+
if (response.stopReason === "aborted") {
|
|
1140
|
+
throw new AIError.AbortError("Summarization aborted", { cause: signal?.reason });
|
|
1141
|
+
}
|
|
1133
1142
|
if (response.stopReason === "error") {
|
|
1134
1143
|
throw createSummarizationError("Summarization failed", response);
|
|
1135
1144
|
}
|
|
@@ -1186,8 +1195,8 @@ export interface HandoffFromContextOptions {
|
|
|
1186
1195
|
* session's payload/response hooks. Sending the same routing + payload shape
|
|
1187
1196
|
* the main loop uses is what lets the handoff oneshot READ the provider
|
|
1188
1197
|
* prompt cache the live turn populated instead of cold-missing the whole
|
|
1189
|
-
* prefix. `reasoning` and `toolChoice` are set internally and
|
|
1190
|
-
* anything provided here.
|
|
1198
|
+
* prefix. `maxTokens`, `reasoning` and `toolChoice` are set internally and
|
|
1199
|
+
* override anything provided here.
|
|
1191
1200
|
*/
|
|
1192
1201
|
streamOptions: SimpleStreamOptions;
|
|
1193
1202
|
/** Optional completion transport override for host-level request wrappers. */
|
|
@@ -1229,6 +1238,11 @@ export async function generateHandoffFromContext(
|
|
|
1229
1238
|
}
|
|
1230
1239
|
const requestOptions = {
|
|
1231
1240
|
...options.streamOptions,
|
|
1241
|
+
// Bound the document like a summary: without an explicit cap a local
|
|
1242
|
+
// server falls back to its own (possibly unlimited) output limit, so a
|
|
1243
|
+
// runaway stream never ends and maintenance never reaches its next method.
|
|
1244
|
+
// Hitting the cap ends with `stopReason: "length"`, rejected below.
|
|
1245
|
+
maxTokens: MAX_SUMMARY_TOKENS,
|
|
1232
1246
|
reasoning: resolveCompactionEffort(model, options.thinkingLevel),
|
|
1233
1247
|
toolChoice: "none" as const,
|
|
1234
1248
|
};
|
|
@@ -1852,6 +1866,7 @@ export async function compact(
|
|
|
1852
1866
|
promptOverride: options?.promptOverride,
|
|
1853
1867
|
extraContext: options?.extraContext,
|
|
1854
1868
|
remoteEndpoint: settings.remoteEnabled === false ? undefined : settings.remoteEndpoint,
|
|
1869
|
+
summaryMaxTokens: options?.summaryMaxTokens ?? settings.summaryMaxTokens,
|
|
1855
1870
|
remoteSystemPrompt: options?.remoteSystemPrompt,
|
|
1856
1871
|
initiatorOverride: options?.initiatorOverride,
|
|
1857
1872
|
metadata: options?.metadata,
|
|
@@ -2414,22 +2429,33 @@ export async function compact(
|
|
|
2414
2429
|
const inputTokens = getCompactionV2PreserveData(preserveData)?.usedTokens ?? 0;
|
|
2415
2430
|
summary = formatRemoteCompactionSummary(inputTokens);
|
|
2416
2431
|
} else if (isSplitTurn && turnPrefixMessages.length > 0) {
|
|
2417
|
-
// Generate both summaries in parallel
|
|
2418
|
-
|
|
2432
|
+
// Generate both summaries in parallel. The first failure aborts the other
|
|
2433
|
+
// request with that failure as the reason, and compaction throws it only
|
|
2434
|
+
// after both requests have stopped, so no summary request outlives the
|
|
2435
|
+
// compaction that started it. The caller's signal, with its own reason,
|
|
2436
|
+
// still reaches both requests.
|
|
2437
|
+
const splitAbort = new AbortController();
|
|
2438
|
+
const summarySignal = signal ? AbortSignal.any([signal, splitAbort.signal]) : splitAbort.signal;
|
|
2439
|
+
const requests = [
|
|
2419
2440
|
messagesToSummarize.length > 0 || previousSummaryForCompaction
|
|
2420
2441
|
? generateSummary(
|
|
2421
2442
|
messagesToSummarize,
|
|
2422
2443
|
model,
|
|
2423
2444
|
reserveTokens,
|
|
2424
2445
|
apiKey,
|
|
2425
|
-
|
|
2446
|
+
summarySignal,
|
|
2426
2447
|
customInstructions,
|
|
2427
2448
|
previousSummaryForCompaction,
|
|
2428
2449
|
summaryOptions,
|
|
2429
2450
|
)
|
|
2430
2451
|
: Promise.resolve("No prior history."),
|
|
2431
|
-
generateTurnPrefixSummary(turnPrefixMessages, model, reserveTokens, apiKey,
|
|
2432
|
-
]
|
|
2452
|
+
generateTurnPrefixSummary(turnPrefixMessages, model, reserveTokens, apiKey, summarySignal, summaryOptions),
|
|
2453
|
+
] as const;
|
|
2454
|
+
const [historyResult, turnPrefixResult] = await Promise.all(requests).catch(async (error: unknown) => {
|
|
2455
|
+
splitAbort.abort(error);
|
|
2456
|
+
await Promise.allSettled(requests);
|
|
2457
|
+
throw error;
|
|
2458
|
+
});
|
|
2433
2459
|
// Merge into single summary
|
|
2434
2460
|
summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
|
|
2435
2461
|
} else if (messagesToSummarize.length > 0) {
|
|
@@ -51,6 +51,8 @@ export interface BranchSummaryMessage {
|
|
|
51
51
|
|
|
52
52
|
export interface CompactionSummaryMessage {
|
|
53
53
|
role: "compactionSummary";
|
|
54
|
+
/** Runtime replay state: a spoken delegation was still open at the retained-history boundary. */
|
|
55
|
+
liveVoiceOpen?: true;
|
|
54
56
|
summary: string;
|
|
55
57
|
shortSummary?: string;
|
|
56
58
|
tokensBefore: number;
|
package/src/compaction/shake.ts
CHANGED
|
@@ -75,7 +75,7 @@ export const RESCUE_SHAKE_CONFIG: ShakeConfig = {
|
|
|
75
75
|
protectedTools: [...AGGRESSIVE_SHAKE_CONFIG.protectedTools, isArtifactRecoveryToolResult],
|
|
76
76
|
};
|
|
77
77
|
|
|
78
|
-
/** Rough token cost of a placeholder line;
|
|
78
|
+
/** Rough token cost of a placeholder line; floors tool-result regions and feeds the savings gate. */
|
|
79
79
|
const PLACEHOLDER_TOKEN_ESTIMATE = 16;
|
|
80
80
|
|
|
81
81
|
/** A located eligible region. */
|
|
@@ -347,6 +347,8 @@ export function collectShakeRegions(entries: SessionEntry[], tokenizer: Tokenize
|
|
|
347
347
|
continue;
|
|
348
348
|
const text = toolResultText(toolResult, tokenizer);
|
|
349
349
|
if (!text) continue;
|
|
350
|
+
// Replacing a result no larger than its placeholder only grows context.
|
|
351
|
+
if (text.tokens <= PLACEHOLDER_TOKEN_ESTIMATE) continue;
|
|
350
352
|
regions.push({
|
|
351
353
|
kind: "toolResult",
|
|
352
354
|
entry: entry as SessionMessageEntry,
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export * from "./agent";
|
|
3
3
|
// Loop functions
|
|
4
4
|
export * from "./agent-loop";
|
|
5
|
+
// Owner-worded tool descriptions a fork sends to share its owner's cached prefix
|
|
6
|
+
export * from "./inherited-tool-descriptions";
|
|
5
7
|
// Append-only context mode
|
|
6
8
|
export * from "./append-only-context";
|
|
7
9
|
// Compaction
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Tool } from "@oh-my-pi/pi-ai";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Tool descriptions a fork sends in its owner's wording, so its requests open
|
|
5
|
+
* with the owner's cached prefix.
|
|
6
|
+
*
|
|
7
|
+
* A fork (`/tan`) continues its owner's transcript, but its tools render their
|
|
8
|
+
* descriptions from session state it does not share: no UI, no TUI transcript,
|
|
9
|
+
* a headless approval mode. Any byte of that drift sits ahead of the transcript,
|
|
10
|
+
* so the fork misses the owner's prompt cache entirely and, on prefix-bound
|
|
11
|
+
* reasoning (Claude, GPT-6.2), the provider drops every inherited thinking block.
|
|
12
|
+
*
|
|
13
|
+
* Only wording is inherited: a tool whose wire schema differs from the owner's
|
|
14
|
+
* keeps its own spec, so the model never sees arguments the fork's tool rejects.
|
|
15
|
+
* A pin holds while the fork's own description still renders as it did when
|
|
16
|
+
* pinned; once it changes (a setting, an MCP reload), the fork's own wording wins.
|
|
17
|
+
*/
|
|
18
|
+
export class InheritedToolDescriptions {
|
|
19
|
+
#byName = new Map<string, { own: string; owner: string }>();
|
|
20
|
+
|
|
21
|
+
/** Pin `owner`'s description of every tool `own` declares with the same wire schema but other wording. */
|
|
22
|
+
constructor(own: readonly Tool[], owner: readonly Tool[]) {
|
|
23
|
+
const ownerByName = new Map(owner.map(tool => [tool.name, tool]));
|
|
24
|
+
for (const tool of own) {
|
|
25
|
+
const ownerTool = ownerByName.get(tool.name);
|
|
26
|
+
if (!ownerTool || ownerTool.description === tool.description) continue;
|
|
27
|
+
if (wireShape(ownerTool) !== wireShape(tool)) continue;
|
|
28
|
+
this.#byName.set(tool.name, { own: tool.description, owner: ownerTool.description });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The description to send for `name`, given the one the fork renders now. */
|
|
33
|
+
resolve(name: string, description: string): string {
|
|
34
|
+
const pin = this.#byName.get(name);
|
|
35
|
+
return pin?.own === description ? pin.owner : description;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every wire field of `tool` except its description. */
|
|
40
|
+
function wireShape(tool: Tool): string {
|
|
41
|
+
const { description: _, ...shape } = tool;
|
|
42
|
+
return JSON.stringify(shape);
|
|
43
|
+
}
|
package/src/telemetry.ts
CHANGED
|
@@ -616,8 +616,6 @@ function mapProviderNameToOtel(provider: string | undefined): string | undefined
|
|
|
616
616
|
case "amazon-bedrock":
|
|
617
617
|
return "aws.bedrock";
|
|
618
618
|
case "google":
|
|
619
|
-
case "google-antigravity":
|
|
620
|
-
case "google-gemini-cli":
|
|
621
619
|
return "gcp.gemini";
|
|
622
620
|
case "google-vertex":
|
|
623
621
|
return "gcp.vertex_ai";
|
|
@@ -1161,7 +1159,7 @@ export async function finishChatSpan(
|
|
|
1161
1159
|
},
|
|
1162
1160
|
): Promise<void> {
|
|
1163
1161
|
if (!span) return;
|
|
1164
|
-
applyChatResponseAttributes(span, message);
|
|
1162
|
+
applyChatResponseAttributes(span, message, options.modelId);
|
|
1165
1163
|
applyUsageAttributes(span, message.usage);
|
|
1166
1164
|
applyGatewayAttributes(span, options.responseHeaders, options.baseUrl);
|
|
1167
1165
|
const cost = applyCostEstimate(telemetry, span, message, options.serviceTier, options.stepNumber, options.modelId);
|
|
@@ -1232,8 +1230,11 @@ export function failChatSpan(
|
|
|
1232
1230
|
span.end();
|
|
1233
1231
|
}
|
|
1234
1232
|
|
|
1235
|
-
function applyChatResponseAttributes(span: Span, message: AssistantMessage): void {
|
|
1236
|
-
|
|
1233
|
+
function applyChatResponseAttributes(span: Span, message: AssistantMessage, requestedModelId?: string): void {
|
|
1234
|
+
// A provider that promoted `model` to a served fallback has named the serving model;
|
|
1235
|
+
// `upstreamModel` can still hold the declined primary's signed id.
|
|
1236
|
+
const promoted = requestedModelId !== undefined && message.model !== requestedModelId;
|
|
1237
|
+
span.setAttribute(GenAIAttr.ResponseModel, promoted ? message.model : (message.upstreamModel ?? message.model));
|
|
1237
1238
|
if (message.responseId) span.setAttribute(GenAIAttr.ResponseId, message.responseId);
|
|
1238
1239
|
if (message.upstreamProvider) {
|
|
1239
1240
|
span.setAttribute(OmpGenAIAttr.ResponseUpstreamProvider, message.upstreamProvider);
|
package/src/tokenizer.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Api, AssistantMessage, Model } from "@oh-my-pi/pi-ai";
|
|
1
|
+
import type { Api, AssistantMessage, ImageContent, Model } from "@oh-my-pi/pi-ai";
|
|
2
2
|
import { renderDemotedThinking } from "@oh-my-pi/pi-ai/dialect/demotion";
|
|
3
3
|
import { isFactoryDroidGeminiWire, keepsFactoryGeminiReasoning } from "@oh-my-pi/pi-ai/providers/factory-droid/gemini";
|
|
4
4
|
import { ollamaChatDropsOwnThinking } from "@oh-my-pi/pi-ai/providers/ollama";
|
|
@@ -17,7 +17,7 @@ import { replaysSignedReasoningText } from "@oh-my-pi/pi-ai/utils/reasoning-sour
|
|
|
17
17
|
import { resolveThinkingReplayTokens, type ThinkingReplayTokens } from "@oh-my-pi/pi-catalog/compat/thinking-replay";
|
|
18
18
|
import type { ModelTokenizer } from "@oh-my-pi/pi-catalog/types";
|
|
19
19
|
import * as natives from "@oh-my-pi/pi-natives";
|
|
20
|
-
import { materializeString, stringifyJson } from "@oh-my-pi/pi-utils";
|
|
20
|
+
import { isRecord, materializeString, stringifyJson } from "@oh-my-pi/pi-utils";
|
|
21
21
|
import { LRUCache } from "@oh-my-pi/pi-utils/lru";
|
|
22
22
|
import * as snapcompact from "@oh-my-pi/snapcompact";
|
|
23
23
|
import { isEstimateCacheable, messageEstimateVersion } from "./compaction/message-cache";
|
|
@@ -174,6 +174,11 @@ function sumFragments(text: string | string[], perFragment: (t: string) => numbe
|
|
|
174
174
|
return Array.isArray(text) ? text.reduce((sum, t) => sum + perFragment(t), 0) : perFragment(text);
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
/** Whether `value`, a field of an app role read as data, is an image block a request can carry. */
|
|
178
|
+
function isImageBlock(value: unknown): value is ImageContent {
|
|
179
|
+
return isRecord(value) && value.type === "image" && typeof value.data === "string";
|
|
180
|
+
}
|
|
181
|
+
|
|
177
182
|
interface NativeTokenCount {
|
|
178
183
|
tokens: number;
|
|
179
184
|
exact: boolean;
|
|
@@ -417,6 +422,11 @@ export class Tokenizer {
|
|
|
417
422
|
return estimateImageTokens(size, detail, this.#frameBilling.rule);
|
|
418
423
|
}
|
|
419
424
|
|
|
425
|
+
/** {@link imageTokens} for an image block a request carries. */
|
|
426
|
+
#imageBlockTokens(image: ImageContent): number {
|
|
427
|
+
return this.imageTokens(base64ImageSize(image.data), image.detail);
|
|
428
|
+
}
|
|
429
|
+
|
|
420
430
|
/**
|
|
421
431
|
* Whether `message`'s signed reasoning reaches this reader natively: from
|
|
422
432
|
* the same model, host and wire, or from another Claude model on the same
|
|
@@ -469,25 +479,21 @@ export class Tokenizer {
|
|
|
469
479
|
}
|
|
470
480
|
|
|
471
481
|
#measureMessage(message: AgentMessage, excludeEncryptedReasoning: boolean, latestTurn: boolean): number {
|
|
482
|
+
const appTokens = this.#measureAppMessage(message);
|
|
483
|
+
if (appTokens !== undefined) return appTokens;
|
|
472
484
|
const fragments: string[] = [];
|
|
473
485
|
let extra = 0;
|
|
474
|
-
// Declaration-merged app roles (the coding-agent's bashExecution) are
|
|
475
|
-
// invisible to this package's union, so the discriminant is read as data.
|
|
476
|
-
const role: string = message.role;
|
|
477
|
-
if (role === "bashExecution") {
|
|
478
|
-
if ("command" in message && typeof message.command === "string") fragments.push(message.command);
|
|
479
|
-
if ("output" in message && typeof message.output === "string") fragments.push(message.output);
|
|
480
|
-
return fragments.length === 0 ? 0 : this.countTokens(fragments);
|
|
481
|
-
}
|
|
482
486
|
|
|
483
487
|
switch (message.role) {
|
|
484
488
|
case "user":
|
|
485
|
-
case "developer":
|
|
486
|
-
|
|
489
|
+
case "developer":
|
|
490
|
+
case "custom":
|
|
491
|
+
case "hookMessage": {
|
|
492
|
+
// All four roles carry `string | (TextContent | ImageContent)[]` and all are
|
|
487
493
|
// sent to the provider -- convertMessageToLlm handles developer alongside
|
|
488
|
-
// user -- so they are counted alike.
|
|
489
|
-
//
|
|
490
|
-
//
|
|
494
|
+
// user -- so they are counted alike. Content that is neither (a malformed
|
|
495
|
+
// persisted custom message) is in no request: the coding-agent's
|
|
496
|
+
// `convertToLlm` drops it, and it counts 0.
|
|
491
497
|
const content = message.content;
|
|
492
498
|
if (typeof content === "string") {
|
|
493
499
|
fragments.push(content);
|
|
@@ -496,7 +502,7 @@ export class Tokenizer {
|
|
|
496
502
|
if (block.type === "text" && block.text) {
|
|
497
503
|
fragments.push(block.text);
|
|
498
504
|
} else if (block.type === "image") {
|
|
499
|
-
extra += this
|
|
505
|
+
extra += this.#imageBlockTokens(block);
|
|
500
506
|
}
|
|
501
507
|
}
|
|
502
508
|
}
|
|
@@ -637,8 +643,6 @@ export class Tokenizer {
|
|
|
637
643
|
}
|
|
638
644
|
break;
|
|
639
645
|
}
|
|
640
|
-
case "custom":
|
|
641
|
-
case "hookMessage":
|
|
642
646
|
case "toolResult": {
|
|
643
647
|
if (typeof message.content === "string") {
|
|
644
648
|
fragments.push(message.content);
|
|
@@ -647,7 +651,7 @@ export class Tokenizer {
|
|
|
647
651
|
if (block.type === "text" && block.text) {
|
|
648
652
|
fragments.push(block.text);
|
|
649
653
|
} else if (block.type === "image") {
|
|
650
|
-
extra += this
|
|
654
|
+
extra += this.#imageBlockTokens(block);
|
|
651
655
|
}
|
|
652
656
|
}
|
|
653
657
|
}
|
|
@@ -678,6 +682,52 @@ export class Tokenizer {
|
|
|
678
682
|
return extra + this.countTokens(fragments);
|
|
679
683
|
}
|
|
680
684
|
|
|
685
|
+
/**
|
|
686
|
+
* Tokens the coding-agent's `convertToLlm` sends for one of its app roles,
|
|
687
|
+
* or `undefined` for a role this package's union names. Declaration
|
|
688
|
+
* merging keeps those roles out of that union, so the discriminant and
|
|
689
|
+
* every field are read as data.
|
|
690
|
+
*
|
|
691
|
+
* - `bashExecution` and `pythonExecution` (`!` and `$`): one user message
|
|
692
|
+
* rendering the command or code and its output, beside a bash run's
|
|
693
|
+
* terminal images. A run excluded from context (`!!` and `$$`) is in no
|
|
694
|
+
* request and costs nothing.
|
|
695
|
+
* - `fileMention` (`@file`): each file's path and content, and each
|
|
696
|
+
* attached image at the rate the user arm charges it.
|
|
697
|
+
*
|
|
698
|
+
* The rendering's fixed framing (the `Ran` lead-in, code fences, `<file>`
|
|
699
|
+
* tags, exit and truncation notices) adds a few tokens per message that
|
|
700
|
+
* this leaves out.
|
|
701
|
+
*/
|
|
702
|
+
#measureAppMessage(message: AgentMessage): number | undefined {
|
|
703
|
+
const role: string = message.role;
|
|
704
|
+
const execution = role === "bashExecution" || role === "pythonExecution";
|
|
705
|
+
if (!execution && role !== "fileMention") return undefined;
|
|
706
|
+
if (execution && "excludeFromContext" in message && message.excludeFromContext) return 0;
|
|
707
|
+
const fragments: string[] = [];
|
|
708
|
+
let extra = 0;
|
|
709
|
+
if (execution) {
|
|
710
|
+
if ("command" in message && typeof message.command === "string") fragments.push(message.command);
|
|
711
|
+
if ("code" in message && typeof message.code === "string") fragments.push(message.code);
|
|
712
|
+
if ("output" in message && typeof message.output === "string") fragments.push(message.output);
|
|
713
|
+
if (role === "bashExecution" && "images" in message && Array.isArray(message.images)) {
|
|
714
|
+
const images: readonly unknown[] = message.images;
|
|
715
|
+
for (const image of images) {
|
|
716
|
+
if (isImageBlock(image)) extra += this.#imageBlockTokens(image);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
} else if ("files" in message && Array.isArray(message.files)) {
|
|
720
|
+
const files: readonly unknown[] = message.files;
|
|
721
|
+
for (const file of files) {
|
|
722
|
+
if (!isRecord(file)) continue;
|
|
723
|
+
if (typeof file.path === "string") fragments.push(file.path);
|
|
724
|
+
if (typeof file.content === "string") fragments.push(file.content);
|
|
725
|
+
if (isImageBlock(file.image)) extra += this.#imageBlockTokens(file.image);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return fragments.length === 0 ? extra : extra + this.countTokens(fragments);
|
|
729
|
+
}
|
|
730
|
+
|
|
681
731
|
/**
|
|
682
732
|
* Input tokens this reader bills for replaying `message`'s native Responses
|
|
683
733
|
* reasoning; `undefined` when the reader re-encodes the turn from its
|