@peer-agent/runtime-core 0.0.1-beta.43

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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/capability-registry.d.ts +15 -0
  4. package/dist/capability-registry.js +88 -0
  5. package/dist/compaction-progress.d.ts +51 -0
  6. package/dist/compaction-progress.js +83 -0
  7. package/dist/context-accounting-lifecycle.d.ts +41 -0
  8. package/dist/context-accounting-lifecycle.js +90 -0
  9. package/dist/context-accounting-pipeline.d.ts +98 -0
  10. package/dist/context-accounting-pipeline.js +561 -0
  11. package/dist/context-compaction.d.ts +70 -0
  12. package/dist/context-compaction.js +192 -0
  13. package/dist/context-projection-lifecycle.d.ts +32 -0
  14. package/dist/context-projection-lifecycle.js +65 -0
  15. package/dist/context-projection.d.ts +74 -0
  16. package/dist/context-projection.js +183 -0
  17. package/dist/contracts.d.ts +218 -0
  18. package/dist/contracts.js +1 -0
  19. package/dist/conversation-history-projector.d.ts +52 -0
  20. package/dist/conversation-history-projector.js +472 -0
  21. package/dist/decision.d.ts +4 -0
  22. package/dist/decision.js +23 -0
  23. package/dist/evidence.d.ts +64 -0
  24. package/dist/evidence.js +127 -0
  25. package/dist/hooks.d.ts +5 -0
  26. package/dist/hooks.js +4 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.js +18 -0
  29. package/dist/local-tool-contracts.d.ts +60 -0
  30. package/dist/local-tool-contracts.js +64 -0
  31. package/dist/microcompact.d.ts +38 -0
  32. package/dist/microcompact.js +354 -0
  33. package/dist/permission.d.ts +18 -0
  34. package/dist/permission.js +50 -0
  35. package/dist/projection-materializers.d.ts +18 -0
  36. package/dist/projection-materializers.js +34 -0
  37. package/dist/projection.d.ts +15 -0
  38. package/dist/projection.js +78 -0
  39. package/dist/runtime-usage-accounting.d.ts +19 -0
  40. package/dist/runtime-usage-accounting.js +79 -0
  41. package/package.json +47 -0
