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
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { formatExecutionObservation } from "../execution/failure.js";
|
|
2
|
+
import type { Message } from "../core/types.js";
|
|
3
|
+
import { assertProviderRequestAllowed } from "../core/provider-deadline.js";
|
|
4
|
+
import { TokenCounter } from "./token-counter.js";
|
|
5
|
+
import { compactDecision, compactMessageGroups, compactRequestTokens, protectedCompactGroups, type CompactOptions } from "./compact.js";
|
|
6
|
+
import { headTailPreview } from "./compact-summary.js";
|
|
7
|
+
import { countCodePoints } from "../utils/logical-lines.js";
|
|
8
|
+
import { Microcompact, TOOL_RESULT_COMPACTED_MARKER } from "./microcompact.js";
|
|
9
|
+
import { redactTextSecrets } from "../utils/redact.js";
|
|
10
|
+
import { contextFingerprint } from "./request-recovery.js";
|
|
11
|
+
|
|
12
|
+
export interface PruneResult {
|
|
13
|
+
messages: Message[];
|
|
14
|
+
status: "pruned" | "not_needed" | "no_change";
|
|
15
|
+
inputTokens: number;
|
|
16
|
+
outputTokens: number;
|
|
17
|
+
messagesPruned: number;
|
|
18
|
+
bytesBefore: number;
|
|
19
|
+
bytesAfter: number;
|
|
20
|
+
firstChangedMessage?: number;
|
|
21
|
+
beforeHash: string;
|
|
22
|
+
afterHash: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Pure, pressure-gated candidate construction. No tool, provider or file I/O. */
|
|
26
|
+
export function planPrune(messages: Message[], options: CompactOptions = {}): PruneResult {
|
|
27
|
+
assertProviderRequestAllowed(options);
|
|
28
|
+
const counter = options.counter ?? new TokenCounter();
|
|
29
|
+
const measure = (candidate: Message[]) => compactRequestTokens(candidate, options, counter);
|
|
30
|
+
const inputTokens = measure(messages);
|
|
31
|
+
const beforeHash = contextFingerprint(messages);
|
|
32
|
+
const bytesBefore = Buffer.byteLength(JSON.stringify(messages));
|
|
33
|
+
const unchanged = (status: "not_needed" | "no_change"): PruneResult => ({ messages, status,
|
|
34
|
+
inputTokens, outputTokens: inputTokens, messagesPruned: 0, bytesBefore, bytesAfter: bytesBefore,
|
|
35
|
+
beforeHash, afterHash: beforeHash });
|
|
36
|
+
if (!compactDecision(messages, { ...options, autoEnabled: true, force: false }).shouldCompact) return unchanged("not_needed");
|
|
37
|
+
|
|
38
|
+
const candidate = structuredClone(messages);
|
|
39
|
+
const groups = compactMessageGroups(candidate);
|
|
40
|
+
const protectedGroups = protectedCompactGroups(groups, options.protectedUserText);
|
|
41
|
+
const protectedMessages = new Set(groups.flatMap((group, index) => protectedGroups.has(index) ? group : []));
|
|
42
|
+
const original = [...candidate];
|
|
43
|
+
new Microcompact().compact(candidate);
|
|
44
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
45
|
+
const message = original[i]!;
|
|
46
|
+
// Persisted-output markers are already bounded and carry the only recovery
|
|
47
|
+
// reference. Never shorten that reference or invent a new read authority.
|
|
48
|
+
if (message.role === "tool_result" && candidate[i] !== message) {
|
|
49
|
+
// Short results are cheap evidence, especially failures whose cause may
|
|
50
|
+
// be in the tail. Prune bulky bodies, not a few hundred useful characters.
|
|
51
|
+
if (countCodePoints(message.content) <= 500) {
|
|
52
|
+
const observation = formatExecutionObservation(message.executionObservation);
|
|
53
|
+
const content = observation && !message.content.includes(observation) ? `${observation}\n${message.content}` : message.content;
|
|
54
|
+
candidate[i] = { ...candidate[i]!, content: content + ` [historical blocks omitted by prune] ${TOOL_RESULT_COMPACTED_MARKER}` };
|
|
55
|
+
if (!message.contentBlocks?.length) candidate[i] = message;
|
|
56
|
+
}
|
|
57
|
+
const independentText = message.contentBlocks?.flatMap(block => block.type === "text" && block.text !== message.content
|
|
58
|
+
? [block.text] : []) ?? [];
|
|
59
|
+
if (independentText.length && candidate[i] !== message) {
|
|
60
|
+
candidate[i]!.content += "\n[Historical independent tool text blocks; bounded preview]\n"
|
|
61
|
+
+ headTailPreview(independentText.join("\n"), 4000);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (message.role === "user" && message.content !== candidate[i]!.content && message.contentBlocks?.length) {
|
|
65
|
+
const textBlocks = message.contentBlocks.filter(block => block.type === "text");
|
|
66
|
+
if (textBlocks.length === 1 && textBlocks[0]!.text === message.content) {
|
|
67
|
+
candidate[i]!.contentBlocks = message.contentBlocks.map(block => block.type === "text"
|
|
68
|
+
? { type: "text", text: candidate[i]!.content } : block);
|
|
69
|
+
} else candidate[i] = message; // Don't drop independent multimodal text.
|
|
70
|
+
}
|
|
71
|
+
if (message.role === "system" || protectedMessages.has(message) || message.cache?.transient
|
|
72
|
+
|| message.content.includes("<persisted-output")) candidate[i] = message;
|
|
73
|
+
}
|
|
74
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
75
|
+
const images = original[i]!.contentBlocks?.filter(block => block.type === "image");
|
|
76
|
+
if (images?.length && !candidate[i]!.contentBlocks && candidate[i] !== original[i]) {
|
|
77
|
+
candidate[i]!.content += "\n[Historical image references; pixels omitted, not visual evidence] "
|
|
78
|
+
+ JSON.stringify(images.map(image => ({ filePath: redactTextSecrets(image.filePath), source: redactTextSecrets(image.source), mediaType: image.mediaType })));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
82
|
+
if (counter.countMessage(candidate[i]!) >= counter.countMessage(original[i]!)) candidate[i] = original[i]!;
|
|
83
|
+
}
|
|
84
|
+
compactMessageGroups(candidate); // No orphan tool calls/results may be committed.
|
|
85
|
+
const outputTokens = measure(candidate);
|
|
86
|
+
const bytesAfter = Buffer.byteLength(JSON.stringify(candidate));
|
|
87
|
+
if (outputTokens >= inputTokens || bytesAfter >= bytesBefore) return unchanged("no_change");
|
|
88
|
+
const changed = candidate.flatMap((message, index) => contextFingerprint([message]) !== contextFingerprint([original[index]!]) ? [index] : []);
|
|
89
|
+
assertProviderRequestAllowed(options);
|
|
90
|
+
return { messages: candidate, status: "pruned", inputTokens, outputTokens,
|
|
91
|
+
messagesPruned: changed.length, bytesBefore, bytesAfter, firstChangedMessage: changed[0],
|
|
92
|
+
beforeHash, afterHash: contextFingerprint(candidate) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Hysteresis survives Host Loop reconstruction. New history must grow by 10%
|
|
96
|
+
* of the pressure threshold (at least 256 tokens) before another soft prune. */
|
|
97
|
+
export class PruneGate {
|
|
98
|
+
private last?: { hash: string; tokens: number; threshold: number };
|
|
99
|
+
clear(): void { this.last = undefined; }
|
|
100
|
+
canAttempt(hash: string, tokens: number, threshold: number, hardLimit?: number): boolean {
|
|
101
|
+
return !this.last || this.last.threshold !== threshold || (this.last.hash !== hash
|
|
102
|
+
&& (tokens >= this.last.tokens + Math.max(256, Math.floor(threshold * 0.1))
|
|
103
|
+
|| hardLimit !== undefined && tokens > hardLimit));
|
|
104
|
+
}
|
|
105
|
+
record(hash: string, tokens: number, threshold: number): void { this.last = { hash, tokens, threshold }; }
|
|
106
|
+
}
|
|
@@ -7,6 +7,7 @@ import { contextFingerprint, measureRecoveryInput, recoveryReason, reduceHistori
|
|
|
7
7
|
import { Microcompact } from "./microcompact.js";
|
|
8
8
|
import { redactTextSecrets } from "../utils/redact.js";
|
|
9
9
|
import { countCodePoints, sliceHeadCodePoints, sliceTailCodePoints } from "../utils/logical-lines.js";
|
|
10
|
+
import { CompactInputReductionError } from "./compact.js";
|
|
10
11
|
|
|
11
12
|
const MAX_REACTIVE_MESSAGE_CHARS = 12_000;
|
|
12
13
|
const REACTIVE_MESSAGE_EDGE_CHARS = 3_000;
|
|
@@ -23,6 +24,8 @@ export interface RecoveryNotice {
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
export interface RecoveryCallOptions {
|
|
27
|
+
/** The active user request is not a disposable historical preview. */
|
|
28
|
+
protectedUserText?: string;
|
|
26
29
|
/** A stream already failed. Transform before making another request. */
|
|
27
30
|
initialError?: unknown;
|
|
28
31
|
/** Snapshot the actual failed provider view before preparing a retry. */
|
|
@@ -56,12 +59,21 @@ export class ReactiveCompact {
|
|
|
56
59
|
this.onRetry = options.onRetry;
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
compactMessages(messages: Message[], counter = new TokenCounter()): { messages: Message[]; compacted: boolean } {
|
|
62
|
+
compactMessages(messages: Message[], counter = new TokenCounter(), protectedUserText?: string): { messages: Message[]; compacted: boolean } {
|
|
60
63
|
const before = measureRecoveryInput(messages, counter);
|
|
61
64
|
const beforeLength = messages.length;
|
|
65
|
+
const protectedFingerprints = protectedRecoveryMessages(messages, protectedUserText)
|
|
66
|
+
.map(message => contextFingerprint([message]));
|
|
62
67
|
const compactedMessages = this.onCompact
|
|
63
|
-
|
|
64
|
-
|
|
68
|
+
// A custom reducer must not mutate the source or the protection baseline.
|
|
69
|
+
// The spread retains local origin symbols used to position transient data.
|
|
70
|
+
? this.onCompact(messages.map(message => ({ ...message, ...structuredClone(message) })))
|
|
71
|
+
: this.defaultCompact(messages, protectedUserText);
|
|
72
|
+
for (const fingerprint of protectedFingerprints) {
|
|
73
|
+
if (!compactedMessages.some(candidate => contextFingerprint([candidate]) === fingerprint)) {
|
|
74
|
+
throw new CompactInputReductionError();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
65
77
|
return {
|
|
66
78
|
messages: compactedMessages,
|
|
67
79
|
compacted:
|
|
@@ -98,7 +110,7 @@ export class ReactiveCompact {
|
|
|
98
110
|
const source = attempt === 0 ? recovery.recoveryMessages?.() ?? currentMessages : currentMessages;
|
|
99
111
|
const candidate = reason === "request_body"
|
|
100
112
|
? reduceHistoricalImages(source)
|
|
101
|
-
: this.compactWithTransientAnchors(source, counter);
|
|
113
|
+
: this.compactWithTransientAnchors(source, counter, recovery.protectedUserText);
|
|
102
114
|
assertProviderRequestAllowed(opts);
|
|
103
115
|
const before = measureRecoveryInput(currentMessages, counter);
|
|
104
116
|
const after = measureRecoveryInput(candidate, counter);
|
|
@@ -107,6 +119,7 @@ export class ReactiveCompact {
|
|
|
107
119
|
? after.messageBytes < before.messageBytes
|
|
108
120
|
: after.estimatedTokens < before.estimatedTokens;
|
|
109
121
|
if (!improved || attempted.has(fingerprint)) {
|
|
122
|
+
if (reason === "context_tokens" && recovery.protectedUserText !== undefined) throw new CompactInputReductionError();
|
|
110
123
|
throw new RequestRecoveryError(reason, failure,
|
|
111
124
|
reason === "request_body"
|
|
112
125
|
? "no further safe media reduction; latest images and user attachments retained"
|
|
@@ -137,14 +150,14 @@ export class ReactiveCompact {
|
|
|
137
150
|
}
|
|
138
151
|
}
|
|
139
152
|
|
|
140
|
-
private compactWithTransientAnchors(messages: Message[], counter: TokenCounter): Message[] {
|
|
153
|
+
private compactWithTransientAnchors(messages: Message[], counter: TokenCounter, protectedUserText?: string): Message[] {
|
|
141
154
|
// Symbols survive object spreads inside compaction but never enter JSON.
|
|
142
155
|
// This lets transient host messages retain their position even when their
|
|
143
156
|
// neighbouring persistent message was shortened or an earlier range dropped.
|
|
144
157
|
const origin = Symbol("recovery-origin");
|
|
145
158
|
const tagged = messages.map((message, index) => ({ ...message, [origin]: index }));
|
|
146
159
|
const persistent = tagged.filter(m => !m.cache?.transient);
|
|
147
|
-
const result = this.compactMessages(persistent, counter).messages as Array<Message & { [origin]?: number }>;
|
|
160
|
+
const result = this.compactMessages(persistent, counter, protectedUserText).messages as Array<Message & { [origin]?: number }>;
|
|
148
161
|
for (const message of tagged.filter(m => m.cache?.transient)) {
|
|
149
162
|
const compacted = this.compactMessages([message], counter).messages[0] as Message & { [origin]?: number };
|
|
150
163
|
const next = result.findIndex(m => m[origin] !== undefined && m[origin]! > message[origin]);
|
|
@@ -156,16 +169,18 @@ export class ReactiveCompact {
|
|
|
156
169
|
});
|
|
157
170
|
}
|
|
158
171
|
|
|
159
|
-
private defaultCompact(messages: Message[]): Message[] {
|
|
172
|
+
private defaultCompact(messages: Message[], protectedUserText?: string): Message[] {
|
|
160
173
|
const result = [...messages];
|
|
174
|
+
const protectedMessages = new Set(protectedRecoveryMessages(messages, protectedUserText));
|
|
161
175
|
|
|
162
176
|
// Step 1: Microcompact all tool results aggressively
|
|
163
177
|
new Microcompact({ keepRecent: 2 }).compact(result);
|
|
178
|
+
messages.forEach((message, index) => { if (protectedMessages.has(message)) result[index] = message; });
|
|
164
179
|
|
|
165
180
|
// Step 2: Shrink any single oversized narrative message, including the
|
|
166
181
|
// latest user paste. Dropping the middle cannot help when the overflow is
|
|
167
182
|
// caused by the tail message itself, so preserve its head/tail and retry.
|
|
168
|
-
this.compactOversizedMessages(result);
|
|
183
|
+
this.compactOversizedMessages(result, protectedMessages);
|
|
169
184
|
|
|
170
185
|
// Step 3: If still overflowing, drop middle messages.
|
|
171
186
|
// Keep: leading system messages, last 6 messages, drop the middle. Trigger whenever
|
|
@@ -181,10 +196,14 @@ export class ReactiveCompact {
|
|
|
181
196
|
tailStart--;
|
|
182
197
|
}
|
|
183
198
|
const tail = result.slice(tailStart);
|
|
184
|
-
const
|
|
199
|
+
const middle = result.slice(system.length, tailStart);
|
|
200
|
+
const droppedMessages = middle.filter(message => !protectedMessages.has(message));
|
|
201
|
+
const pinned = middle.filter(message => protectedMessages.has(message));
|
|
202
|
+
if (!droppedMessages.length) return result;
|
|
185
203
|
return [
|
|
186
204
|
...system,
|
|
187
205
|
{ role: "user" as const, content: summarizeDroppedMessages(droppedMessages) },
|
|
206
|
+
...pinned,
|
|
188
207
|
...tail,
|
|
189
208
|
];
|
|
190
209
|
}
|
|
@@ -192,12 +211,12 @@ export class ReactiveCompact {
|
|
|
192
211
|
return result;
|
|
193
212
|
}
|
|
194
213
|
|
|
195
|
-
private compactOversizedMessages(messages: Message[]): number {
|
|
214
|
+
private compactOversizedMessages(messages: Message[], protectedMessages = new Set<Message>()): number {
|
|
196
215
|
const systemLen = leadingSystemMessageCount(messages);
|
|
197
216
|
let compacted = 0;
|
|
198
217
|
for (let i = systemLen; i < messages.length; i++) {
|
|
199
218
|
const msg = messages[i];
|
|
200
|
-
if (!msg || msg.role === "tool_result") continue;
|
|
219
|
+
if (!msg || msg.role === "tool_result" || protectedMessages.has(msg)) continue;
|
|
201
220
|
const contentChars = countCodePoints(msg.content);
|
|
202
221
|
if (contentChars <= MAX_REACTIVE_MESSAGE_CHARS) continue;
|
|
203
222
|
const head = sliceHeadCodePoints(msg.content, REACTIVE_MESSAGE_EDGE_CHARS);
|
|
@@ -215,6 +234,20 @@ export class ReactiveCompact {
|
|
|
215
234
|
}
|
|
216
235
|
}
|
|
217
236
|
|
|
237
|
+
function protectedRecoveryMessages(messages: Message[], protectedUserText?: string): Message[] {
|
|
238
|
+
if (protectedUserText === undefined) return [];
|
|
239
|
+
const persistent = messages.filter(message => !message.cache?.transient);
|
|
240
|
+
const user = persistent.findLast(message => message.role === "user" && message.content === protectedUserText);
|
|
241
|
+
const lastUser = persistent.findLast(message => message.role === "user");
|
|
242
|
+
const protectedMessages = [user, lastUser].filter((message): message is Message => !!message);
|
|
243
|
+
const lastTool = persistent.findLastIndex(message => message.role === "assistant" && !!message.toolCalls?.length);
|
|
244
|
+
if (user && lastTool > persistent.indexOf(user)) {
|
|
245
|
+
protectedMessages.push(persistent[lastTool]!);
|
|
246
|
+
for (let i = lastTool + 1; persistent[i]?.role === "tool_result"; i++) protectedMessages.push(persistent[i]!);
|
|
247
|
+
}
|
|
248
|
+
return protectedMessages;
|
|
249
|
+
}
|
|
250
|
+
|
|
218
251
|
function leadingSystemMessageCount(messages: Message[]): number {
|
|
219
252
|
let count = 0;
|
|
220
253
|
while (messages[count]?.role === "system") count++;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const MAX_HASHES = 256;
|
|
4
|
+
export interface RequestCacheShape {
|
|
5
|
+
scopeHash: string;
|
|
6
|
+
staticHash: string;
|
|
7
|
+
messageCount: number;
|
|
8
|
+
messageHashes: string[];
|
|
9
|
+
fullHash: string;
|
|
10
|
+
}
|
|
11
|
+
export interface RequestCacheObservation {
|
|
12
|
+
change: "initial" | "unchanged" | "append" | "rewrite" | "scope_change" | "shape_change" | "unsampled_change";
|
|
13
|
+
reason?: "prune" | "summary" | "recovery";
|
|
14
|
+
commonPrefixMessages: number;
|
|
15
|
+
previousMessages: number;
|
|
16
|
+
messages: number;
|
|
17
|
+
sampled: boolean;
|
|
18
|
+
beforeHash?: string;
|
|
19
|
+
afterHash: string;
|
|
20
|
+
scopeHash: string;
|
|
21
|
+
staticHash: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value, (key, item) => key === "cache_control" ? undefined : item) ?? "null").digest("hex");
|
|
25
|
+
|
|
26
|
+
/** Called with the adapter's final serialized body, never API headers/keys.
|
|
27
|
+
* Cache placement hints are excluded; the existing requestFingerprint records
|
|
28
|
+
* the exact JSON, including placement changes. Digests describe local wire shape, not provider cache hits or token savings. */
|
|
29
|
+
export function requestCacheShape(body: unknown, transport = "unknown"): RequestCacheShape | undefined {
|
|
30
|
+
if (!body || typeof body !== "object") return undefined;
|
|
31
|
+
const record = body as Record<string, unknown>;
|
|
32
|
+
const messages = Array.isArray(record.messages) ? record.messages : Array.isArray(record.input) ? record.input : undefined;
|
|
33
|
+
if (!messages) return undefined;
|
|
34
|
+
// Output limits, streaming and usage controls change independently of the
|
|
35
|
+
// cacheable prefix. System/instructions and schemas are part of its shape.
|
|
36
|
+
const staticPart = { system: record.system, instructions: record.instructions, tools: record.tools,
|
|
37
|
+
tool_choice: record.tool_choice, reasoning: record.reasoning, reasoning_effort: record.reasoning_effort };
|
|
38
|
+
return { scopeHash: hash([transport, record.model]), staticHash: hash(staticPart),
|
|
39
|
+
messageCount: messages.length, messageHashes: messages.slice(0, MAX_HASHES).map(hash), fullHash: hash(messages) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function scopeRequestCacheShape(shape: RequestCacheShape, providerScope?: string): RequestCacheShape {
|
|
43
|
+
return providerScope === undefined ? shape : { ...shape, scopeHash: hash([providerScope, shape.scopeHash]) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Bounded per-conversation baseline, reused when the Host rebuilds LoopAgent. */
|
|
47
|
+
export class RequestCacheTracker {
|
|
48
|
+
private previous?: RequestCacheShape;
|
|
49
|
+
private pending?: RequestCacheObservation["reason"];
|
|
50
|
+
markMaintenance(reason: NonNullable<RequestCacheObservation["reason"]>): void { this.pending = reason; }
|
|
51
|
+
clear(): void { this.previous = undefined; this.pending = undefined; }
|
|
52
|
+
observe(shape: RequestCacheShape): RequestCacheObservation {
|
|
53
|
+
const previous = this.previous;
|
|
54
|
+
let common = 0;
|
|
55
|
+
if (previous && previous.scopeHash === shape.scopeHash && previous.staticHash === shape.staticHash) {
|
|
56
|
+
while (common < Math.min(previous.messageHashes.length, shape.messageHashes.length)
|
|
57
|
+
&& previous.messageHashes[common] === shape.messageHashes[common]) common++;
|
|
58
|
+
}
|
|
59
|
+
const sampled = shape.messageCount > shape.messageHashes.length
|
|
60
|
+
|| !!previous && previous.messageCount > previous.messageHashes.length;
|
|
61
|
+
const change: RequestCacheObservation["change"] = !previous ? "initial"
|
|
62
|
+
: previous.scopeHash !== shape.scopeHash ? "scope_change"
|
|
63
|
+
: previous.staticHash !== shape.staticHash ? "shape_change"
|
|
64
|
+
: previous.fullHash === shape.fullHash ? "unchanged"
|
|
65
|
+
: common === previous.messageCount && shape.messageCount > previous.messageCount ? "append"
|
|
66
|
+
: sampled && common === Math.min(previous.messageHashes.length, shape.messageHashes.length) ? "unsampled_change" : "rewrite";
|
|
67
|
+
const observation: RequestCacheObservation = { change,
|
|
68
|
+
...(this.pending ? { reason: this.pending } : {}), commonPrefixMessages: common,
|
|
69
|
+
previousMessages: previous?.messageCount ?? 0, messages: shape.messageCount, sampled,
|
|
70
|
+
...(previous ? { beforeHash: previous.fullHash } : {}), afterHash: shape.fullHash,
|
|
71
|
+
scopeHash: shape.scopeHash, staticHash: shape.staticHash };
|
|
72
|
+
this.previous = { ...shape, messageHashes: shape.messageHashes.slice() };
|
|
73
|
+
this.pending = undefined;
|
|
74
|
+
return observation;
|
|
75
|
+
}
|
|
76
|
+
}
|
package/zapsdk/core/llm.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RequestCacheShape } from "../context/request-cache.js";
|
|
1
2
|
import type { ImageTokenContext } from "../context/image-tokens.js";
|
|
2
3
|
import type { LLMResponse, LLMChunk, Message } from "./types.js";
|
|
3
4
|
import type { ToolDefinition } from "../tools/types.js";
|
|
@@ -14,6 +15,8 @@ export interface ProviderRequestEvent {
|
|
|
14
15
|
/** Actual JSON UTF-8 body bytes, measured by the adapter before SDK I/O. */
|
|
15
16
|
requestBytes?: number;
|
|
16
17
|
requestFingerprint?: string;
|
|
18
|
+
/** Bounded digests of the adapter-serialized request; never provider hit data. */
|
|
19
|
+
cacheShape?: RequestCacheShape;
|
|
17
20
|
delayMs?: number;
|
|
18
21
|
/** Snapshot of streamed output observed in this attempt. Times are measured
|
|
19
22
|
* from request start; counts use JS string lengths, not tokens or bytes.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestCacheShape } from "../context/request-cache.js";
|
|
1
2
|
import type { LLMCallOptions, ProviderRequestEvent } from "./llm.js";
|
|
2
3
|
import type { LLMChunk } from "./types.js";
|
|
3
4
|
import { assertProviderRequestAllowed } from "./provider-deadline.js";
|
|
@@ -41,6 +42,8 @@ export class ProviderRequest {
|
|
|
41
42
|
private output?: ProviderRequestEvent["output"];
|
|
42
43
|
private requestBytes?: number;
|
|
43
44
|
private requestFingerprint?: string;
|
|
45
|
+
private cacheShape?: ProviderRequestEvent["cacheShape"];
|
|
46
|
+
private cacheShapeEmitted = false;
|
|
44
47
|
private rejectWait!: (error: Error) => void;
|
|
45
48
|
private failure = new Promise<never>((_, reject) => { this.rejectWait = reject; });
|
|
46
49
|
private abort = () => this.fail(new DOMException("Provider request cancelled", "AbortError"));
|
|
@@ -59,15 +62,22 @@ export class ProviderRequest {
|
|
|
59
62
|
if (this.closed) return;
|
|
60
63
|
const at = Date.now();
|
|
61
64
|
if (phase === "streaming") this.lastOutputEventAt = at;
|
|
65
|
+
// Prefix digests are bounded but still sizeable. Send them once per
|
|
66
|
+
// serialized request, not on every streaming progress/audit event.
|
|
67
|
+
const cacheShape = this.cacheShapeEmitted ? undefined : this.cacheShape;
|
|
68
|
+
if (cacheShape) this.cacheShapeEmitted = true;
|
|
62
69
|
notifyProviderRequest(this.opts, { phase, attempt: this.opts?.requestAttempt?.attempt ?? 1,
|
|
63
70
|
maxAttempts: this.opts?.requestAttempt?.maxAttempts ?? 1,
|
|
64
71
|
startedAt: this.startedAt, at, elapsedMs: at - this.startedAt, reason,
|
|
65
72
|
...(this.requestBytes !== undefined ? { requestBytes: this.requestBytes, requestFingerprint: this.requestFingerprint } : {}),
|
|
73
|
+
...(cacheShape ? { cacheShape } : {}),
|
|
66
74
|
...(this.output ? { output: { ...this.output } } : {}) });
|
|
67
75
|
}
|
|
68
76
|
|
|
69
|
-
measureBody(body: unknown, maxRequestBytes?: number): void {
|
|
77
|
+
measureBody(body: unknown, maxRequestBytes?: number, transport?: string): void {
|
|
70
78
|
const json = JSON.stringify(body);
|
|
79
|
+
this.cacheShape = requestCacheShape(body, transport);
|
|
80
|
+
this.cacheShapeEmitted = false;
|
|
71
81
|
this.requestBytes = Buffer.byteLength(json);
|
|
72
82
|
this.requestFingerprint = createHash("sha256").update(json).digest("hex");
|
|
73
83
|
if (maxRequestBytes !== undefined && Number.isFinite(maxRequestBytes) && maxRequestBytes > 0 && this.requestBytes > maxRequestBytes) {
|
|
@@ -41,6 +41,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
41
41
|
private client: Anthropic;
|
|
42
42
|
private maxTokens: number;
|
|
43
43
|
private maxRequestBytes?: number;
|
|
44
|
+
private requestCacheScope: string;
|
|
44
45
|
private promptCaching: boolean;
|
|
45
46
|
private streamIdleMs?: number;
|
|
46
47
|
|
|
@@ -49,6 +50,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
49
50
|
this.imageTokenRule = options.imageTokenRule;
|
|
50
51
|
this.canonicalModelIds = { ...options.canonicalModelIds };
|
|
51
52
|
this.maxRequestBytes = options.maxRequestBytes;
|
|
53
|
+
this.requestCacheScope = `anthropic:${options.client?.baseURL ?? "default"}`;
|
|
52
54
|
this.client = options.client ?? new Anthropic({ maxRetries: 0 });
|
|
53
55
|
this.maxTokens = options.maxTokens ?? 4096;
|
|
54
56
|
this.promptCaching = options.promptCaching ?? true;
|
|
@@ -96,7 +98,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
96
98
|
|
|
97
99
|
const request = new ProviderRequest(opts);
|
|
98
100
|
try {
|
|
99
|
-
request.measureBody(params, this.maxRequestBytes);
|
|
101
|
+
request.measureBody(params, this.maxRequestBytes, this.requestCacheScope);
|
|
100
102
|
const response = await request.wait(this.client.messages.create(params as any, {
|
|
101
103
|
signal: request.signal, maxRetries: 0,
|
|
102
104
|
}));
|
|
@@ -112,7 +114,7 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
112
114
|
opts?: LLMCallOptions,
|
|
113
115
|
): AsyncIterable<LLMChunk> {
|
|
114
116
|
const request = new ProviderRequest(opts);
|
|
115
|
-
yield* request.watch(this.streamResponse(messages, tools, { ...opts, signal: request.signal }, request.responseReceived, body => request.measureBody(body, this.maxRequestBytes)));
|
|
117
|
+
yield* request.watch(this.streamResponse(messages, tools, { ...opts, signal: request.signal }, request.responseReceived, body => request.measureBody(body, this.maxRequestBytes, this.requestCacheScope)));
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
private async *streamResponse(
|
|
@@ -138,6 +138,7 @@ export class OpenAICompatibleProvider implements LLMProvider {
|
|
|
138
138
|
private client: OpenAI;
|
|
139
139
|
private maxTokens: number;
|
|
140
140
|
private maxRequestBytes?: number;
|
|
141
|
+
private requestCacheScope: string;
|
|
141
142
|
private extraRequestParams: Record<string, unknown>;
|
|
142
143
|
private supportsVision?: boolean;
|
|
143
144
|
private streamIdleMs?: number;
|
|
@@ -147,6 +148,7 @@ export class OpenAICompatibleProvider implements LLMProvider {
|
|
|
147
148
|
this.imageTokenRule = options.imageTokenRule;
|
|
148
149
|
this.canonicalModelIds = { ...options.canonicalModelIds };
|
|
149
150
|
this.maxRequestBytes = options.maxRequestBytes;
|
|
151
|
+
this.requestCacheScope = `chat:${options.baseURL ?? options.client?.baseURL ?? "default"}`;
|
|
150
152
|
this.client =
|
|
151
153
|
options.client ??
|
|
152
154
|
new OpenAI({
|
|
@@ -214,7 +216,7 @@ export class OpenAICompatibleProvider implements LLMProvider {
|
|
|
214
216
|
|
|
215
217
|
const request = new ProviderRequest(opts);
|
|
216
218
|
try {
|
|
217
|
-
request.measureBody(params, this.maxRequestBytes);
|
|
219
|
+
request.measureBody(params, this.maxRequestBytes, this.requestCacheScope);
|
|
218
220
|
const response = await request.wait(this.client.chat.completions.create(params as any, {
|
|
219
221
|
signal: request.signal, maxRetries: 0,
|
|
220
222
|
}));
|
|
@@ -230,7 +232,7 @@ export class OpenAICompatibleProvider implements LLMProvider {
|
|
|
230
232
|
opts?: LLMCallOptions,
|
|
231
233
|
): AsyncIterable<LLMChunk> {
|
|
232
234
|
const request = new ProviderRequest(opts);
|
|
233
|
-
yield* request.watch(this.streamResponse(messages, tools, { ...opts, signal: request.signal }, request.responseReceived, body => request.measureBody(body, this.maxRequestBytes)));
|
|
235
|
+
yield* request.watch(this.streamResponse(messages, tools, { ...opts, signal: request.signal }, request.responseReceived, body => request.measureBody(body, this.maxRequestBytes, this.requestCacheScope)));
|
|
234
236
|
}
|
|
235
237
|
|
|
236
238
|
private async *streamResponse(
|
|
@@ -153,7 +153,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
153
153
|
const request = new ProviderRequest(opts);
|
|
154
154
|
try {
|
|
155
155
|
const body = this.body(messages, tools, opts, false);
|
|
156
|
-
request.measureBody(body, this.options.maxRequestBytes);
|
|
156
|
+
request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
|
|
157
157
|
const response = await request.wait(this.client.responses.create({ ...body, stream: false }, { signal: request.signal, maxRetries: 0 }));
|
|
158
158
|
const parsed = this.parse(response);
|
|
159
159
|
request.complete();
|
|
@@ -168,7 +168,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
168
168
|
|
|
169
169
|
private async *streamResponse(messages: Message[], tools: ToolDefinition[] | undefined, opts: LLMCallOptions | undefined, request: ProviderRequest): AsyncIterable<LLMChunk> {
|
|
170
170
|
const body = this.body(messages, tools, opts, true);
|
|
171
|
-
request.measureBody(body, this.options.maxRequestBytes);
|
|
171
|
+
request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
|
|
172
172
|
const stream = await this.client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 });
|
|
173
173
|
request.responseReceived();
|
|
174
174
|
let emittedText = "";
|
package/zapsdk/index.ts
CHANGED
|
@@ -76,6 +76,7 @@ export { ResultCompressor, type ResultCompressorOptions } from "./context/result
|
|
|
76
76
|
export { Microcompact, type MicrocompactOptions } from "./context/microcompact.js";
|
|
77
77
|
export { ReactiveCompact, type ReactiveCompactOptions } from "./context/reactive-compact.js";
|
|
78
78
|
export { AutoCompact, type AutoCompactOptions } from "./context/autocompact.js";
|
|
79
|
+
export { CompactInputReductionError, compactDecision, planCompact, type CompactOptions, type CompactPlan, type CompactResult } from "./context/compact.js";
|
|
79
80
|
export { restoreRecentFiles } from "./context/restore-files.js";
|
|
80
81
|
export { generateToolUseSummary, type ToolCallInfo } from "./context/tool-use-summary.js";
|
|
81
82
|
|
|
@@ -151,3 +152,5 @@ export { EXECUTION_CONTRACT_VERSION, ExecutionOperationSchema, BackendCapabiliti
|
|
|
151
152
|
export * from "./services/index.js";
|
|
152
153
|
|
|
153
154
|
export { createResultSourceGuard, ResultSourcePolicySchema, type ResultSourcePolicy, type ToolResultGuard } from "./tools/result-source-policy.js";
|
|
155
|
+
|
|
156
|
+
export { planPrune, type PruneResult } from "./context/prune.js";
|