zapagent 1.14.10 → 1.14.11
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/package.json +1 -1
- package/src/App.tsx +10 -4
- package/src/agent/buildAgentRuntime.ts +3 -0
- package/src/agent/cacheMemoryAudit.ts +56 -1
- package/src/agent/wireRunHandlers.ts +17 -10
- package/src/commands/dispatcher.ts +14 -10
- package/src/commands/status.ts +10 -0
- package/src/config.ts +10 -17
- package/src/context-budget.ts +3 -10
- package/src/headless/runHeadless.ts +3 -0
- package/src/hooks/useAgentRunner.ts +3 -92
- package/src/provider-catalog.ts +34 -3
- package/src/provider-metadata.ts +20 -9
- package/src/ui/dialog-connect.tsx +19 -10
- package/src/ui/dialog-context-window.tsx +42 -0
- package/src/ui/dialog-model-metadata.tsx +57 -0
- package/src/ui/dialog-model.tsx +30 -7
- package/src/ui/provider-directory.tsx +5 -5
- package/zapsdk/agent/events.ts +4 -0
- package/zapsdk/agent/loop.ts +153 -34
- package/zapsdk/agent/subagent-assembly.ts +3 -0
- package/zapsdk/builtin-tools/subagent.ts +6 -0
- package/zapsdk/context/autocompact.ts +17 -460
- package/zapsdk/context/compact-budget.ts +30 -0
- package/zapsdk/context/compact-summary.ts +336 -0
- package/zapsdk/context/compact.ts +290 -0
- package/zapsdk/context/microcompact.ts +1 -1
- package/zapsdk/context/prune.ts +106 -0
- package/zapsdk/context/reactive-compact.ts +44 -11
- package/zapsdk/context/request-cache.ts +76 -0
- package/zapsdk/core/llm.ts +3 -0
- package/zapsdk/core/provider-request.ts +11 -1
- package/zapsdk/core/providers/anthropic.ts +4 -2
- package/zapsdk/core/providers/openai-compatible.ts +4 -2
- package/zapsdk/core/providers/openai-responses.ts +2 -2
- package/zapsdk/index.ts +3 -0
- package/zapsdk/memory/conversation.ts +81 -92
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { PruneGate } from "../context/prune.js";
|
|
2
|
+
import { RequestCacheTracker } from "../context/request-cache.js";
|
|
1
3
|
import type { Message, ToolCallRequest } from "../core/types.js";
|
|
2
4
|
import type { LLMProvider } from "../core/llm.js";
|
|
3
5
|
import { HistoricalImageRetention, type HistoricalImagePolicy } from "../context/historical-images.js";
|
|
4
6
|
import { mergeRecoveredProviderView } from "../context/request-recovery.js";
|
|
5
7
|
import { TokenCounter } from "../context/token-counter.js";
|
|
6
|
-
import {
|
|
8
|
+
import { compactDecision, executeCompact, type CompactOptions, type CompactResult } from "../context/compact.js";
|
|
9
|
+
import { contextFingerprint } from "../context/request-recovery.js";
|
|
10
|
+
import { compactBudget } from "../context/compact-budget.js";
|
|
7
11
|
import {
|
|
8
12
|
type Turn,
|
|
9
13
|
type CompletedCall,
|
|
@@ -19,6 +23,11 @@ export interface CompressResult {
|
|
|
19
23
|
before: number;
|
|
20
24
|
/** Surviving non-system messages (tail kept), excluding the new summary message. */
|
|
21
25
|
after: number;
|
|
26
|
+
status?: CompactResult["status"];
|
|
27
|
+
inputTokens?: number;
|
|
28
|
+
outputTokens?: number;
|
|
29
|
+
filesRestored?: number;
|
|
30
|
+
sourceTruncated?: boolean;
|
|
22
31
|
}
|
|
23
32
|
|
|
24
33
|
export interface ConversationManagerOptions {
|
|
@@ -46,7 +55,7 @@ export interface ConversationManagerOptions {
|
|
|
46
55
|
autoCompress?: boolean;
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
interface CompressOptions {
|
|
58
|
+
export interface CompressOptions extends CompactOptions {
|
|
50
59
|
force?: boolean;
|
|
51
60
|
targetTokens?: number;
|
|
52
61
|
signal?: AbortSignal;
|
|
@@ -79,6 +88,10 @@ interface PendingToolTurn {
|
|
|
79
88
|
* to keep these in sync" bugs (issue #12 was one of them).
|
|
80
89
|
*/
|
|
81
90
|
export class ConversationManager {
|
|
91
|
+
private revision = 0;
|
|
92
|
+
readonly pruneGate = new PruneGate();
|
|
93
|
+
readonly requestCacheTracker = new RequestCacheTracker();
|
|
94
|
+
private compactionContext: CompactOptions = {};
|
|
82
95
|
private turns: Turn[] = [];
|
|
83
96
|
private pending: PendingToolTurn | null = null;
|
|
84
97
|
/** Recovery keeps omitted history readable without reintroducing it into requests. */
|
|
@@ -374,114 +387,85 @@ export class ConversationManager {
|
|
|
374
387
|
return this._lastCompressionFailureReason;
|
|
375
388
|
}
|
|
376
389
|
|
|
390
|
+
/** Request metadata only, never changes/persists conversation contents. */
|
|
391
|
+
setCompactionContext(context: CompactOptions): void {
|
|
392
|
+
this.compactionContext = { ...context, transientMessages: structuredClone(context.transientMessages ?? []) };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
getCompactionContext(): CompactOptions {
|
|
396
|
+
return { ...this.compactionContext, tools: this.compactionContext.tools?.slice(),
|
|
397
|
+
transientMessages: structuredClone(this.compactionContext.transientMessages ?? []) };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
getSnapshot(): { messages: Message[]; revision: number } {
|
|
401
|
+
this.flushPending();
|
|
402
|
+
return { messages: structuredClone(this.getAllMessages()), revision: this.revision };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
compareAndReplace(messages: Message[], expectedRevision: number, counter = this.counter): boolean {
|
|
406
|
+
this.flushPending();
|
|
407
|
+
if (this.revision !== expectedRevision) return false;
|
|
408
|
+
const turns = rederiveTurns(messages);
|
|
409
|
+
const tokens = counter.countMessages(turnsToMessages(turns));
|
|
410
|
+
this.turns = turns;
|
|
411
|
+
this.counter = counter;
|
|
412
|
+
this.providerViewFloor = 0;
|
|
413
|
+
this.historicalImages?.reset();
|
|
414
|
+
this._estimatedTokens = tokens;
|
|
415
|
+
this.revision++;
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
377
419
|
/**
|
|
378
420
|
* Compress conversation by LLM summarization. Keeps the most recent turns
|
|
379
421
|
* whose total token count fits under `targetTokens` (defaults to
|
|
380
422
|
* `targetTokensAfterCompress`, which defaults to 50% of the trigger);
|
|
381
423
|
* earlier turns become a single summary turn.
|
|
382
424
|
*/
|
|
383
|
-
async compress(
|
|
384
|
-
provider?: LLMProvider,
|
|
385
|
-
options: CompressOptions = {},
|
|
386
|
-
): Promise<CompressResult | null> {
|
|
425
|
+
async compress(provider?: LLMProvider, options: CompressOptions = {}): Promise<CompressResult | null> {
|
|
387
426
|
this.flushPending();
|
|
388
427
|
this._lastCompressionFailureReason = undefined;
|
|
389
|
-
|
|
390
|
-
const force = options.force ?? false;
|
|
391
|
-
const targetTokens = nonNegativeInteger(options.targetTokens)
|
|
392
|
-
?? this.targetTokensAfterCompress
|
|
393
|
-
?? (this.triggerAtTokens ? Math.floor(this.triggerAtTokens * 0.5) : undefined);
|
|
394
|
-
|
|
395
428
|
const summarizer = provider ?? this.summarizer;
|
|
396
429
|
if (!summarizer) return null;
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
const overSoftTrigger = this.triggerAtTokens ? this._estimatedTokens > this.triggerAtTokens : false;
|
|
403
|
-
|
|
404
|
-
if (!force && !overMessages && !overTokens && !overSoftTrigger) return null;
|
|
430
|
+
const snapshot = this.getSnapshot();
|
|
431
|
+
const context = { ...this.compactionContext, ...options, counter: options.counter ?? this.counter };
|
|
432
|
+
const targetTokens = options.targetTokens ?? this.targetTokensAfterCompress
|
|
433
|
+
?? compactBudget(context)?.keepFloorTokens
|
|
434
|
+
?? (this.triggerAtTokens ? Math.floor(this.triggerAtTokens * 0.5) : undefined);
|
|
405
435
|
if (targetTokens === undefined) return null;
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
// its tool_results).
|
|
415
|
-
const systemMsgsTokens = systemTurns.reduce((sum, t) => sum + countTurnTokens(this.counter, t), 0);
|
|
416
|
-
let keepStart = nonSystem.length;
|
|
417
|
-
let keepTokens = systemMsgsTokens;
|
|
418
|
-
while (keepStart > 0) {
|
|
419
|
-
const next = keepStart - 1;
|
|
420
|
-
const t = nonSystem[next];
|
|
421
|
-
const tTokens = countTurnTokens(this.counter, t);
|
|
422
|
-
if (keepTokens + tTokens > targetTokens) break;
|
|
423
|
-
keepStart = next;
|
|
424
|
-
keepTokens += tTokens;
|
|
425
|
-
}
|
|
426
|
-
if (!force && keepStart === nonSystem.length && nonSystem.length > 0) {
|
|
427
|
-
keepStart = nonSystem.length - 1;
|
|
428
|
-
}
|
|
429
|
-
if (force && nonSystem.length > 1) {
|
|
430
|
-
const cap = Math.max(0, nonSystem.length - 10);
|
|
431
|
-
if (keepStart < cap) keepStart = cap;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
const toSummarize = nonSystem.slice(0, keepStart);
|
|
435
|
-
const toKeep = nonSystem.slice(keepStart);
|
|
436
|
-
|
|
437
|
-
if (toSummarize.length === 0) return null;
|
|
438
|
-
|
|
439
|
-
// Convert summarized turns to messages for the LLM input. Counting
|
|
440
|
-
// before/after at the message level keeps backward-compat with the
|
|
441
|
-
// CompressResult shape consumers display.
|
|
442
|
-
const summarizedMsgs = toSummarize.flatMap((t) => turnToMessages(t));
|
|
443
|
-
const before = nonSystem.flatMap((t) => turnToMessages(t)).length;
|
|
444
|
-
|
|
445
|
-
const historyText = summarizedMsgs
|
|
446
|
-
.map((m) => {
|
|
447
|
-
const role = m.role === "tool_result" ? "tool_result" : m.role;
|
|
448
|
-
return `[${role}]: ${previewMessageForCompact(role, m.content)}`;
|
|
449
|
-
})
|
|
450
|
-
.join("\n\n");
|
|
451
|
-
|
|
452
|
-
let response: Awaited<ReturnType<LLMProvider["call"]>>;
|
|
436
|
+
const over = snapshot.messages.length > this.maxMessages
|
|
437
|
+
|| (this.maxTokens !== undefined && this._estimatedTokens > this.maxTokens)
|
|
438
|
+
|| (this.triggerAtTokens !== undefined && this._estimatedTokens > this.triggerAtTokens);
|
|
439
|
+
if (context.contextWindow !== undefined) {
|
|
440
|
+
if (!compactDecision(snapshot.messages, { ...context, force: options.force,
|
|
441
|
+
triggerAtTokens: context.triggerAtTokens ?? this.triggerAtTokens }).shouldCompact) return null;
|
|
442
|
+
} else if (!options.force && !over) return null;
|
|
443
|
+
let result: CompactResult;
|
|
453
444
|
try {
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
{ role: "user", content: historyText },
|
|
457
|
-
], undefined, { signal: options.signal });
|
|
445
|
+
result = await executeCompact(snapshot.messages, summarizer, { ...context, targetTokens,
|
|
446
|
+
legacyForce: options.force, restoreFiles: context.contextWindow !== undefined && context.restoreFiles !== false });
|
|
458
447
|
} catch (err) {
|
|
459
|
-
|
|
460
|
-
this._lastCompressionFailureReason = `summarizer failed: ${message}`;
|
|
448
|
+
this._lastCompressionFailureReason = `summarizer failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
461
449
|
throw err;
|
|
462
450
|
}
|
|
463
|
-
if (
|
|
464
|
-
|
|
451
|
+
if (!result.summary) {
|
|
452
|
+
this._lastCompressionFailureReason = result.failureReason;
|
|
453
|
+
return null;
|
|
465
454
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
this._lastCompressionFailureReason =
|
|
455
|
+
if (options.signal?.aborted) throw options.signal.reason ?? new Error("compression aborted");
|
|
456
|
+
if (contextFingerprint(this.getAllMessages()) !== contextFingerprint(snapshot.messages)
|
|
457
|
+
|| !this.compareAndReplace(result.messages, snapshot.revision, context.counter)) {
|
|
458
|
+
this._lastCompressionFailureReason = "Context changed during compaction (revision conflict)";
|
|
470
459
|
return null;
|
|
471
460
|
}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
this.recalculateTokens();
|
|
481
|
-
|
|
482
|
-
const after = toKeep.flatMap((t) => turnToMessages(t)).length;
|
|
483
|
-
|
|
484
|
-
return { summary, before, after };
|
|
461
|
+
this.requestCacheTracker.markMaintenance("summary");
|
|
462
|
+
let systemCount = 0;
|
|
463
|
+
while (snapshot.messages[systemCount]?.role === "system") systemCount++;
|
|
464
|
+
const before = snapshot.messages.length - systemCount;
|
|
465
|
+
return { summary: result.summary, before,
|
|
466
|
+
after: result.messages.length - systemCount - 1, status: result.status,
|
|
467
|
+
inputTokens: result.inputTokens, outputTokens: result.outputTokens,
|
|
468
|
+
filesRestored: result.filesRestored, sourceTruncated: result.sourceTruncated };
|
|
485
469
|
}
|
|
486
470
|
|
|
487
471
|
async waitForCompression(provider?: LLMProvider, options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
@@ -521,6 +505,10 @@ export class ConversationManager {
|
|
|
521
505
|
}
|
|
522
506
|
|
|
523
507
|
clear(): void {
|
|
508
|
+
this.requestCacheTracker.clear();
|
|
509
|
+
this.pruneGate.clear();
|
|
510
|
+
this.revision++;
|
|
511
|
+
this.compactionContext = {};
|
|
524
512
|
this.historicalImages?.reset();
|
|
525
513
|
this.providerViewFloor = 0;
|
|
526
514
|
this.turns = [];
|
|
@@ -680,6 +668,7 @@ export class ConversationManager {
|
|
|
680
668
|
}
|
|
681
669
|
|
|
682
670
|
private recalculateTokens(): void {
|
|
671
|
+
this.revision++;
|
|
683
672
|
const msgs = turnsToMessages(this.turns);
|
|
684
673
|
this._estimatedTokens = this.counter.countMessages(msgs);
|
|
685
674
|
}
|