@dexto/core 1.16.3 → 1.16.5
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/dist/context/manager.cjs +84 -60
- package/dist/context/manager.d.ts +38 -3
- package/dist/context/manager.d.ts.map +1 -1
- package/dist/context/manager.js +84 -60
- package/dist/llm/executor/stream-processor.cjs +7 -0
- package/dist/llm/executor/stream-processor.d.ts +1 -0
- package/dist/llm/executor/stream-processor.d.ts.map +1 -1
- package/dist/llm/executor/stream-processor.js +7 -0
- package/dist/llm/executor/turn-executor.cjs +34 -23
- package/dist/llm/executor/turn-executor.d.ts +2 -1
- package/dist/llm/executor/turn-executor.d.ts.map +1 -1
- package/dist/llm/executor/turn-executor.js +34 -23
- package/dist/storage/conversation/database.cjs +4 -0
- package/dist/storage/conversation/database.d.ts +3 -0
- package/dist/storage/conversation/database.d.ts.map +1 -1
- package/dist/storage/conversation/database.js +4 -0
- package/dist/storage/conversation/types.d.ts +8 -0
- package/dist/storage/conversation/types.d.ts.map +1 -1
- package/dist/storage/stores/in-memory.cjs +3 -0
- package/dist/storage/stores/in-memory.d.ts.map +1 -1
- package/dist/storage/stores/in-memory.js +3 -0
- package/dist/test-utils/model-history-count-cases.cjs +88 -0
- package/dist/test-utils/model-history-count-cases.js +64 -0
- package/package.json +2 -2
package/dist/context/manager.cjs
CHANGED
|
@@ -108,6 +108,15 @@ class ContextManager {
|
|
|
108
108
|
*/
|
|
109
109
|
lastCallMessageCount = null;
|
|
110
110
|
conversationStore;
|
|
111
|
+
/**
|
|
112
|
+
* The assistant message of the reply being streamed. Each streamed delta, tool call and the
|
|
113
|
+
* final usage update changes it, so it is held here and written through instead of being
|
|
114
|
+
* found in the whole stored history every time. Stores copy a message when they save it.
|
|
115
|
+
* It lives for one model step: any other write through this manager, a failed write, and the
|
|
116
|
+
* end of the step (`releaseAssistantMessage`) drop it, so a write by anyone else between
|
|
117
|
+
* steps is read again, never overwritten by this copy.
|
|
118
|
+
*/
|
|
119
|
+
inFlightAssistant = null;
|
|
111
120
|
sessionId;
|
|
112
121
|
/**
|
|
113
122
|
* ResourceManager for resolving blob references in message content.
|
|
@@ -341,10 +350,7 @@ class ContextManager {
|
|
|
341
350
|
* This marks the boundary for "new messages" calculation.
|
|
342
351
|
*/
|
|
343
352
|
async recordLastCallMessageCount() {
|
|
344
|
-
|
|
345
|
-
sessionId: this.sessionId
|
|
346
|
-
});
|
|
347
|
-
this.lastCallMessageCount = history.messages.length;
|
|
353
|
+
this.lastCallMessageCount = await this.countModelMessages();
|
|
348
354
|
this.logger.debug(`Recorded lastCallMessageCount: ${this.lastCallMessageCount}`);
|
|
349
355
|
}
|
|
350
356
|
/**
|
|
@@ -389,20 +395,38 @@ class ContextManager {
|
|
|
389
395
|
* method instead of prepareHistory().
|
|
390
396
|
*/
|
|
391
397
|
async prepareModelHistory() {
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
398
|
+
return this.prepareLoadedModelHistory(await this.loadModelHistory());
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Prepares a model history the caller already loaded with loadModelHistory(), so one step can
|
|
402
|
+
* load once and prepare from the same load. The caller reloads after anything that changes
|
|
403
|
+
* stored messages.
|
|
404
|
+
*/
|
|
405
|
+
prepareLoadedModelHistory(modelHistory) {
|
|
395
406
|
return this.prepareVisibleHistory({
|
|
396
407
|
history: modelHistory.messages,
|
|
397
408
|
originalCount: modelHistory.stats.returnedMessages + modelHistory.stats.skippedPreSummaryMessages,
|
|
398
409
|
source: "prepareModelHistory"
|
|
399
410
|
});
|
|
400
411
|
}
|
|
412
|
+
/** Loads the stored messages the model sees: everything from the latest summary on. */
|
|
413
|
+
async loadModelHistory() {
|
|
414
|
+
return this.conversationStore.loadModelHistory({ sessionId: this.sessionId });
|
|
415
|
+
}
|
|
416
|
+
/** @deprecated Use loadModelHistory() */
|
|
401
417
|
async getModelHistory() {
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
418
|
+
return (await this.loadModelHistory()).messages;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Number of stored messages the model sees. Reads a count when the store has one; otherwise
|
|
422
|
+
* derives it from a full load. Use it instead of loading history only to take its length.
|
|
423
|
+
*/
|
|
424
|
+
async countModelMessages() {
|
|
425
|
+
const input = { sessionId: this.sessionId };
|
|
426
|
+
if (this.conversationStore.countModelMessages) {
|
|
427
|
+
return this.conversationStore.countModelMessages(input);
|
|
428
|
+
}
|
|
429
|
+
return (await this.conversationStore.loadModelHistory(input)).messages.length;
|
|
406
430
|
}
|
|
407
431
|
prepareVisibleHistory(input) {
|
|
408
432
|
const visibleToolCallIds = /* @__PURE__ */ new Set();
|
|
@@ -507,22 +531,43 @@ ${prompt}`);
|
|
|
507
531
|
this.logger.debug(`Context cleared for session: ${this.sessionId}`);
|
|
508
532
|
}
|
|
509
533
|
/**
|
|
510
|
-
*
|
|
511
|
-
*
|
|
534
|
+
* Finds the assistant message of the reply being streamed. The one this manager started is
|
|
535
|
+
* held in memory; any other id is found with one read of the history and held from then on.
|
|
512
536
|
*/
|
|
513
|
-
async
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
if (messageIndex === -1) {
|
|
517
|
-
throw import_errors.ContextError.messageNotFound(messageId);
|
|
537
|
+
async loadAssistantMessage(messageId) {
|
|
538
|
+
if (this.inFlightAssistant?.id === messageId) {
|
|
539
|
+
return this.inFlightAssistant;
|
|
518
540
|
}
|
|
519
|
-
const
|
|
541
|
+
const history = await this.conversationStore.listMessages({ sessionId: this.sessionId });
|
|
542
|
+
const message = history.find((m) => m.id === messageId);
|
|
520
543
|
if (!message) {
|
|
521
544
|
throw import_errors.ContextError.messageNotFound(messageId);
|
|
522
545
|
}
|
|
523
|
-
if (
|
|
546
|
+
if (!(0, import_types.isAssistantMessage)(message)) {
|
|
524
547
|
throw import_errors.ContextError.messageNotAssistant(messageId);
|
|
525
548
|
}
|
|
549
|
+
this.inFlightAssistant = message;
|
|
550
|
+
return message;
|
|
551
|
+
}
|
|
552
|
+
/** Ends the streamed reply: the next change to its message reads it from the store again. */
|
|
553
|
+
releaseAssistantMessage() {
|
|
554
|
+
this.inFlightAssistant = null;
|
|
555
|
+
}
|
|
556
|
+
/** Writes the held assistant message through. A failed write drops it, so a retry rereads. */
|
|
557
|
+
async writeAssistantMessage(message) {
|
|
558
|
+
try {
|
|
559
|
+
await this.conversationStore.updateMessage({ sessionId: this.sessionId, message });
|
|
560
|
+
} catch (error) {
|
|
561
|
+
this.inFlightAssistant = null;
|
|
562
|
+
throw error;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Appends text to an existing assistant message.
|
|
567
|
+
* Used for streaming responses.
|
|
568
|
+
*/
|
|
569
|
+
async appendAssistantText(messageId, text) {
|
|
570
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
526
571
|
if (message.content === null) {
|
|
527
572
|
message.content = [{ type: "text", text }];
|
|
528
573
|
} else if (Array.isArray(message.content)) {
|
|
@@ -533,50 +578,28 @@ ${prompt}`);
|
|
|
533
578
|
message.content.push({ type: "text", text });
|
|
534
579
|
}
|
|
535
580
|
}
|
|
536
|
-
await this.
|
|
581
|
+
await this.writeAssistantMessage(message);
|
|
537
582
|
}
|
|
538
583
|
/**
|
|
539
584
|
* Adds a tool call to an existing assistant message.
|
|
540
585
|
* Used for streaming responses.
|
|
541
586
|
*/
|
|
542
587
|
async addToolCall(messageId, toolCall) {
|
|
543
|
-
const
|
|
544
|
-
const messageIndex = history.findIndex((m) => m.id === messageId);
|
|
545
|
-
if (messageIndex === -1) {
|
|
546
|
-
throw import_errors.ContextError.messageNotFound(messageId);
|
|
547
|
-
}
|
|
548
|
-
const message = history[messageIndex];
|
|
549
|
-
if (!message) {
|
|
550
|
-
throw import_errors.ContextError.messageNotFound(messageId);
|
|
551
|
-
}
|
|
552
|
-
if (message.role !== "assistant") {
|
|
553
|
-
throw import_errors.ContextError.messageNotAssistant(messageId);
|
|
554
|
-
}
|
|
588
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
555
589
|
if (!message.toolCalls) {
|
|
556
590
|
message.toolCalls = [];
|
|
557
591
|
}
|
|
558
592
|
message.toolCalls.push(toolCall);
|
|
559
|
-
await this.
|
|
593
|
+
await this.writeAssistantMessage(message);
|
|
560
594
|
}
|
|
561
595
|
/**
|
|
562
596
|
* Updates an existing assistant message with new properties.
|
|
563
597
|
* Used for finalizing streaming responses (e.g. adding token usage).
|
|
564
598
|
*/
|
|
565
599
|
async updateAssistantMessage(messageId, updates) {
|
|
566
|
-
const
|
|
567
|
-
const messageIndex = history.findIndex((m) => m.id === messageId);
|
|
568
|
-
if (messageIndex === -1) {
|
|
569
|
-
throw import_errors.ContextError.messageNotFound(messageId);
|
|
570
|
-
}
|
|
571
|
-
const message = history[messageIndex];
|
|
572
|
-
if (!message) {
|
|
573
|
-
throw import_errors.ContextError.messageNotFound(messageId);
|
|
574
|
-
}
|
|
575
|
-
if (message.role !== "assistant") {
|
|
576
|
-
throw import_errors.ContextError.messageNotAssistant(messageId);
|
|
577
|
-
}
|
|
600
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
578
601
|
Object.assign(message, updates);
|
|
579
|
-
await this.
|
|
602
|
+
await this.writeAssistantMessage(message);
|
|
580
603
|
}
|
|
581
604
|
/**
|
|
582
605
|
* Marks tool messages as compacted (pruned).
|
|
@@ -594,6 +617,7 @@ ${prompt}`);
|
|
|
594
617
|
if (messageIds.length === 0) {
|
|
595
618
|
return 0;
|
|
596
619
|
}
|
|
620
|
+
this.inFlightAssistant = null;
|
|
597
621
|
const history = await this.conversationStore.listMessages({ sessionId: this.sessionId });
|
|
598
622
|
const timestamp = Date.now();
|
|
599
623
|
let markedCount = 0;
|
|
@@ -677,6 +701,7 @@ ${prompt}`);
|
|
|
677
701
|
this.logger.debug(
|
|
678
702
|
`ContextManager: Adding message to conversation store: ${JSON.stringify(message, null, 2)}`
|
|
679
703
|
);
|
|
704
|
+
this.inFlightAssistant = null;
|
|
680
705
|
await this.conversationStore.saveMessage({ sessionId: this.sessionId, message });
|
|
681
706
|
this.logger.debug("ContextManager: Message saved to conversation store", {
|
|
682
707
|
messageId: message.id,
|
|
@@ -744,6 +769,9 @@ ${prompt}`);
|
|
|
744
769
|
if (message.id === void 0) {
|
|
745
770
|
throw import_errors.ContextError.assistantMessageIdMissing();
|
|
746
771
|
}
|
|
772
|
+
if ((0, import_types.isAssistantMessage)(message)) {
|
|
773
|
+
this.inFlightAssistant = message;
|
|
774
|
+
}
|
|
747
775
|
return message.id;
|
|
748
776
|
}
|
|
749
777
|
/**
|
|
@@ -927,18 +955,13 @@ ${prompt}`);
|
|
|
927
955
|
*
|
|
928
956
|
* @param contributorContext Context for building the system prompt
|
|
929
957
|
* @param tools Tool definitions to include in the estimate
|
|
958
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
930
959
|
* @returns Token estimates with breakdown and comparison to actual (if available)
|
|
931
960
|
*/
|
|
932
|
-
async getContextTokenEstimate(contributorContext, tools) {
|
|
961
|
+
async getContextTokenEstimate(contributorContext, tools, loadedModelHistory) {
|
|
933
962
|
const systemPrompt = await this.getSystemPrompt(contributorContext);
|
|
934
|
-
const modelHistory = await this.
|
|
935
|
-
|
|
936
|
-
});
|
|
937
|
-
const { preparedHistory, stats } = this.prepareVisibleHistory({
|
|
938
|
-
history: modelHistory.messages,
|
|
939
|
-
originalCount: modelHistory.stats.returnedMessages + modelHistory.stats.skippedPreSummaryMessages,
|
|
940
|
-
source: "getContextTokenEstimate"
|
|
941
|
-
});
|
|
963
|
+
const modelHistory = loadedModelHistory ?? await this.loadModelHistory();
|
|
964
|
+
const { preparedHistory, stats } = this.prepareLoadedModelHistory(modelHistory);
|
|
942
965
|
const lastInput = this.lastActualInputTokens;
|
|
943
966
|
const lastOutput = this.lastActualOutputTokens;
|
|
944
967
|
const lastMsgCount = this.lastCallMessageCount;
|
|
@@ -1036,16 +1059,16 @@ ${prompt}`);
|
|
|
1036
1059
|
* @param systemPrompt The system prompt string
|
|
1037
1060
|
* @param preparedHistory Message history AFTER filterCompacted and pruning
|
|
1038
1061
|
* @param tools Tool definitions
|
|
1062
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
1063
|
+
* and the actuals-based formula needs the messages after the last call
|
|
1039
1064
|
* @returns Estimated total input tokens for the next LLM call
|
|
1040
1065
|
*/
|
|
1041
|
-
async getEstimatedNextInputTokens(systemPrompt, preparedHistory, tools) {
|
|
1066
|
+
async getEstimatedNextInputTokens(systemPrompt, preparedHistory, tools, loadedModelHistory) {
|
|
1042
1067
|
const lastInput = this.lastActualInputTokens;
|
|
1043
1068
|
const lastOutput = this.lastActualOutputTokens;
|
|
1044
1069
|
const lastMsgCount = this.lastCallMessageCount;
|
|
1045
1070
|
if (lastInput !== null && lastOutput !== null && lastMsgCount !== null) {
|
|
1046
|
-
const modelHistory = await this.
|
|
1047
|
-
sessionId: this.sessionId
|
|
1048
|
-
});
|
|
1071
|
+
const modelHistory = loadedModelHistory ?? await this.loadModelHistory();
|
|
1049
1072
|
const newMessages = modelHistory.messages.slice(lastMsgCount);
|
|
1050
1073
|
const newMessagesEstimate = (0, import_utils.estimateMessagesTokens)(newMessages);
|
|
1051
1074
|
const total = lastInput + lastOutput + newMessagesEstimate;
|
|
@@ -1073,6 +1096,7 @@ ${prompt}`);
|
|
|
1073
1096
|
* Does not reset the system prompt
|
|
1074
1097
|
*/
|
|
1075
1098
|
async resetConversation() {
|
|
1099
|
+
this.inFlightAssistant = null;
|
|
1076
1100
|
await this.conversationStore.clearMessages({ sessionId: this.sessionId });
|
|
1077
1101
|
this.resetActualTokenTracking();
|
|
1078
1102
|
this.logger.debug(
|
|
@@ -6,7 +6,7 @@ import type { Logger } from '../logger/v2/types.js';
|
|
|
6
6
|
import type { SanitizedToolResult } from './types.js';
|
|
7
7
|
import { DynamicContributorContext } from '../systemPrompt/types.js';
|
|
8
8
|
import { SystemPromptManager } from '../systemPrompt/manager.js';
|
|
9
|
-
import type { ConversationStore } from '../storage/conversation/types.js';
|
|
9
|
+
import type { ConversationStore, ModelHistoryLoad } from '../storage/conversation/types.js';
|
|
10
10
|
import { ValidatedLLMConfig } from '../llm/schemas.js';
|
|
11
11
|
import type { ToolPresentationSnapshotV1 } from '../tools/types.js';
|
|
12
12
|
import type { ToolCallMetadata } from '../tools/tool-call-metadata.js';
|
|
@@ -73,6 +73,15 @@ export declare class ContextManager<TMessage = unknown> {
|
|
|
73
73
|
*/
|
|
74
74
|
private lastCallMessageCount;
|
|
75
75
|
private conversationStore;
|
|
76
|
+
/**
|
|
77
|
+
* The assistant message of the reply being streamed. Each streamed delta, tool call and the
|
|
78
|
+
* final usage update changes it, so it is held here and written through instead of being
|
|
79
|
+
* found in the whole stored history every time. Stores copy a message when they save it.
|
|
80
|
+
* It lives for one model step: any other write through this manager, a failed write, and the
|
|
81
|
+
* end of the step (`releaseAssistantMessage`) drop it, so a write by anyone else between
|
|
82
|
+
* steps is read again, never overwritten by this copy.
|
|
83
|
+
*/
|
|
84
|
+
private inFlightAssistant;
|
|
76
85
|
private readonly sessionId;
|
|
77
86
|
/**
|
|
78
87
|
* ResourceManager for resolving blob references in message content.
|
|
@@ -169,7 +178,21 @@ export declare class ContextManager<TMessage = unknown> {
|
|
|
169
178
|
* method instead of prepareHistory().
|
|
170
179
|
*/
|
|
171
180
|
prepareModelHistory(): Promise<PreparedHistoryResult>;
|
|
181
|
+
/**
|
|
182
|
+
* Prepares a model history the caller already loaded with loadModelHistory(), so one step can
|
|
183
|
+
* load once and prepare from the same load. The caller reloads after anything that changes
|
|
184
|
+
* stored messages.
|
|
185
|
+
*/
|
|
186
|
+
prepareLoadedModelHistory(modelHistory: ModelHistoryLoad): PreparedHistoryResult;
|
|
187
|
+
/** Loads the stored messages the model sees: everything from the latest summary on. */
|
|
188
|
+
loadModelHistory(): Promise<ModelHistoryLoad>;
|
|
189
|
+
/** @deprecated Use loadModelHistory() */
|
|
172
190
|
getModelHistory(): Promise<Readonly<InternalMessage[]>>;
|
|
191
|
+
/**
|
|
192
|
+
* Number of stored messages the model sees. Reads a count when the store has one; otherwise
|
|
193
|
+
* derives it from a full load. Use it instead of loading history only to take its length.
|
|
194
|
+
*/
|
|
195
|
+
countModelMessages(): Promise<number>;
|
|
173
196
|
private prepareVisibleHistory;
|
|
174
197
|
/**
|
|
175
198
|
* Assembles and returns the current system prompt by invoking the SystemPromptManager.
|
|
@@ -198,6 +221,15 @@ export declare class ContextManager<TMessage = unknown> {
|
|
|
198
221
|
* The full history remains in the database for review via /resume or session history.
|
|
199
222
|
*/
|
|
200
223
|
clearContext(): Promise<void>;
|
|
224
|
+
/**
|
|
225
|
+
* Finds the assistant message of the reply being streamed. The one this manager started is
|
|
226
|
+
* held in memory; any other id is found with one read of the history and held from then on.
|
|
227
|
+
*/
|
|
228
|
+
private loadAssistantMessage;
|
|
229
|
+
/** Ends the streamed reply: the next change to its message reads it from the store again. */
|
|
230
|
+
releaseAssistantMessage(): void;
|
|
231
|
+
/** Writes the held assistant message through. A failed write drops it, so a retry rereads. */
|
|
232
|
+
private writeAssistantMessage;
|
|
201
233
|
/**
|
|
202
234
|
* Appends text to an existing assistant message.
|
|
203
235
|
* Used for streaming responses.
|
|
@@ -324,13 +356,14 @@ export declare class ContextManager<TMessage = unknown> {
|
|
|
324
356
|
*
|
|
325
357
|
* @param contributorContext Context for building the system prompt
|
|
326
358
|
* @param tools Tool definitions to include in the estimate
|
|
359
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
327
360
|
* @returns Token estimates with breakdown and comparison to actual (if available)
|
|
328
361
|
*/
|
|
329
362
|
getContextTokenEstimate(contributorContext: DynamicContributorContext, tools: Record<string, {
|
|
330
363
|
name?: string;
|
|
331
364
|
description?: string;
|
|
332
365
|
parameters?: unknown;
|
|
333
|
-
}
|
|
366
|
+
}>, loadedModelHistory?: ModelHistoryLoad): Promise<{
|
|
334
367
|
/** Total estimated tokens */
|
|
335
368
|
estimated: number;
|
|
336
369
|
/** Last actual token count from LLM API (null if no calls made yet) */
|
|
@@ -406,13 +439,15 @@ export declare class ContextManager<TMessage = unknown> {
|
|
|
406
439
|
* @param systemPrompt The system prompt string
|
|
407
440
|
* @param preparedHistory Message history AFTER filterCompacted and pruning
|
|
408
441
|
* @param tools Tool definitions
|
|
442
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
443
|
+
* and the actuals-based formula needs the messages after the last call
|
|
409
444
|
* @returns Estimated total input tokens for the next LLM call
|
|
410
445
|
*/
|
|
411
446
|
getEstimatedNextInputTokens(systemPrompt: string, preparedHistory: readonly InternalMessage[], tools: Record<string, {
|
|
412
447
|
name?: string;
|
|
413
448
|
description?: string;
|
|
414
449
|
parameters?: unknown;
|
|
415
|
-
}
|
|
450
|
+
}>, loadedModelHistory?: ModelHistoryLoad): Promise<number>;
|
|
416
451
|
/**
|
|
417
452
|
* Gets the system prompt formatted for the target LLM provider
|
|
418
453
|
* Some providers handle system prompts differently
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/context/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAExE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE9E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAWpD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,iBAAiB,EAAE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ore;
|
|
87
|
+
/**
|
|
88
|
+
* The assistant message of the reply being streamed. Each streamed delta, tool call and the
|
|
89
|
+
* final usage update changes it, so it is held here and written through instead of being
|
|
90
|
+
* found in the whole stored history every time. Stores copy a message when they save it.
|
|
91
|
+
* It lives for one model step: any other write through this manager, a failed write, and the
|
|
92
|
+
* end of the step (`releaseAssistantMessage`) drop it, so a write by anyone else between
|
|
93
|
+
* steps is read again, never overwritten by this copy.
|
|
94
|
+
*/
|
|
95
|
+
inFlightAssistant = null;
|
|
87
96
|
sessionId;
|
|
88
97
|
/**
|
|
89
98
|
* ResourceManager for resolving blob references in message content.
|
|
@@ -317,10 +326,7 @@ class ContextManager {
|
|
|
317
326
|
* This marks the boundary for "new messages" calculation.
|
|
318
327
|
*/
|
|
319
328
|
async recordLastCallMessageCount() {
|
|
320
|
-
|
|
321
|
-
sessionId: this.sessionId
|
|
322
|
-
});
|
|
323
|
-
this.lastCallMessageCount = history.messages.length;
|
|
329
|
+
this.lastCallMessageCount = await this.countModelMessages();
|
|
324
330
|
this.logger.debug(`Recorded lastCallMessageCount: ${this.lastCallMessageCount}`);
|
|
325
331
|
}
|
|
326
332
|
/**
|
|
@@ -365,20 +371,38 @@ class ContextManager {
|
|
|
365
371
|
* method instead of prepareHistory().
|
|
366
372
|
*/
|
|
367
373
|
async prepareModelHistory() {
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
374
|
+
return this.prepareLoadedModelHistory(await this.loadModelHistory());
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Prepares a model history the caller already loaded with loadModelHistory(), so one step can
|
|
378
|
+
* load once and prepare from the same load. The caller reloads after anything that changes
|
|
379
|
+
* stored messages.
|
|
380
|
+
*/
|
|
381
|
+
prepareLoadedModelHistory(modelHistory) {
|
|
371
382
|
return this.prepareVisibleHistory({
|
|
372
383
|
history: modelHistory.messages,
|
|
373
384
|
originalCount: modelHistory.stats.returnedMessages + modelHistory.stats.skippedPreSummaryMessages,
|
|
374
385
|
source: "prepareModelHistory"
|
|
375
386
|
});
|
|
376
387
|
}
|
|
388
|
+
/** Loads the stored messages the model sees: everything from the latest summary on. */
|
|
389
|
+
async loadModelHistory() {
|
|
390
|
+
return this.conversationStore.loadModelHistory({ sessionId: this.sessionId });
|
|
391
|
+
}
|
|
392
|
+
/** @deprecated Use loadModelHistory() */
|
|
377
393
|
async getModelHistory() {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
394
|
+
return (await this.loadModelHistory()).messages;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Number of stored messages the model sees. Reads a count when the store has one; otherwise
|
|
398
|
+
* derives it from a full load. Use it instead of loading history only to take its length.
|
|
399
|
+
*/
|
|
400
|
+
async countModelMessages() {
|
|
401
|
+
const input = { sessionId: this.sessionId };
|
|
402
|
+
if (this.conversationStore.countModelMessages) {
|
|
403
|
+
return this.conversationStore.countModelMessages(input);
|
|
404
|
+
}
|
|
405
|
+
return (await this.conversationStore.loadModelHistory(input)).messages.length;
|
|
382
406
|
}
|
|
383
407
|
prepareVisibleHistory(input) {
|
|
384
408
|
const visibleToolCallIds = /* @__PURE__ */ new Set();
|
|
@@ -483,22 +507,43 @@ ${prompt}`);
|
|
|
483
507
|
this.logger.debug(`Context cleared for session: ${this.sessionId}`);
|
|
484
508
|
}
|
|
485
509
|
/**
|
|
486
|
-
*
|
|
487
|
-
*
|
|
510
|
+
* Finds the assistant message of the reply being streamed. The one this manager started is
|
|
511
|
+
* held in memory; any other id is found with one read of the history and held from then on.
|
|
488
512
|
*/
|
|
489
|
-
async
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
if (messageIndex === -1) {
|
|
493
|
-
throw ContextError.messageNotFound(messageId);
|
|
513
|
+
async loadAssistantMessage(messageId) {
|
|
514
|
+
if (this.inFlightAssistant?.id === messageId) {
|
|
515
|
+
return this.inFlightAssistant;
|
|
494
516
|
}
|
|
495
|
-
const
|
|
517
|
+
const history = await this.conversationStore.listMessages({ sessionId: this.sessionId });
|
|
518
|
+
const message = history.find((m) => m.id === messageId);
|
|
496
519
|
if (!message) {
|
|
497
520
|
throw ContextError.messageNotFound(messageId);
|
|
498
521
|
}
|
|
499
|
-
if (message
|
|
522
|
+
if (!isAssistantMessage(message)) {
|
|
500
523
|
throw ContextError.messageNotAssistant(messageId);
|
|
501
524
|
}
|
|
525
|
+
this.inFlightAssistant = message;
|
|
526
|
+
return message;
|
|
527
|
+
}
|
|
528
|
+
/** Ends the streamed reply: the next change to its message reads it from the store again. */
|
|
529
|
+
releaseAssistantMessage() {
|
|
530
|
+
this.inFlightAssistant = null;
|
|
531
|
+
}
|
|
532
|
+
/** Writes the held assistant message through. A failed write drops it, so a retry rereads. */
|
|
533
|
+
async writeAssistantMessage(message) {
|
|
534
|
+
try {
|
|
535
|
+
await this.conversationStore.updateMessage({ sessionId: this.sessionId, message });
|
|
536
|
+
} catch (error) {
|
|
537
|
+
this.inFlightAssistant = null;
|
|
538
|
+
throw error;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Appends text to an existing assistant message.
|
|
543
|
+
* Used for streaming responses.
|
|
544
|
+
*/
|
|
545
|
+
async appendAssistantText(messageId, text) {
|
|
546
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
502
547
|
if (message.content === null) {
|
|
503
548
|
message.content = [{ type: "text", text }];
|
|
504
549
|
} else if (Array.isArray(message.content)) {
|
|
@@ -509,50 +554,28 @@ ${prompt}`);
|
|
|
509
554
|
message.content.push({ type: "text", text });
|
|
510
555
|
}
|
|
511
556
|
}
|
|
512
|
-
await this.
|
|
557
|
+
await this.writeAssistantMessage(message);
|
|
513
558
|
}
|
|
514
559
|
/**
|
|
515
560
|
* Adds a tool call to an existing assistant message.
|
|
516
561
|
* Used for streaming responses.
|
|
517
562
|
*/
|
|
518
563
|
async addToolCall(messageId, toolCall) {
|
|
519
|
-
const
|
|
520
|
-
const messageIndex = history.findIndex((m) => m.id === messageId);
|
|
521
|
-
if (messageIndex === -1) {
|
|
522
|
-
throw ContextError.messageNotFound(messageId);
|
|
523
|
-
}
|
|
524
|
-
const message = history[messageIndex];
|
|
525
|
-
if (!message) {
|
|
526
|
-
throw ContextError.messageNotFound(messageId);
|
|
527
|
-
}
|
|
528
|
-
if (message.role !== "assistant") {
|
|
529
|
-
throw ContextError.messageNotAssistant(messageId);
|
|
530
|
-
}
|
|
564
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
531
565
|
if (!message.toolCalls) {
|
|
532
566
|
message.toolCalls = [];
|
|
533
567
|
}
|
|
534
568
|
message.toolCalls.push(toolCall);
|
|
535
|
-
await this.
|
|
569
|
+
await this.writeAssistantMessage(message);
|
|
536
570
|
}
|
|
537
571
|
/**
|
|
538
572
|
* Updates an existing assistant message with new properties.
|
|
539
573
|
* Used for finalizing streaming responses (e.g. adding token usage).
|
|
540
574
|
*/
|
|
541
575
|
async updateAssistantMessage(messageId, updates) {
|
|
542
|
-
const
|
|
543
|
-
const messageIndex = history.findIndex((m) => m.id === messageId);
|
|
544
|
-
if (messageIndex === -1) {
|
|
545
|
-
throw ContextError.messageNotFound(messageId);
|
|
546
|
-
}
|
|
547
|
-
const message = history[messageIndex];
|
|
548
|
-
if (!message) {
|
|
549
|
-
throw ContextError.messageNotFound(messageId);
|
|
550
|
-
}
|
|
551
|
-
if (message.role !== "assistant") {
|
|
552
|
-
throw ContextError.messageNotAssistant(messageId);
|
|
553
|
-
}
|
|
576
|
+
const message = await this.loadAssistantMessage(messageId);
|
|
554
577
|
Object.assign(message, updates);
|
|
555
|
-
await this.
|
|
578
|
+
await this.writeAssistantMessage(message);
|
|
556
579
|
}
|
|
557
580
|
/**
|
|
558
581
|
* Marks tool messages as compacted (pruned).
|
|
@@ -570,6 +593,7 @@ ${prompt}`);
|
|
|
570
593
|
if (messageIds.length === 0) {
|
|
571
594
|
return 0;
|
|
572
595
|
}
|
|
596
|
+
this.inFlightAssistant = null;
|
|
573
597
|
const history = await this.conversationStore.listMessages({ sessionId: this.sessionId });
|
|
574
598
|
const timestamp = Date.now();
|
|
575
599
|
let markedCount = 0;
|
|
@@ -653,6 +677,7 @@ ${prompt}`);
|
|
|
653
677
|
this.logger.debug(
|
|
654
678
|
`ContextManager: Adding message to conversation store: ${JSON.stringify(message, null, 2)}`
|
|
655
679
|
);
|
|
680
|
+
this.inFlightAssistant = null;
|
|
656
681
|
await this.conversationStore.saveMessage({ sessionId: this.sessionId, message });
|
|
657
682
|
this.logger.debug("ContextManager: Message saved to conversation store", {
|
|
658
683
|
messageId: message.id,
|
|
@@ -720,6 +745,9 @@ ${prompt}`);
|
|
|
720
745
|
if (message.id === void 0) {
|
|
721
746
|
throw ContextError.assistantMessageIdMissing();
|
|
722
747
|
}
|
|
748
|
+
if (isAssistantMessage(message)) {
|
|
749
|
+
this.inFlightAssistant = message;
|
|
750
|
+
}
|
|
723
751
|
return message.id;
|
|
724
752
|
}
|
|
725
753
|
/**
|
|
@@ -903,18 +931,13 @@ ${prompt}`);
|
|
|
903
931
|
*
|
|
904
932
|
* @param contributorContext Context for building the system prompt
|
|
905
933
|
* @param tools Tool definitions to include in the estimate
|
|
934
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
906
935
|
* @returns Token estimates with breakdown and comparison to actual (if available)
|
|
907
936
|
*/
|
|
908
|
-
async getContextTokenEstimate(contributorContext, tools) {
|
|
937
|
+
async getContextTokenEstimate(contributorContext, tools, loadedModelHistory) {
|
|
909
938
|
const systemPrompt = await this.getSystemPrompt(contributorContext);
|
|
910
|
-
const modelHistory = await this.
|
|
911
|
-
|
|
912
|
-
});
|
|
913
|
-
const { preparedHistory, stats } = this.prepareVisibleHistory({
|
|
914
|
-
history: modelHistory.messages,
|
|
915
|
-
originalCount: modelHistory.stats.returnedMessages + modelHistory.stats.skippedPreSummaryMessages,
|
|
916
|
-
source: "getContextTokenEstimate"
|
|
917
|
-
});
|
|
939
|
+
const modelHistory = loadedModelHistory ?? await this.loadModelHistory();
|
|
940
|
+
const { preparedHistory, stats } = this.prepareLoadedModelHistory(modelHistory);
|
|
918
941
|
const lastInput = this.lastActualInputTokens;
|
|
919
942
|
const lastOutput = this.lastActualOutputTokens;
|
|
920
943
|
const lastMsgCount = this.lastCallMessageCount;
|
|
@@ -1012,16 +1035,16 @@ ${prompt}`);
|
|
|
1012
1035
|
* @param systemPrompt The system prompt string
|
|
1013
1036
|
* @param preparedHistory Message history AFTER filterCompacted and pruning
|
|
1014
1037
|
* @param tools Tool definitions
|
|
1038
|
+
* @param loadedModelHistory A model history the caller just loaded; loaded here when omitted
|
|
1039
|
+
* and the actuals-based formula needs the messages after the last call
|
|
1015
1040
|
* @returns Estimated total input tokens for the next LLM call
|
|
1016
1041
|
*/
|
|
1017
|
-
async getEstimatedNextInputTokens(systemPrompt, preparedHistory, tools) {
|
|
1042
|
+
async getEstimatedNextInputTokens(systemPrompt, preparedHistory, tools, loadedModelHistory) {
|
|
1018
1043
|
const lastInput = this.lastActualInputTokens;
|
|
1019
1044
|
const lastOutput = this.lastActualOutputTokens;
|
|
1020
1045
|
const lastMsgCount = this.lastCallMessageCount;
|
|
1021
1046
|
if (lastInput !== null && lastOutput !== null && lastMsgCount !== null) {
|
|
1022
|
-
const modelHistory = await this.
|
|
1023
|
-
sessionId: this.sessionId
|
|
1024
|
-
});
|
|
1047
|
+
const modelHistory = loadedModelHistory ?? await this.loadModelHistory();
|
|
1025
1048
|
const newMessages = modelHistory.messages.slice(lastMsgCount);
|
|
1026
1049
|
const newMessagesEstimate = estimateMessagesTokens(newMessages);
|
|
1027
1050
|
const total = lastInput + lastOutput + newMessagesEstimate;
|
|
@@ -1049,6 +1072,7 @@ ${prompt}`);
|
|
|
1049
1072
|
* Does not reset the system prompt
|
|
1050
1073
|
*/
|
|
1051
1074
|
async resetConversation() {
|
|
1075
|
+
this.inFlightAssistant = null;
|
|
1052
1076
|
await this.conversationStore.clearMessages({ sessionId: this.sessionId });
|
|
1053
1077
|
this.resetActualTokenTracking();
|
|
1054
1078
|
this.logger.debug(
|
|
@@ -118,6 +118,13 @@ class StreamProcessor {
|
|
|
118
118
|
partialToolCalls = /* @__PURE__ */ new Map();
|
|
119
119
|
/** Runs one model attempt. `streamFn` must send its request with the given abort signal. */
|
|
120
120
|
async process(streamFn) {
|
|
121
|
+
try {
|
|
122
|
+
return await this.processStream(streamFn);
|
|
123
|
+
} finally {
|
|
124
|
+
this.contextManager.releaseAssistantMessage();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async processStream(streamFn) {
|
|
121
128
|
const startedAtMs = Date.now();
|
|
122
129
|
const setStreamAttribute = (name, value) => {
|
|
123
130
|
import_api.trace.getActiveSpan()?.setAttribute(`llm.stream.${name}`, value);
|
|
@@ -66,6 +66,7 @@ export declare class StreamProcessor {
|
|
|
66
66
|
constructor(contextManager: ContextManager, eventBus: SessionEventBus, abortSignal: AbortSignal, config: StreamProcessorConfig, logger: Logger, streaming?: boolean, emitFatalErrors?: boolean);
|
|
67
67
|
/** Runs one model attempt. `streamFn` must send its request with the given abort signal. */
|
|
68
68
|
process(streamFn: (abortSignal: AbortSignal) => StreamTextResult<VercelToolSet, unknown>): Promise<StreamProcessorResult>;
|
|
69
|
+
private processStream;
|
|
69
70
|
private getCacheTokensFromProviderMetadata;
|
|
70
71
|
private normalizeUsage;
|
|
71
72
|
private getProviderMetadata;
|