zapagent 1.14.9 → 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/execution-environment.ts +3 -1
- 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/command.ts +5 -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/execution/root-git.ts +106 -0
- package/zapsdk/execution/sandbox.ts +29 -6
- package/zapsdk/index.ts +3 -0
- package/zapsdk/memory/conversation.ts +81 -92
- package/zapsdk/policy/engine.ts +2 -2
- package/zapsdk/policy/types.ts +3 -0
- package/zapsdk/tools/executor.ts +12 -3
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -290,7 +290,7 @@ export function App() {
|
|
|
290
290
|
}, [updateConfig])
|
|
291
291
|
|
|
292
292
|
// ── Conversation state ──
|
|
293
|
-
const { logs, addLog, replaceLog, peekNextLogId, getUiLogCount, compactLogs, setLogs, setStaticCommitFrozen, getIsFrozen, registerStaticFlushCallback } = useLogs()
|
|
293
|
+
const { logs, addLog, replaceLog, peekNextLogId, getUiLogCount, compactLogs: replaceWithCompactLog, setLogs, setStaticCommitFrozen, getIsFrozen, registerStaticFlushCallback } = useLogs()
|
|
294
294
|
const logsRef = useRef(logs)
|
|
295
295
|
logsRef.current = logs
|
|
296
296
|
|
|
@@ -298,6 +298,12 @@ export function App() {
|
|
|
298
298
|
// scratch — session restore / rewind / /clear / /new all need this.
|
|
299
299
|
const [transcriptEpoch, setTranscriptEpoch] = useState(0)
|
|
300
300
|
const bumpTranscript = useCallback(() => setTranscriptEpoch((e) => e + 1), [])
|
|
301
|
+
const compactLogs = useCallback((...args: Parameters<typeof replaceWithCompactLog>) => {
|
|
302
|
+
replaceWithCompactLog(...args)
|
|
303
|
+
// Ink Static remembers its emitted item count. Replacing a long history
|
|
304
|
+
// with one compact marker must reset that cursor before subsequent logs.
|
|
305
|
+
bumpTranscript()
|
|
306
|
+
}, [replaceWithCompactLog, bumpTranscript])
|
|
301
307
|
|
|
302
308
|
// ── Input ──
|
|
303
309
|
const [inputValue, setInputValue] = useState("")
|
|
@@ -780,9 +786,9 @@ export function App() {
|
|
|
780
786
|
},
|
|
781
787
|
onCompactFailure: setCompactFailure,
|
|
782
788
|
onMemoryFailure: setMemoryFailure,
|
|
783
|
-
onContextChanged: () => {
|
|
789
|
+
onContextChanged: (requestTokens) => {
|
|
784
790
|
setContextTokens(
|
|
785
|
-
conversation.estimatedTokens + tokenAccounting.promptOverhead,
|
|
791
|
+
requestTokens ?? conversation.estimatedTokens + tokenAccounting.promptOverhead,
|
|
786
792
|
"estimated",
|
|
787
793
|
null,
|
|
788
794
|
)
|
|
@@ -1174,7 +1180,7 @@ export function App() {
|
|
|
1174
1180
|
if (persistence.pendingWrites || persistence.lastFailure) throw new Error("Save the current session successfully before updating.")
|
|
1175
1181
|
}} onCancel={closeDialog} onRestart={request => { readCurrentSessionLogs(); requestUpdateRestart(request); exit() }} />}
|
|
1176
1182
|
{dialog === "connect" && <ConnectDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1177
|
-
{dialog === "model" && <ModelDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1183
|
+
{dialog === "model" && <ModelDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1178
1184
|
{dialog === "mode" && <ModeDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1179
1185
|
{dialog === "effort" && <EffortDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1180
1186
|
{dialog === "status" && (
|
|
@@ -82,6 +82,9 @@ export function buildAgentRuntime(deps: BuildAgentRuntimeDeps): AgentRuntime {
|
|
|
82
82
|
maxToolRetries: 2,
|
|
83
83
|
autoCompactThreshold: deps.autoCompactThreshold,
|
|
84
84
|
autoCompactTokenThreshold: deps.autoCompactTokenThreshold,
|
|
85
|
+
autoCompactEnabled: deps.config.compaction.auto,
|
|
86
|
+
pruneEnabled: deps.config.compaction.prune,
|
|
87
|
+
requestCacheScope: getActiveProvider(deps.config)?.id,
|
|
85
88
|
contextWindow: contextLimits.contextWindow,
|
|
86
89
|
inputTokenLimit: contextLimits.inputLimit,
|
|
87
90
|
outputTokenCeiling: getActiveMaxOutputTokens(deps.config),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RequestCacheObservation } from "../../zapsdk/context/request-cache.js"
|
|
1
2
|
import {
|
|
2
3
|
appendFileSync,
|
|
3
4
|
chmodSync,
|
|
@@ -51,6 +52,10 @@ export interface CacheMemoryAuditCompaction {
|
|
|
51
52
|
autoSucceeded: number
|
|
52
53
|
autoFailed: number
|
|
53
54
|
reactiveCompactions: number
|
|
55
|
+
pruneAttempts?: number
|
|
56
|
+
pruneSucceeded?: number
|
|
57
|
+
prunedTokens?: number
|
|
58
|
+
prunedMessages?: number
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
export interface CacheMemoryAuditTelemetry {
|
|
@@ -59,6 +64,8 @@ export interface CacheMemoryAuditTelemetry {
|
|
|
59
64
|
contextSamples: number
|
|
60
65
|
contextShapes: number
|
|
61
66
|
conversationPrefixShapes: number
|
|
67
|
+
wireRequests?: number
|
|
68
|
+
wireRewrites?: number
|
|
62
69
|
}
|
|
63
70
|
|
|
64
71
|
export interface CacheMemoryAuditEntry {
|
|
@@ -73,6 +80,7 @@ export interface CacheMemoryAuditEntry {
|
|
|
73
80
|
usage: CacheMemoryAuditUsage
|
|
74
81
|
promptCacheDiagnostics?: PromptCacheDiagnostics
|
|
75
82
|
contextDiagnostics?: ContextDiagnostics
|
|
83
|
+
requestCache?: RequestCacheObservation
|
|
76
84
|
telemetry?: CacheMemoryAuditTelemetry
|
|
77
85
|
compaction: CacheMemoryAuditCompaction
|
|
78
86
|
memoryUtility?: MemoryUtilityAttribution
|
|
@@ -96,6 +104,7 @@ export interface CacheMemoryAuditEntryInput {
|
|
|
96
104
|
>
|
|
97
105
|
promptCacheDiagnostics?: PromptCacheDiagnostics
|
|
98
106
|
contextDiagnostics?: ContextDiagnostics
|
|
107
|
+
requestCache?: RequestCacheObservation
|
|
99
108
|
telemetry?: Partial<CacheMemoryAuditTelemetry>
|
|
100
109
|
compaction?: Partial<CacheMemoryAuditCompaction>
|
|
101
110
|
memoryUtility?: MemoryUtilityAttribution
|
|
@@ -172,6 +181,7 @@ export function buildCacheMemoryAuditEntry(input: CacheMemoryAuditEntryInput): C
|
|
|
172
181
|
...(promptCacheDiagnostics ? { promptCacheDiagnostics } : {}),
|
|
173
182
|
...(contextDiagnostics ? { contextDiagnostics } : {}),
|
|
174
183
|
...(input.telemetry ? { telemetry: sanitizeTelemetry(input.telemetry) } : {}),
|
|
184
|
+
...(sanitizeRequestCache(input.requestCache) ? { requestCache: sanitizeRequestCache(input.requestCache) } : {}),
|
|
175
185
|
compaction: sanitizeCompaction(input.compaction),
|
|
176
186
|
...(memoryUtility ? { memoryUtility } : {}),
|
|
177
187
|
}
|
|
@@ -241,6 +251,9 @@ export class CacheMemoryAuditTracker {
|
|
|
241
251
|
private contextShapes = new Set<string>()
|
|
242
252
|
private conversationPrefixShapes = new Set<string>()
|
|
243
253
|
private written = false
|
|
254
|
+
private requestCache?: RequestCacheObservation
|
|
255
|
+
private wireRequests = 0
|
|
256
|
+
private wireRewrites = 0
|
|
244
257
|
private compaction: CacheMemoryAuditCompaction = emptyCompaction()
|
|
245
258
|
private readonly memoryUtility: MemoryUtilityTracker | undefined
|
|
246
259
|
|
|
@@ -268,6 +281,9 @@ export class CacheMemoryAuditTracker {
|
|
|
268
281
|
this.conversationPrefixShapes.clear()
|
|
269
282
|
this.written = false
|
|
270
283
|
this.compaction = emptyCompaction()
|
|
284
|
+
this.requestCache = undefined
|
|
285
|
+
this.wireRequests = 0
|
|
286
|
+
this.wireRewrites = 0
|
|
271
287
|
return
|
|
272
288
|
}
|
|
273
289
|
if (event.type === "run_step") {
|
|
@@ -291,6 +307,13 @@ export class CacheMemoryAuditTracker {
|
|
|
291
307
|
return
|
|
292
308
|
}
|
|
293
309
|
if (event.type === "observation") {
|
|
310
|
+
if (event.kind === "request_cache_shape") {
|
|
311
|
+
const shape = sanitizeRequestCache(event.detail)
|
|
312
|
+
if (shape) {
|
|
313
|
+
this.requestCache = shape; this.wireRequests++
|
|
314
|
+
if (["rewrite", "scope_change", "shape_change"].includes(shape.change)) this.wireRewrites++
|
|
315
|
+
}
|
|
316
|
+
}
|
|
294
317
|
this.recordCompaction(event)
|
|
295
318
|
return
|
|
296
319
|
}
|
|
@@ -314,12 +337,14 @@ export class CacheMemoryAuditTracker {
|
|
|
314
337
|
usage: event.usage,
|
|
315
338
|
promptCacheDiagnostics,
|
|
316
339
|
contextDiagnostics: this.latestContextDiagnostics,
|
|
340
|
+
requestCache: this.requestCache,
|
|
317
341
|
telemetry: {
|
|
318
342
|
usageSamples: this.usageSamples,
|
|
319
343
|
cacheAccountingSamples: this.cacheAccountingSamples,
|
|
320
344
|
contextSamples: this.contextSamples,
|
|
321
345
|
contextShapes: this.contextShapes.size,
|
|
322
346
|
conversationPrefixShapes: this.conversationPrefixShapes.size,
|
|
347
|
+
...(this.wireRequests ? { wireRequests: this.wireRequests, wireRewrites: this.wireRewrites } : {}),
|
|
323
348
|
},
|
|
324
349
|
compaction: this.compaction,
|
|
325
350
|
memoryUtility: this.memoryUtility?.summarize(),
|
|
@@ -332,7 +357,14 @@ export class CacheMemoryAuditTracker {
|
|
|
332
357
|
}
|
|
333
358
|
|
|
334
359
|
private recordCompaction(event: Extract<AgentEvent, { type: "observation" }>): void {
|
|
335
|
-
if (event.kind === "
|
|
360
|
+
if (event.kind === "prune_start") {
|
|
361
|
+
this.compaction.pruneAttempts = (this.compaction.pruneAttempts ?? 0) + 1
|
|
362
|
+
} else if (event.kind === "prune_done") {
|
|
363
|
+
this.compaction.pruneSucceeded = (this.compaction.pruneSucceeded ?? 0) + 1
|
|
364
|
+
this.compaction.prunedTokens = (this.compaction.prunedTokens ?? 0) + Math.max(0,
|
|
365
|
+
nonNegativeInteger(event.detail?.inputTokens) - nonNegativeInteger(event.detail?.outputTokens))
|
|
366
|
+
this.compaction.prunedMessages = (this.compaction.prunedMessages ?? 0) + nonNegativeInteger(event.detail?.messagesPruned)
|
|
367
|
+
} else if (event.kind === "autocompact_start") {
|
|
336
368
|
this.compaction.autoAttempts++
|
|
337
369
|
} else if (event.kind === "autocompact_done") {
|
|
338
370
|
if (event.detail?.failed === true) this.compaction.autoFailed++
|
|
@@ -388,14 +420,21 @@ function sanitizeCacheMemoryAuditEntry(value: unknown): CacheMemoryAuditEntry |
|
|
|
388
420
|
contextSamples: numberOrUndefined(value.telemetry.contextSamples),
|
|
389
421
|
contextShapes: numberOrUndefined(value.telemetry.contextShapes),
|
|
390
422
|
conversationPrefixShapes: numberOrUndefined(value.telemetry.conversationPrefixShapes),
|
|
423
|
+
wireRequests: numberOrUndefined(value.telemetry.wireRequests),
|
|
424
|
+
wireRewrites: numberOrUndefined(value.telemetry.wireRewrites),
|
|
391
425
|
}
|
|
392
426
|
: undefined,
|
|
427
|
+
requestCache: sanitizeRequestCache(value.requestCache),
|
|
393
428
|
compaction: isRecord(value.compaction)
|
|
394
429
|
? {
|
|
395
430
|
autoAttempts: numberOrUndefined(value.compaction.autoAttempts),
|
|
396
431
|
autoSucceeded: numberOrUndefined(value.compaction.autoSucceeded),
|
|
397
432
|
autoFailed: numberOrUndefined(value.compaction.autoFailed),
|
|
398
433
|
reactiveCompactions: numberOrUndefined(value.compaction.reactiveCompactions),
|
|
434
|
+
pruneAttempts: numberOrUndefined(value.compaction.pruneAttempts),
|
|
435
|
+
pruneSucceeded: numberOrUndefined(value.compaction.pruneSucceeded),
|
|
436
|
+
prunedTokens: numberOrUndefined(value.compaction.prunedTokens),
|
|
437
|
+
prunedMessages: numberOrUndefined(value.compaction.prunedMessages),
|
|
399
438
|
}
|
|
400
439
|
: undefined,
|
|
401
440
|
memoryUtility: sanitizeMemoryUtilityAttribution(value.memoryUtility),
|
|
@@ -440,12 +479,27 @@ function atomicRewrite(path: string, content: string): void {
|
|
|
440
479
|
}
|
|
441
480
|
}
|
|
442
481
|
|
|
482
|
+
function sanitizeRequestCache(value: unknown): RequestCacheObservation | undefined {
|
|
483
|
+
if (!isRecord(value) || !["initial", "unchanged", "append", "rewrite", "scope_change", "shape_change", "unsampled_change"].includes(String(value.change))) return undefined
|
|
484
|
+
const validHash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value)
|
|
485
|
+
if (!validHash(value.afterHash) || !validHash(value.scopeHash) || !validHash(value.staticHash)) return undefined
|
|
486
|
+
return { change: value.change as RequestCacheObservation["change"],
|
|
487
|
+
...(["prune", "summary", "recovery"].includes(String(value.reason)) ? { reason: value.reason as RequestCacheObservation["reason"] } : {}),
|
|
488
|
+
commonPrefixMessages: nonNegativeInteger(value.commonPrefixMessages), previousMessages: nonNegativeInteger(value.previousMessages),
|
|
489
|
+
messages: nonNegativeInteger(value.messages), sampled: value.sampled === true,
|
|
490
|
+
...(validHash(value.beforeHash) ? { beforeHash: value.beforeHash } : {}),
|
|
491
|
+
afterHash: value.afterHash, scopeHash: value.scopeHash, staticHash: value.staticHash }
|
|
492
|
+
}
|
|
493
|
+
|
|
443
494
|
function sanitizeCompaction(value: Partial<CacheMemoryAuditCompaction> | undefined): CacheMemoryAuditCompaction {
|
|
444
495
|
return {
|
|
445
496
|
autoAttempts: nonNegativeInteger(value?.autoAttempts),
|
|
446
497
|
autoSucceeded: nonNegativeInteger(value?.autoSucceeded),
|
|
447
498
|
autoFailed: nonNegativeInteger(value?.autoFailed),
|
|
448
499
|
reactiveCompactions: nonNegativeInteger(value?.reactiveCompactions),
|
|
500
|
+
...Object.fromEntries(["pruneAttempts", "pruneSucceeded", "prunedTokens", "prunedMessages"]
|
|
501
|
+
.filter(key => value?.[key as keyof CacheMemoryAuditCompaction] !== undefined)
|
|
502
|
+
.map(key => [key, nonNegativeInteger(value?.[key as keyof CacheMemoryAuditCompaction])])),
|
|
449
503
|
}
|
|
450
504
|
}
|
|
451
505
|
|
|
@@ -454,6 +508,7 @@ function sanitizeTelemetry(value: Partial<CacheMemoryAuditTelemetry>): CacheMemo
|
|
|
454
508
|
const contextSamples = nonNegativeInteger(value.contextSamples)
|
|
455
509
|
return {
|
|
456
510
|
usageSamples,
|
|
511
|
+
...(value.wireRequests === undefined ? {} : { wireRequests: nonNegativeInteger(value.wireRequests), wireRewrites: nonNegativeInteger(value.wireRewrites) }),
|
|
457
512
|
cacheAccountingSamples: Math.min(
|
|
458
513
|
usageSamples,
|
|
459
514
|
nonNegativeInteger(value.cacheAccountingSamples),
|
|
@@ -559,6 +559,13 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
559
559
|
|
|
560
560
|
agent.on("observation", (e: AgentEvent) => {
|
|
561
561
|
if (e.type !== "observation") return
|
|
562
|
+
if (e.kind === "prune_done" && !e.path?.length) {
|
|
563
|
+
const d = e.detail
|
|
564
|
+
const before = Number(d?.inputTokens ?? 0), after = Number(d?.outputTokens ?? 0)
|
|
565
|
+
deps.setContextTokens(after, "estimated", null)
|
|
566
|
+
deps.addLog("system", `Pruned ${d?.messagesPruned ?? 0} historical outputs · ~${Math.max(0, before - after)} tokens saved locally; provider cache may rebuild.`,
|
|
567
|
+
undefined, undefined, undefined, { restore: false })
|
|
568
|
+
}
|
|
562
569
|
if (e.kind === "autocompact_start") {
|
|
563
570
|
deps.setStatus("compacting")
|
|
564
571
|
const d = e.detail as
|
|
@@ -566,21 +573,15 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
566
573
|
| undefined
|
|
567
574
|
const msgs = d?.messageCount ?? 0
|
|
568
575
|
const tok = d?.tokenEstimate ?? 0
|
|
569
|
-
const reason = d?.trigger === "tokens" ? "token threshold" : "char threshold"
|
|
576
|
+
const reason = d?.trigger === "force" ? "overflow recovery" : d?.trigger === "tokens" ? "token threshold" : "char threshold"
|
|
570
577
|
deps.addLog(
|
|
571
578
|
"system",
|
|
572
579
|
`🗜 Compacting context — ${msgs} messages / ~${Math.round(tok / 1000)}k tokens (${reason})`,
|
|
573
580
|
)
|
|
574
|
-
//
|
|
575
|
-
//
|
|
576
|
-
// displaying the last API-truth (104K in the user repro that
|
|
577
|
-
// motivated this fix) even though the next call is already
|
|
578
|
-
// 155K + overhead — making it look like compact triggered with
|
|
579
|
-
// plenty of room left. Use the same `estimate + promptOverhead`
|
|
580
|
-
// shape the fallback paths use so the displayed total stays
|
|
581
|
-
// self-consistent across pre-turn / in-loop / restore.
|
|
581
|
+
// The shared planner already counted schemas and transient context.
|
|
582
|
+
// Do not add the previous provider-calibrated overhead a second time.
|
|
582
583
|
if (tok > 0) {
|
|
583
|
-
deps.setContextTokens(tok
|
|
584
|
+
deps.setContextTokens(tok, "estimated", null)
|
|
584
585
|
}
|
|
585
586
|
} else if (e.kind === "image_strip_self_heal") {
|
|
586
587
|
deps.addLog(
|
|
@@ -627,6 +628,9 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
627
628
|
error?: string
|
|
628
629
|
breakerTripped?: boolean
|
|
629
630
|
consecutiveFailures?: number
|
|
631
|
+
outputTokens?: number
|
|
632
|
+
status?: string
|
|
633
|
+
sourceTruncated?: boolean
|
|
630
634
|
}
|
|
631
635
|
| undefined
|
|
632
636
|
if (d?.failed) {
|
|
@@ -649,11 +653,14 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
649
653
|
)
|
|
650
654
|
}
|
|
651
655
|
} else {
|
|
656
|
+
if (typeof d?.outputTokens === "number") deps.setContextTokens(d.outputTokens, "estimated", null)
|
|
652
657
|
const before = d?.messagesBefore ?? 0
|
|
653
658
|
const after = d?.messagesAfter ?? 0
|
|
654
659
|
const summary = d?.summary ?? ""
|
|
655
660
|
if (summary && before > 0) {
|
|
656
661
|
deps.compactLogs(summary, before, after, extractFilesFromSummary(summary))
|
|
662
|
+
if (d?.status === "target_not_met") deps.addLog("system", "⚠ Compacted; protected recent input exceeds the soft target but fits the context limit.")
|
|
663
|
+
if (d?.sourceTruncated) deps.addLog("system", "⚠ Compact used bounded history previews; some historical detail was omitted.")
|
|
657
664
|
// Persist durable sections (decisions / errors / files) so they
|
|
658
665
|
// survive compact-of-compact decay. Fire-and-forget — matches the
|
|
659
666
|
// pre-turn and manual /compact paths.
|
|
@@ -10,7 +10,9 @@ import {
|
|
|
10
10
|
resolveEffortInput,
|
|
11
11
|
setEffort,
|
|
12
12
|
validateConfig,
|
|
13
|
+
getActiveMaxOutputTokens,
|
|
13
14
|
} from "../config.js"
|
|
15
|
+
import { TokenCounter } from "../../zapsdk/context/token-counter.js"
|
|
14
16
|
import { resolveActiveContextLimits } from "../context-budget.js"
|
|
15
17
|
import type { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
|
|
16
18
|
import { conversation, autoMemory } from "../singletons.js"
|
|
@@ -21,7 +23,6 @@ import {
|
|
|
21
23
|
readCurrentSessionLogs,
|
|
22
24
|
startNewSession,
|
|
23
25
|
} from "../session.js"
|
|
24
|
-
import { restoreRecentFiles } from "../../zapsdk/index.js"
|
|
25
26
|
import { extractFilesFromSummary } from "../ui/compact-utils.js"
|
|
26
27
|
import { manualCompactFailureReason } from "../agent/compactDiagnostics.js"
|
|
27
28
|
import {
|
|
@@ -159,7 +160,7 @@ export interface DispatchSlashCommandDeps {
|
|
|
159
160
|
onMemoryFailure?: (failure: MemoryFailureDiagnostic | undefined) => void
|
|
160
161
|
/** Refreshes the shared context meter after commands mutate conversation
|
|
161
162
|
* history outside the normal agent event stream (currently /compact). */
|
|
162
|
-
onContextChanged?: () => void
|
|
163
|
+
onContextChanged?: (requestTokens?: number) => void
|
|
163
164
|
/** Bind manual compaction to the AbortController used by Esc/Ctrl+C. */
|
|
164
165
|
beginManualCompact?: () => AbortController
|
|
165
166
|
/** Release the controller only when this operation still owns it. */
|
|
@@ -521,14 +522,19 @@ export function dispatchSlashCommand(
|
|
|
521
522
|
try { recordMaintenanceUsage(usage) }
|
|
522
523
|
catch (error) { deps.addToast(`Usage history could not be saved: ${String(error)}`, { variant: "error" }) }
|
|
523
524
|
})
|
|
525
|
+
const limits = resolveActiveContextLimits(deps.configRef.current)
|
|
526
|
+
const counter = new TokenCounter(() => deps.agentRef.current.provider.getImageTokenContext?.() ?? {})
|
|
524
527
|
const result = await conversation.compress(meter.wrap(deps.agentRef.current.provider, "maintenance"), {
|
|
525
|
-
force: true,
|
|
526
|
-
|
|
528
|
+
force: true, signal: controller.signal, counter,
|
|
529
|
+
contextWindow: limits.contextWindow, inputTokenLimit: limits.inputLimit,
|
|
530
|
+
reservedOutputTokens: limits.reservedOutputTokens,
|
|
531
|
+
outputTokenCeiling: getActiveMaxOutputTokens(deps.configRef.current),
|
|
532
|
+
targetTokens: limits.keepFloorTokens, restoreFiles: true,
|
|
533
|
+
tools: conversation.getCompactionContext().tools ?? deps.agentRef.current.registry?.definitions() ?? [],
|
|
527
534
|
})
|
|
528
535
|
if (controller.signal.aborted) {
|
|
529
536
|
throw controller.signal.reason ?? new Error("Compact cancelled")
|
|
530
537
|
}
|
|
531
|
-
const limits = resolveActiveContextLimits(deps.configRef.current)
|
|
532
538
|
const thresholds = {
|
|
533
539
|
triggerAt: limits.compactAt,
|
|
534
540
|
keepFloorTokens: limits.keepFloorTokens,
|
|
@@ -545,10 +551,6 @@ export function dispatchSlashCommand(
|
|
|
545
551
|
deps.onCompactFailure?.({ phase: "manual", error: failureReason })
|
|
546
552
|
deps.addToast(`Compact failed: ${failureReason}`, { variant: "error" })
|
|
547
553
|
} else if (result) {
|
|
548
|
-
const restored = await restoreRecentFiles(preMessages, { maxTokens: Math.min(2048, Math.max(0, thresholds.keepFloorTokens - conversation.estimatedTokens)) })
|
|
549
|
-
if (restored) {
|
|
550
|
-
conversation.commitTurn({ kind: "user", content: restored })
|
|
551
|
-
}
|
|
552
554
|
// Persist durable sections (decisions / errors / files) so they
|
|
553
555
|
// survive compact-of-compact decay. Fire-and-forget.
|
|
554
556
|
persistCompactSummaryBestEffort(result.summary, autoMemory, {
|
|
@@ -556,7 +558,9 @@ export function dispatchSlashCommand(
|
|
|
556
558
|
persist: deps.persistCompactSummary,
|
|
557
559
|
})
|
|
558
560
|
deps.compactLogs(result.summary, result.before, result.after, extractFilesFromSummary(result.summary))
|
|
559
|
-
deps.
|
|
561
|
+
if (result.status === "target_not_met") deps.addToast("Compacted; protected recent input exceeds the soft target but fits the context limit.", { variant: "warning" })
|
|
562
|
+
if (result.sourceTruncated) deps.addToast("Compact used bounded history previews; some historical detail was omitted.", { variant: "warning" })
|
|
563
|
+
deps.onContextChanged?.(result.outputTokens)
|
|
560
564
|
deps.onCompactFailure?.(undefined)
|
|
561
565
|
deps.addToast(`Compacted ${result.before}→${result.after} msgs`, { variant: "success" })
|
|
562
566
|
} else {
|
package/src/commands/status.ts
CHANGED
|
@@ -383,6 +383,16 @@ export function buildStatusText(
|
|
|
383
383
|
if (memoryUtility) lines.push(`Memory utility: ${memoryUtility}`)
|
|
384
384
|
}
|
|
385
385
|
lines.push(`Auto-compact: ${config.compaction.auto ? "on" : "off"}`)
|
|
386
|
+
lines.push(`Prune: ${config.compaction.prune ? "on · pressure-gated old outputs" : "off"} (overflow recovery is independent)`)
|
|
387
|
+
const latestMaintenance = diagnostics.cacheMemoryAudit?.entries.slice().reverse().find(entry =>
|
|
388
|
+
!currentCacheScope || samePromptCacheScope(entry.cacheScope, currentCacheScope))
|
|
389
|
+
if (latestMaintenance?.compaction.pruneSucceeded) {
|
|
390
|
+
lines.push(`Last prune: ${latestMaintenance.compaction.prunedMessages ?? 0} outputs · ~${formatTokens(latestMaintenance.compaction.prunedTokens ?? 0)} tokens removed locally`)
|
|
391
|
+
}
|
|
392
|
+
if (latestMaintenance?.requestCache) {
|
|
393
|
+
const shape = latestMaintenance.requestCache
|
|
394
|
+
lines.push(`Wire prefix: ${shape.change}${shape.reason ? ` (${shape.reason})` : ""} · ${shape.commonPrefixMessages} shared messages${shape.sampled ? " · sampled" : ""}; provider hit rate is separate`)
|
|
395
|
+
}
|
|
386
396
|
lines.push(`Memory dir: ${shortPath(autoMemory.memoryDir)}`)
|
|
387
397
|
lines.push(`Global memory: ${shortPath(globalMemoryDir)}`)
|
|
388
398
|
lines.push("")
|
package/src/config.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { deriveCompactionThresholds } from "../zapsdk/context/compact-budget.js"
|
|
1
2
|
import { canonicalModelId } from "../zapsdk/core/model-identity.js"
|
|
2
3
|
import { existsSync, readFileSync } from "node:fs"
|
|
3
4
|
import { sandboxTemporaryDirectoryDescription } from "./prompts/execution-facts.js"
|
|
@@ -64,6 +65,8 @@ export const DEFAULT_EFFORT_VALUES = ["minimal", "low", "medium", "high", "xhigh
|
|
|
64
65
|
* Keeping this local means normal startup and model switching never depend on
|
|
65
66
|
* network access after /connect has completed. */
|
|
66
67
|
export interface ProviderModelMetadata {
|
|
68
|
+
/** Explicit metadata source for an endpoint alias; never changes its wire ID. */
|
|
69
|
+
catalogRef?: { providerId: string; modelId: string }
|
|
67
70
|
/** Underlying lab/model identity; never replaces the endpoint request model. */
|
|
68
71
|
canonicalModelId?: string
|
|
69
72
|
name?: string
|
|
@@ -131,23 +134,7 @@ export interface CompactionThresholds {
|
|
|
131
134
|
}
|
|
132
135
|
|
|
133
136
|
export function deriveCompaction(contextWindow: number): CompactionThresholds {
|
|
134
|
-
|
|
135
|
-
// Bytes the provider needs to reserve for the model's response. These
|
|
136
|
-
// aren't available for input — clamping at 1k floor + 8k ceiling matches
|
|
137
|
-
// most provider's expected response sizes (the 8k cap covers most replies
|
|
138
|
-
// including long code edits; pinning at 10% of window so 1M-context
|
|
139
|
-
// models don't waste 100k of headroom on a number that's actually constant
|
|
140
|
-
// in practice).
|
|
141
|
-
const reserveForOutput = Math.min(8192, Math.max(1024, Math.floor(normalizedWindow * 0.10)))
|
|
142
|
-
// Effective window for input is the headroom we actually have. Used as
|
|
143
|
-
// the basis for compact + warning thresholds so they fire on time even
|
|
144
|
-
// for narrow context windows where the reservation is a meaningful slice.
|
|
145
|
-
const effectiveWindow = normalizedWindow - reserveForOutput
|
|
146
|
-
return {
|
|
147
|
-
triggerAt: Math.floor(effectiveWindow * 0.80),
|
|
148
|
-
keepFloorTokens: Math.floor(effectiveWindow * 0.40),
|
|
149
|
-
reserveForOutput,
|
|
150
|
-
}
|
|
137
|
+
return deriveCompactionThresholds(contextWindow)
|
|
151
138
|
}
|
|
152
139
|
|
|
153
140
|
export interface TokenWarningState {
|
|
@@ -530,6 +517,12 @@ function normalizeModelMetadata(value: unknown): Record<string, ProviderModelMet
|
|
|
530
517
|
for (const [modelId, raw] of Object.entries(value)) {
|
|
531
518
|
if (!modelId || !isRecord(raw)) continue
|
|
532
519
|
const metadata: ProviderModelMetadata = {}
|
|
520
|
+
if (isRecord(raw.catalogRef)) {
|
|
521
|
+
const { providerId, modelId: catalogModelId } = raw.catalogRef
|
|
522
|
+
const validId = (id: unknown): id is string => typeof id === "string" && id.length > 0
|
|
523
|
+
&& id.length <= 256 && !/[\u0000-\u001f\u007f]/.test(id)
|
|
524
|
+
if (validId(providerId) && validId(catalogModelId)) metadata.catalogRef = { providerId, modelId: catalogModelId }
|
|
525
|
+
}
|
|
533
526
|
if (typeof raw.name === "string" && raw.name) metadata.name = raw.name
|
|
534
527
|
const identity = canonicalModelId(raw.canonicalModelId)
|
|
535
528
|
if (identity) metadata.canonicalModelId = identity
|
package/src/context-budget.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
resolveProviderContextWindow,
|
|
7
7
|
type AppConfig,
|
|
8
8
|
} from "./config.js"
|
|
9
|
+
import { compactBudget } from "../zapsdk/context/compact-budget.js"
|
|
9
10
|
import { CONTEXT_INPUT_SAFETY_MARGIN_TOKENS } from "../zapsdk/agent/context-limits.js"
|
|
10
11
|
|
|
11
12
|
export type ContextUsageSource = "provider" | "estimated" | "restored" | "pending"
|
|
@@ -132,16 +133,8 @@ export function resolveActiveContextLimits(config: AppConfig): ContextLimits {
|
|
|
132
133
|
const metadata = provider?.modelMetadata?.[config.active.model]
|
|
133
134
|
const inputLimit = positiveInteger(metadata?.inputLimit)
|
|
134
135
|
const derived = deriveCompaction(contextWindow)
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
inputLimit ?? contextWindow - derived.reserveForOutput,
|
|
138
|
-
)
|
|
139
|
-
const effectiveInputLimit = Math.max(
|
|
140
|
-
1,
|
|
141
|
-
advertisedInputCapacity - CONTEXT_INPUT_SAFETY_MARGIN_TOKENS,
|
|
142
|
-
)
|
|
143
|
-
const compactAt = Math.max(1, Math.floor(effectiveInputLimit * 0.80))
|
|
144
|
-
const keepFloorTokens = Math.max(1, Math.floor(effectiveInputLimit * 0.40))
|
|
136
|
+
const budget = compactBudget({ contextWindow, inputTokenLimit: inputLimit, reservedOutputTokens: derived.reserveForOutput })!
|
|
137
|
+
const { effectiveInputLimit, compactAt, keepFloorTokens } = budget
|
|
145
138
|
return {
|
|
146
139
|
contextWindow,
|
|
147
140
|
...(inputLimit ? { inputLimit } : {}),
|
|
@@ -22,7 +22,7 @@ export interface ExecutionEnvironment {
|
|
|
22
22
|
capacity?: ExecutionCapacityFacts
|
|
23
23
|
// No prompt, model, retry, budget or completion policy is accepted here.
|
|
24
24
|
commandOptions: Pick<ExecuteCommandOptions,
|
|
25
|
-
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands">
|
|
25
|
+
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration">
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export type ExecutionBackend = "local" | "vm"
|
|
@@ -123,6 +123,7 @@ export function createExecutionEnvironment(
|
|
|
123
123
|
const local = new DefaultExecutionBroker({
|
|
124
124
|
services: serviceOwner,
|
|
125
125
|
sandbox: createPlatformSandbox({
|
|
126
|
+
rootWorkspaceGitWrites: true,
|
|
126
127
|
workspaceStateRoot: resident || installation || cloud ? undefined : join(getAppDataDir(), "sandbox", "workspaces"),
|
|
127
128
|
// Trusted outer mounts/egress are enforcement details, not Agent policy.
|
|
128
129
|
trustedWritablePaths: resident ? ["/nix"] : (installation || cloud ? [] : hostPackageWriteRoots()),
|
|
@@ -148,6 +149,7 @@ export function createExecutionEnvironment(
|
|
|
148
149
|
vm: cloud ? createZapVmCloudExecutionBroker(cloud) : undefined,
|
|
149
150
|
}),
|
|
150
151
|
commandOptions: {
|
|
152
|
+
sandboxGitIntegration: hostSandboxed && sandboxMode !== "disabled" && local.sandboxStatus().available,
|
|
151
153
|
// These transports cannot retain a detached child beyond its lease.
|
|
152
154
|
// Other backends defer to the user's env setting instead of overriding it.
|
|
153
155
|
disableBackgroundTasks: cloud !== undefined || resident ? true : undefined,
|
|
@@ -596,6 +596,9 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
596
596
|
maxToolRetries: 2,
|
|
597
597
|
autoCompactThreshold: thresholds.triggerAt * 4,
|
|
598
598
|
autoCompactTokenThreshold: thresholds.triggerAt,
|
|
599
|
+
autoCompactEnabled: config.compaction.auto,
|
|
600
|
+
pruneEnabled: config.compaction.prune,
|
|
601
|
+
requestCacheScope: getActiveProvider(config)?.id,
|
|
599
602
|
contextWindow: ctxWin,
|
|
600
603
|
inputTokenLimit: contextLimits.inputLimit,
|
|
601
604
|
outputTokenCeiling: getActiveMaxOutputTokens(config),
|
|
@@ -11,7 +11,6 @@ import { AgentLogger } from "../../zapsdk/debug/agent-logger.js"
|
|
|
11
11
|
import type { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
|
|
12
12
|
import { AutoMemory } from "../../zapsdk/memory/auto-memory.js"
|
|
13
13
|
import type { ConversationManager } from "../../zapsdk/index.js"
|
|
14
|
-
import { restoreRecentFiles } from "../../zapsdk/index.js"
|
|
15
14
|
import { extractFilesFromSummary } from "../ui/compact-utils.js"
|
|
16
15
|
import { buildCustomSystemPrompt, buildSystemPrompt, deriveCompaction, getActiveProvider } from "../config.js"
|
|
17
16
|
import { appendUsage, saveLastOutput, getCurrentSessionId } from "../session.js"
|
|
@@ -598,97 +597,9 @@ export function useAgentRunner({
|
|
|
598
597
|
const contextLimits = resolveActiveContextLimits(currentConfig)
|
|
599
598
|
const ctxWin = contextLimits.contextWindow
|
|
600
599
|
const thresholds = syncConversationCompactionThresholds(conversation, contextLimits)
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
tokenAccounting.promptOverhead,
|
|
605
|
-
)
|
|
606
|
-
if (shouldPreTurnAutoCompact(conversation.estimatedTokens, tokenAccounting.promptOverhead, thresholds.triggerAt)) {
|
|
607
|
-
setStatus("compacting")
|
|
608
|
-
// System log mirrors the in-loop autocompact_start path so the user
|
|
609
|
-
// gets the same "🗜 Compacting context — ..." marker for all three
|
|
610
|
-
// compact entry points. compactLogs() will replace the log array
|
|
611
|
-
// post-compact anyway, but during the 3-10s wait the row is the
|
|
612
|
-
// most legible "this is why your turn is paused" signal.
|
|
613
|
-
const ctxTokens = estimatedProviderInput
|
|
614
|
-
addLog("system", `🗜 Compacting context — ~${Math.round(ctxTokens / 1000)}k tokens (auto, pre-turn)`)
|
|
615
|
-
try {
|
|
616
|
-
// Capture pre-compact messages BEFORE compress so the post-compact
|
|
617
|
-
// file restoration walks the original history. After compress those
|
|
618
|
-
// turns are gone — restoring from the post-compact view would only
|
|
619
|
-
// see the summary turn and find no read_file tool calls. Use the
|
|
620
|
-
// full backing view here; getMessages() may return a truncated
|
|
621
|
-
// provider view exactly when compaction is needed.
|
|
622
|
-
const preMessages = conversation.getAllMessages()
|
|
623
|
-
const compactResult = await conversation.compress(maintenanceMeter.wrap(provider, "maintenance"), {
|
|
624
|
-
targetTokens: thresholds.keepFloorTokens,
|
|
625
|
-
signal: controller.signal,
|
|
626
|
-
})
|
|
627
|
-
const compactFailureReason = preTurnCompactFailureReason(
|
|
628
|
-
compactResult,
|
|
629
|
-
conversation.lastCompressionFailureReason,
|
|
630
|
-
)
|
|
631
|
-
if (compactFailureReason) {
|
|
632
|
-
appLogger.warn("compact_failed", {
|
|
633
|
-
phase: "pre_turn",
|
|
634
|
-
error: compactFailureReason,
|
|
635
|
-
conversationTokens: conversation.estimatedTokens,
|
|
636
|
-
promptOverhead: tokenAccounting.promptOverhead,
|
|
637
|
-
triggerAt: thresholds.triggerAt,
|
|
638
|
-
})
|
|
639
|
-
setCompactFailure({ phase: "pre_turn", error: compactFailureReason })
|
|
640
|
-
addLog("error", `✗ Context compact failed (pre-turn): ${compactFailureReason}`)
|
|
641
|
-
} else {
|
|
642
|
-
const successfulCompact = compactResult as NonNullable<typeof compactResult>
|
|
643
|
-
// Re-inject the most recently read files as a synthetic user turn
|
|
644
|
-
// — same behaviour as the in-loop AutoCompact path. Without this
|
|
645
|
-
// the agent re-Reads the same files the summary mentions but
|
|
646
|
-
// doesn't contain.
|
|
647
|
-
const restored = await restoreRecentFiles(preMessages, { maxTokens: Math.min(2048, Math.max(0, thresholds.keepFloorTokens - conversation.estimatedTokens)) })
|
|
648
|
-
if (restored) {
|
|
649
|
-
conversation.commitTurn({ kind: "user", content: restored })
|
|
650
|
-
}
|
|
651
|
-
// Persist the durable sections (decisions / errors / files) to the
|
|
652
|
-
// project's memory dir so they survive compact-of-compact decay.
|
|
653
|
-
// Fire-and-forget — best effort, never blocks the turn.
|
|
654
|
-
persistCompactSummaryBestEffort(successfulCompact.summary, autoMemory, {
|
|
655
|
-
logger: appLogger,
|
|
656
|
-
onMemoryFailure: setMemoryFailure,
|
|
657
|
-
})
|
|
658
|
-
// Replace the in-memory transcript with the boundary marker so
|
|
659
|
-
// the user sees the same "✻ Conversation compacted — N→M msgs
|
|
660
|
-
// · K files touched" row that the in-loop and manual paths
|
|
661
|
-
// emit. Without this, pre-turn compact silently swallowed the
|
|
662
|
-
// previous transcript without any persistent marker — the
|
|
663
|
-
// start-log row earlier in this block gets buried under the
|
|
664
|
-
// upcoming agent reply.
|
|
665
|
-
compactLogs(
|
|
666
|
-
successfulCompact.summary,
|
|
667
|
-
successfulCompact.before,
|
|
668
|
-
successfulCompact.after,
|
|
669
|
-
extractFilesFromSummary(successfulCompact.summary),
|
|
670
|
-
)
|
|
671
|
-
}
|
|
672
|
-
setContextTokens(
|
|
673
|
-
conversation.estimatedTokens + tokenAccounting.promptOverhead,
|
|
674
|
-
"estimated",
|
|
675
|
-
null,
|
|
676
|
-
)
|
|
677
|
-
} catch (err) {
|
|
678
|
-
const error = err instanceof Error ? err.message : String(err)
|
|
679
|
-
appLogger.warn("compact_failed", {
|
|
680
|
-
phase: "pre_turn",
|
|
681
|
-
error,
|
|
682
|
-
conversationTokens: conversation.estimatedTokens,
|
|
683
|
-
promptOverhead: tokenAccounting.promptOverhead,
|
|
684
|
-
triggerAt: thresholds.triggerAt,
|
|
685
|
-
})
|
|
686
|
-
setCompactFailure({ phase: "pre_turn", error })
|
|
687
|
-
// Keep the turn moving. The in-loop compact / reactive-compact paths
|
|
688
|
-
// still get a chance to recover if the next provider call overflows.
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
}
|
|
600
|
+
// The first Loop step is the pre-turn maintenance boundary as well.
|
|
601
|
+
// It sees the newly assembled system/schema/attachments and user input,
|
|
602
|
+
// so TUI and headless cannot compact different request views here.
|
|
692
603
|
|
|
693
604
|
// ── System prompt ──
|
|
694
605
|
// Custom systemPrompt path (skills / /init / /commit): the default
|