@@ -0,0 +1,192 @@
1
+ export const COMPACTION_SUMMARY_SYSTEM_PROMPT = '你是对话摘要专家。请将以下对话历史压缩为详细摘要,保留关键信息:用户意图、重要决策、技术概念、文件变更、错误修复、待办事项。特别要详细记录用户的具体执行动作与操作步骤——用户要求做了什么、实际改动了哪些文件、命令/操作执行到哪一步、当前停在何处——因为原文已全量压缩、不再保留,连续性完全依赖本摘要承载。输出纯文本,不要用 markdown。';
2
+ export const COMPACTION_SUMMARY_PROMPT = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
3
+ This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
4
+
5
+ Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
6
+
7
+ 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
8
+ - The user's explicit requests and intents
9
+ - Your approach to addressing the user's requests
10
+ - Key decisions, technical concepts and code patterns
11
+ - Specific details like file names, full code snippets, function signatures, file edits, etc
12
+ - Errors that you ran into and how you fixed them
13
+ - Pay special attention to specific user feedback that may have led to a change in your approach.
14
+ 2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
15
+
16
+ Your summary should include the following sections:
17
+
18
+ 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
19
+ 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
20
+ 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Include a summary of why this file read or edit is important.
21
+ 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback.
22
+ 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
23
+ 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding user feedback and changing intent.
24
+ 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
25
+ 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request. CRITICAL — record the user's concrete execution actions and operation steps in detail: what the user asked to do, which files were actually changed, what commands/operations were run and to which step they progressed, and exactly where things currently stand. The original conversation is fully compacted and NOT retained, so continuity depends entirely on this summary capturing those execution details.
26
+ 9. Optional Next Step: List the next step related to the most recent work. Include direct quotes from the most recent conversation.
27
+
28
+ CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.
29
+
30
+ Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;
31
+ export function formatCompactionMessagesForSummary(messages) {
32
+ return messages
33
+ .map((message) => {
34
+ const content = typeof message.content === 'string'
35
+ ? message.content
36
+ : JSON.stringify(message.content);
37
+ return `[${message.role}]: ${content}`;
38
+ })
39
+ .join('\n\n');
40
+ }
41
+ function contentBlocks(message) {
42
+ return Array.isArray(message.content)
43
+ ? message.content.filter((block) => Boolean(block && typeof block === 'object'))
44
+ : [];
45
+ }
46
+ function toolUseIds(message) {
47
+ const openAiCalls = [...(message.toolCalls ?? []), ...(message.tool_calls ?? [])]
48
+ .map((call) => call?.id)
49
+ .filter((id) => typeof id === 'string' && id.length > 0);
50
+ const anthropicCalls = contentBlocks(message)
51
+ .filter((block) => block.type === 'tool_use')
52
+ .map((block) => block.id)
53
+ .filter((id) => typeof id === 'string' && id.length > 0);
54
+ return [...openAiCalls, ...anthropicCalls];
55
+ }
56
+ function toolResultIds(message) {
57
+ const direct = message.toolCallId ?? message.tool_call_id;
58
+ const blockIds = contentBlocks(message)
59
+ .filter((block) => block.type === 'tool_result')
60
+ .map((block) => block.tool_use_id)
61
+ .filter((id) => typeof id === 'string' && id.length > 0);
62
+ return typeof direct === 'string' && direct.length > 0 ? [direct, ...blockIds] : blockIds;
63
+ }
64
+ function hasToolResult(message) {
65
+ return message.role === 'tool' || toolResultIds(message).length > 0;
66
+ }
67
+ function isHumanUserMessage(message) {
68
+ if (message.role !== 'user' || message._compaction)
69
+ return false;
70
+ const blocks = contentBlocks(message);
71
+ return blocks.length === 0 || blocks.some((block) => block.type !== 'tool_result');
72
+ }
73
+ function findCurrentTurnStart(messages) {
74
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
75
+ if (isHumanUserMessage(messages[index]))
76
+ return index;
77
+ }
78
+ return -1;
79
+ }
80
+ function findUnclosedToolTailStart(messages) {
81
+ const pending = new Map();
82
+ messages.forEach((message, index) => {
83
+ for (const id of toolUseIds(message))
84
+ pending.set(id, index);
85
+ for (const id of toolResultIds(message))
86
+ pending.delete(id);
87
+ });
88
+ return pending.size === 0 ? messages.length : Math.min(...pending.values());
89
+ }
90
+ function expandKeepForToolContinuity(keepMessages, oldMessages) {
91
+ const keep = [...keepMessages];
92
+ const old = [...oldMessages];
93
+ while (keep.length > 0 && hasToolResult(keep[0]) && old.length > 0) {
94
+ const previous = old.pop();
95
+ keep.unshift(previous);
96
+ if (toolUseIds(previous).length > 0)
97
+ break;
98
+ }
99
+ return { keepMessages: keep, oldMessages: old };
100
+ }
101
+ /**
102
+ * Host-neutral form of Desktop's compaction split rules. System messages are kept
103
+ * separately; automatic preflight preserves the newest human turn; and a split
104
+ * never leaves an orphan tool result or an unfinished tool call in summarized history.
105
+ */
106
+ export function splitMessagesForCompaction(messages, options = {}) {
107
+ const systemMessages = messages.filter((message) => message.role === 'system');
108
+ const conversation = messages.filter((message) => message.role !== 'system');
109
+ const currentTurnStart = options.preserveLatestUserTurn ? findCurrentTurnStart(conversation) : -1;
110
+ let keepMessages;
111
+ let oldMessages;
112
+ if (currentTurnStart >= 0) {
113
+ const currentTail = conversation.slice(currentTurnStart + 1);
114
+ const unclosedTailStart = findUnclosedToolTailStart(currentTail);
115
+ keepMessages = [conversation[currentTurnStart], ...currentTail.slice(unclosedTailStart)];
116
+ oldMessages = [...conversation.slice(0, currentTurnStart), ...currentTail.slice(0, unclosedTailStart)];
117
+ }
118
+ else {
119
+ const requested = Math.max(0, Math.floor(options.keepRecentCount ?? 0));
120
+ const keepCount = Math.min(requested, conversation.length);
121
+ keepMessages = keepCount > 0 ? conversation.slice(-keepCount) : [];
122
+ oldMessages = keepCount > 0 ? conversation.slice(0, -keepCount) : [...conversation];
123
+ }
124
+ const safe = expandKeepForToolContinuity(keepMessages, oldMessages);
125
+ return { systemMessages, ...safe };
126
+ }
127
+ /** Desktop's summary preference order, expressed behind a host-provided model port. */
128
+ export async function runCompactionSummaryCascade(options) {
129
+ let fallbackReason = options.summarizeWithLlm
130
+ ? 'llm_failed'
131
+ : 'llm_unavailable';
132
+ let fallbackDetail;
133
+ if (options.summarizeWithLlm) {
134
+ try {
135
+ const summary = (await options.summarizeWithLlm(options.oldMessages))?.trim();
136
+ if (summary)
137
+ return { method: 'llm', summary };
138
+ fallbackDetail = 'LLM summarizer returned an empty summary.';
139
+ }
140
+ catch (error) {
141
+ fallbackDetail = error instanceof Error ? error.message : String(error);
142
+ }
143
+ }
144
+ const structured = options.summarizeStructurally(options.oldMessages)?.trim();
145
+ if (structured) {
146
+ return { method: 'structured', summary: structured, fallbackReason, fallbackDetail };
147
+ }
148
+ fallbackReason = 'structured_empty';
149
+ return {
150
+ method: 'fallback_drop',
151
+ summary: options.fallbackSummary?.trim() || 'Earlier conversation was removed because no safe summary could be produced.',
152
+ fallbackReason,
153
+ fallbackDetail,
154
+ };
155
+ }
156
+ /**
157
+ * Shared strategy boundary used by both Desktop and CLI/TUI. Hosts provide the
158
+ * LLM/structural summarizers and handoff formatting, while split safety and
159
+ * fallback ordering remain owned by runtime-core.
160
+ */
161
+ export async function compactMessagesWithSummaryStrategy(options) {
162
+ const split = splitMessagesForCompaction(options.messages, {
163
+ preserveLatestUserTurn: options.preserveLatestUserTurn,
164
+ keepRecentCount: options.keepRecentCount,
165
+ });
166
+ if (split.oldMessages.length === 0) {
167
+ return {
168
+ compacted: false,
169
+ systemMessages: split.systemMessages,
170
+ keepMessages: split.keepMessages,
171
+ oldMessages: split.oldMessages,
172
+ };
173
+ }
174
+ const cascade = await runCompactionSummaryCascade({
175
+ oldMessages: split.oldMessages,
176
+ summarizeWithLlm: options.summarizeWithLlm,
177
+ summarizeStructurally: options.summarizeStructurally,
178
+ fallbackSummary: options.fallbackSummary,
179
+ });
180
+ const summary = cascade.summary.trim();
181
+ return {
182
+ compacted: true,
183
+ systemMessages: split.systemMessages,
184
+ keepMessages: split.keepMessages,
185
+ oldMessages: split.oldMessages,
186
+ summary,
187
+ handoffContent: options.buildHandoffContent(summary, split.oldMessages.length),
188
+ method: cascade.method,
189
+ fallbackReason: cascade.fallbackReason,
190
+ fallbackDetail: cascade.fallbackDetail,
191
+ };
192
+ }
@@ -0,0 +1,32 @@
1
+ import { projectContext, type ContextProjection } from './context-projection.ts';
2
+ type ProjectionMessage = Parameters<typeof projectContext>[0]['messages'];
3
+ type ProjectionTools = Parameters<typeof projectContext>[0]['tools'];
4
+ export type ContextProjectionLifecycleSnapshot = Readonly<{
5
+ revision: number;
6
+ projection: ContextProjection;
7
+ }>;
8
+ export type ContextProjectionLifecycleInput = Readonly<{
9
+ messages?: ProjectionMessage;
10
+ tools?: ProjectionTools;
11
+ contextWindow?: number | null;
12
+ currentInputTokens?: number | null;
13
+ reason?: string;
14
+ now?: number;
15
+ }>;
16
+ export type ContextProjectionLifecycle = Readonly<{
17
+ requestPreflight(input: ContextProjectionLifecycleInput): ContextProjectionLifecycleSnapshot;
18
+ streamPreview(delta: string, input?: Omit<ContextProjectionLifecycleInput, 'messages'>): ContextProjectionLifecycleSnapshot;
19
+ toolResult(input: ContextProjectionLifecycleInput): ContextProjectionLifecycleSnapshot;
20
+ postCompaction(input: ContextProjectionLifecycleInput): ContextProjectionLifecycleSnapshot;
21
+ turnComplete(input: ContextProjectionLifecycleInput): ContextProjectionLifecycleSnapshot;
22
+ restored(input: ContextProjectionLifecycleInput): ContextProjectionLifecycleSnapshot;
23
+ current(): ContextProjectionLifecycleSnapshot | null;
24
+ }>;
25
+ /**
26
+ * Owns the ordering and transient state for one Runtime turn's context projection.
27
+ * Hosts provide their actual request messages/tools at stable boundaries. During a
28
+ * provider stream only the assistant delta is provisional; it is replaced by the
29
+ * next stable boundary rather than being added to an already persisted message.
30
+ */
31
+ export declare function createContextProjectionLifecycle(onProjection?: (snapshot: ContextProjectionLifecycleSnapshot) => void): ContextProjectionLifecycle;
32
+ export {};
@@ -0,0 +1,65 @@
1
+ import { estimateContextTextTokens, projectContext, } from "./context-projection.js";
2
+ /**
3
+ * Owns the ordering and transient state for one Runtime turn's context projection.
4
+ * Hosts provide their actual request messages/tools at stable boundaries. During a
5
+ * provider stream only the assistant delta is provisional; it is replaced by the
6
+ * next stable boundary rather than being added to an already persisted message.
7
+ */
8
+ export function createContextProjectionLifecycle(onProjection) {
9
+ let revision = 0;
10
+ let lastSnapshot = null;
11
+ let stableInput = {};
12
+ let streamedAssistantText = '';
13
+ const publish = (phase, input, previewInputTokens) => {
14
+ stableInput = { ...stableInput, ...input };
15
+ const projection = projectContext({
16
+ messages: stableInput.messages,
17
+ tools: stableInput.tools,
18
+ contextWindow: stableInput.contextWindow,
19
+ currentInputTokens: input.currentInputTokens ?? stableInput.currentInputTokens,
20
+ previewInputTokens,
21
+ phase,
22
+ quality: phase === 'stream_preview'
23
+ ? 'preview'
24
+ : (input.currentInputTokens ?? stableInput.currentInputTokens) != null
25
+ ? 'exact'
26
+ : 'projected',
27
+ reason: input.reason ?? phase,
28
+ now: input.now,
29
+ });
30
+ const snapshot = Object.freeze({ revision: ++revision, projection });
31
+ lastSnapshot = snapshot;
32
+ onProjection?.(snapshot);
33
+ return snapshot;
34
+ };
35
+ const stableBoundary = (phase, input) => {
36
+ streamedAssistantText = '';
37
+ return publish(phase, input);
38
+ };
39
+ return Object.freeze({
40
+ requestPreflight(input) {
41
+ return stableBoundary('request_preflight', input);
42
+ },
43
+ streamPreview(delta, input = {}) {
44
+ streamedAssistantText += typeof delta === 'string' ? delta : '';
45
+ const base = lastSnapshot?.projection.nextRequestInputTokens ?? 0;
46
+ const previewInputTokens = base + estimateContextTextTokens(streamedAssistantText);
47
+ return publish('stream_preview', input, previewInputTokens);
48
+ },
49
+ toolResult(input) {
50
+ return stableBoundary('tool_result', input);
51
+ },
52
+ postCompaction(input) {
53
+ return stableBoundary('post_compaction', input);
54
+ },
55
+ turnComplete(input) {
56
+ return stableBoundary('turn_complete', input);
57
+ },
58
+ restored(input) {
59
+ return stableBoundary('restored', input);
60
+ },
61
+ current() {
62
+ return lastSnapshot;
63
+ },
64
+ });
65
+ }
@@ -0,0 +1,74 @@
1
+ export declare const CONTEXT_PROJECTION_CONFIG: Readonly<{
2
+ triggerRatio: 0.8;
3
+ hardRatio: 0.92;
4
+ charsPerToken: 4;
5
+ cjkCharsPerToken: 1.7;
6
+ imageTokens: 2000;
7
+ messageFramingTokens: 4;
8
+ toolCallBlockOverhead: 8;
9
+ toolDefinitionOverhead: 16;
10
+ }>;
11
+ export type ContextProjectionPhase = 'request_preflight' | 'stream_preview' | 'tool_result' | 'post_compaction' | 'turn_complete' | 'restored';
12
+ export type ContextProjectionQuality = 'exact' | 'projected' | 'preview' | 'unknown';
13
+ export type ContextPressure = 'unknown' | 'ok' | 'soft' | 'hard' | 'overflow';
14
+ export type CompactionDecisionReason = 'unknown_window' | 'below_threshold' | 'soft_limit' | 'hard_limit' | 'context_overflow' | 'insufficient_summary_headroom';
15
+ export interface ContextProjection {
16
+ version: 1;
17
+ phase: ContextProjectionPhase;
18
+ quality: ContextProjectionQuality;
19
+ reason: string;
20
+ currentInputTokens: number | null;
21
+ nextRequestInputTokens: number | null;
22
+ previewInputTokens: number | null;
23
+ compactionPressureTokens: number | null;
24
+ contextWindow: number | null;
25
+ percent: number | null;
26
+ pressure: ContextPressure;
27
+ updatedAt: number;
28
+ }
29
+ export interface CompactionDecision {
30
+ shouldCompact: boolean;
31
+ force: boolean;
32
+ pressure: ContextPressure;
33
+ reason: CompactionDecisionReason;
34
+ triggerRatio: number;
35
+ hardRatio: number;
36
+ softLimit: number | null;
37
+ hardLimit: number | null;
38
+ }
39
+ type MessageLike = Readonly<{
40
+ role?: string;
41
+ content?: unknown;
42
+ toolCalls?: readonly unknown[];
43
+ tool_calls?: readonly unknown[];
44
+ }>;
45
+ type ToolLike = Readonly<Record<string, unknown>>;
46
+ export declare function estimateContextTextTokens(text: unknown): number;
47
+ export declare function estimateContextMessagesTokens(messages: readonly MessageLike[] | null | undefined): number;
48
+ export declare function estimateContextToolsTokens(tools: readonly ToolLike[] | ToolLike | null | undefined): number;
49
+ /**
50
+ * Host-neutral prompt-too-long classification shared by Desktop provider loops
51
+ * and CLI/TUI emergency recovery. Providers surface this failure in many shapes;
52
+ * classification must stay single-sourced so both hosts retry under the same policy.
53
+ */
54
+ export declare function isPromptTooLongError(status: number | null | undefined, text: string | null | undefined): boolean;
55
+ export declare function decideContextCompaction(options: {
56
+ pressureTokens: number | null | undefined;
57
+ contextWindow: number | null | undefined;
58
+ triggerRatio?: number;
59
+ hardRatio?: number;
60
+ summaryReserveTokens?: number;
61
+ }): CompactionDecision;
62
+ export declare function projectContext(options: {
63
+ messages?: readonly MessageLike[] | null;
64
+ tools?: readonly ToolLike[] | ToolLike | null;
65
+ draftTokens?: number | null;
66
+ currentInputTokens?: number | null;
67
+ previewInputTokens?: number | null;
68
+ contextWindow?: number | null;
69
+ phase: ContextProjectionPhase;
70
+ quality?: ContextProjectionQuality;
71
+ reason?: string;
72
+ now?: number;
73
+ }): ContextProjection;
74
+ export {};
@@ -0,0 +1,183 @@
1
+ export const CONTEXT_PROJECTION_CONFIG = Object.freeze({
2
+ triggerRatio: 0.8,
3
+ hardRatio: 0.92,
4
+ charsPerToken: 4,
5
+ cjkCharsPerToken: 1.7,
6
+ imageTokens: 2_000,
7
+ messageFramingTokens: 4,
8
+ toolCallBlockOverhead: 8,
9
+ toolDefinitionOverhead: 16,
10
+ });
11
+ const CJK_REGEX = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef\uac00-\ud7af]/g;
12
+ function finitePositive(value) {
13
+ return Number.isFinite(value) && Number(value) > 0 ? Math.floor(Number(value)) : null;
14
+ }
15
+ export function estimateContextTextTokens(text) {
16
+ if (text == null || text === '')
17
+ return 0;
18
+ const value = typeof text === 'string' ? text : String(text);
19
+ const cjkCount = value.match(CJK_REGEX)?.length ?? 0;
20
+ return cjkCount / CONTEXT_PROJECTION_CONFIG.cjkCharsPerToken
21
+ + (value.length - cjkCount) / CONTEXT_PROJECTION_CONFIG.charsPerToken;
22
+ }
23
+ function estimateJson(value) {
24
+ try {
25
+ return estimateContextTextTokens(typeof value === 'string' ? value : JSON.stringify(value));
26
+ }
27
+ catch {
28
+ return 0;
29
+ }
30
+ }
31
+ export function estimateContextMessagesTokens(messages) {
32
+ let tokens = 0;
33
+ for (const message of messages ?? []) {
34
+ const content = message?.content;
35
+ if (typeof content === 'string') {
36
+ tokens += estimateContextTextTokens(content);
37
+ }
38
+ else if (Array.isArray(content)) {
39
+ for (const rawPart of content) {
40
+ if (!rawPart || typeof rawPart !== 'object')
41
+ continue;
42
+ const part = rawPart;
43
+ const type = String(part.type ?? '');
44
+ if (type === 'text' || type === 'input_text' || type === 'output_text') {
45
+ tokens += estimateContextTextTokens(part.text);
46
+ }
47
+ else if (type === 'tool_use' || type === 'tool_call' || type === 'functionCall' || type === 'function_call') {
48
+ tokens += CONTEXT_PROJECTION_CONFIG.toolCallBlockOverhead;
49
+ tokens += estimateContextTextTokens(part.name) + estimateContextTextTokens(part.id);
50
+ tokens += estimateJson(part.input ?? part.arguments);
51
+ }
52
+ else if (type === 'tool_result' || type === 'functionResponse' || type === 'function_response') {
53
+ tokens += CONTEXT_PROJECTION_CONFIG.toolCallBlockOverhead;
54
+ tokens += estimateContextTextTokens(part.tool_use_id ?? part.id ?? part.name);
55
+ tokens += estimateJson(part.content ?? part.response);
56
+ }
57
+ else if (type === 'image'
58
+ || type === 'image_url'
59
+ || type === 'input_image'
60
+ || type === 'document'
61
+ || type === 'file'
62
+ || type === 'input_file') {
63
+ // 二进制/媒体块一律 flat 计:绝不能落到 estimateJson 把 base64 当文本展开。
64
+ tokens += CONTEXT_PROJECTION_CONFIG.imageTokens;
65
+ }
66
+ else {
67
+ tokens += estimateJson(part);
68
+ }
69
+ }
70
+ }
71
+ else if (content != null) {
72
+ tokens += estimateJson(content);
73
+ }
74
+ const topLevelToolCalls = message.toolCalls ?? message.tool_calls;
75
+ for (const rawCall of topLevelToolCalls ?? []) {
76
+ if (!rawCall || typeof rawCall !== 'object')
77
+ continue;
78
+ const call = rawCall;
79
+ const fn = call.function && typeof call.function === 'object'
80
+ ? call.function
81
+ : call;
82
+ tokens += CONTEXT_PROJECTION_CONFIG.toolCallBlockOverhead;
83
+ tokens += estimateContextTextTokens(call.id);
84
+ tokens += estimateContextTextTokens(fn.name);
85
+ tokens += estimateJson(fn.arguments ?? fn.input ?? call.arguments ?? call.input);
86
+ }
87
+ tokens += CONTEXT_PROJECTION_CONFIG.messageFramingTokens;
88
+ }
89
+ return Math.ceil(tokens);
90
+ }
91
+ export function estimateContextToolsTokens(tools) {
92
+ if (!tools)
93
+ return 0;
94
+ const source = Array.isArray(tools)
95
+ ? tools
96
+ : Array.isArray(tools.functionDeclarations)
97
+ ? tools.functionDeclarations
98
+ : [tools];
99
+ let tokens = 0;
100
+ for (const tool of source) {
101
+ if (Array.isArray(tool?.functionDeclarations)) {
102
+ tokens += estimateContextToolsTokens(tool.functionDeclarations);
103
+ continue;
104
+ }
105
+ const fn = tool?.function && typeof tool.function === 'object'
106
+ ? tool.function
107
+ : tool;
108
+ tokens += estimateContextTextTokens(fn?.name ?? tool?.name);
109
+ tokens += estimateContextTextTokens(fn?.description ?? tool?.description);
110
+ tokens += estimateJson(fn?.parameters ?? fn?.input_schema ?? tool?.parameters ?? tool?.input_schema ?? tool?.inputSchema ?? {});
111
+ tokens += CONTEXT_PROJECTION_CONFIG.toolDefinitionOverhead;
112
+ }
113
+ return Math.ceil(tokens);
114
+ }
115
+ /**
116
+ * Host-neutral prompt-too-long classification shared by Desktop provider loops
117
+ * and CLI/TUI emergency recovery. Providers surface this failure in many shapes;
118
+ * classification must stay single-sourced so both hosts retry under the same policy.
119
+ */
120
+ export function isPromptTooLongError(status, text) {
121
+ if (status === 413)
122
+ return true;
123
+ const value = String(text ?? '').toLowerCase();
124
+ return (value.includes('prompt_too_long')
125
+ || value.includes('context_length_exceeded')
126
+ || value.includes('maximum context length')
127
+ || value.includes('maximum prompt length')
128
+ || value.includes('context window')
129
+ || value.includes('context too long')
130
+ || value.includes('input is too long')
131
+ || value.includes('exceeds model context')
132
+ || value.includes('too many tokens')
133
+ || value.includes('token limit'));
134
+ }
135
+ export function decideContextCompaction(options) {
136
+ const contextWindow = finitePositive(options.contextWindow);
137
+ const pressureTokens = finitePositive(options.pressureTokens) ?? 0;
138
+ const triggerRatio = options.triggerRatio ?? CONTEXT_PROJECTION_CONFIG.triggerRatio;
139
+ const hardRatio = Math.max(triggerRatio, options.hardRatio ?? CONTEXT_PROJECTION_CONFIG.hardRatio);
140
+ if (contextWindow == null) {
141
+ return { shouldCompact: false, force: false, pressure: 'unknown', reason: 'unknown_window', triggerRatio, hardRatio, softLimit: null, hardLimit: null };
142
+ }
143
+ const softLimit = Math.floor(contextWindow * triggerRatio);
144
+ const hardLimit = Math.floor(contextWindow * hardRatio);
145
+ const reserveLimit = Math.max(1, contextWindow - Math.max(0, options.summaryReserveTokens ?? 0));
146
+ if (pressureTokens > contextWindow)
147
+ return { shouldCompact: true, force: true, pressure: 'overflow', reason: 'context_overflow', triggerRatio, hardRatio, softLimit, hardLimit };
148
+ if (pressureTokens >= hardLimit)
149
+ return { shouldCompact: true, force: true, pressure: 'hard', reason: 'hard_limit', triggerRatio, hardRatio, softLimit, hardLimit };
150
+ if (pressureTokens >= reserveLimit)
151
+ return { shouldCompact: true, force: false, pressure: 'soft', reason: 'insufficient_summary_headroom', triggerRatio, hardRatio, softLimit, hardLimit };
152
+ if (pressureTokens >= softLimit)
153
+ return { shouldCompact: true, force: false, pressure: 'soft', reason: 'soft_limit', triggerRatio, hardRatio, softLimit, hardLimit };
154
+ return { shouldCompact: false, force: false, pressure: 'ok', reason: 'below_threshold', triggerRatio, hardRatio, softLimit, hardLimit };
155
+ }
156
+ export function projectContext(options) {
157
+ const contextWindow = finitePositive(options.contextWindow);
158
+ const projectedInputTokens = estimateContextMessagesTokens(options.messages)
159
+ + estimateContextToolsTokens(options.tools)
160
+ + (finitePositive(options.draftTokens) ?? 0);
161
+ const currentInputTokens = finitePositive(options.currentInputTokens);
162
+ // Provider-observed usage is authoritative. The local projection remains a
163
+ // diagnostic fallback only until an observation exists.
164
+ const nextRequestInputTokens = currentInputTokens ?? projectedInputTokens;
165
+ const previewInputTokens = finitePositive(options.previewInputTokens);
166
+ const compactionPressureTokens = previewInputTokens ?? nextRequestInputTokens;
167
+ const decision = decideContextCompaction({ pressureTokens: compactionPressureTokens, contextWindow });
168
+ return {
169
+ version: 1,
170
+ phase: options.phase,
171
+ quality: options.quality
172
+ ?? (options.phase === 'stream_preview' ? 'preview' : currentInputTokens ? 'exact' : 'projected'),
173
+ reason: options.reason ?? decision.reason,
174
+ currentInputTokens,
175
+ nextRequestInputTokens,
176
+ previewInputTokens,
177
+ compactionPressureTokens,
178
+ contextWindow,
179
+ percent: contextWindow == null ? null : Math.min(100, Math.round((compactionPressureTokens / contextWindow) * 100)),
180
+ pressure: decision.pressure,
181
+ updatedAt: options.now ?? Date.now(),
182
+ };
183
+ }