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.
Files changed (44) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +10 -4
  3. package/src/agent/buildAgentRuntime.ts +3 -0
  4. package/src/agent/cacheMemoryAudit.ts +56 -1
  5. package/src/agent/wireRunHandlers.ts +17 -10
  6. package/src/commands/dispatcher.ts +14 -10
  7. package/src/commands/status.ts +10 -0
  8. package/src/config.ts +10 -17
  9. package/src/context-budget.ts +3 -10
  10. package/src/execution-environment.ts +3 -1
  11. package/src/headless/runHeadless.ts +3 -0
  12. package/src/hooks/useAgentRunner.ts +3 -92
  13. package/src/provider-catalog.ts +34 -3
  14. package/src/provider-metadata.ts +20 -9
  15. package/src/ui/dialog-connect.tsx +19 -10
  16. package/src/ui/dialog-context-window.tsx +42 -0
  17. package/src/ui/dialog-model-metadata.tsx +57 -0
  18. package/src/ui/dialog-model.tsx +30 -7
  19. package/src/ui/provider-directory.tsx +5 -5
  20. package/zapsdk/agent/events.ts +4 -0
  21. package/zapsdk/agent/loop.ts +153 -34
  22. package/zapsdk/agent/subagent-assembly.ts +3 -0
  23. package/zapsdk/builtin-tools/command.ts +5 -0
  24. package/zapsdk/builtin-tools/subagent.ts +6 -0
  25. package/zapsdk/context/autocompact.ts +17 -460
  26. package/zapsdk/context/compact-budget.ts +30 -0
  27. package/zapsdk/context/compact-summary.ts +336 -0
  28. package/zapsdk/context/compact.ts +290 -0
  29. package/zapsdk/context/microcompact.ts +1 -1
  30. package/zapsdk/context/prune.ts +106 -0
  31. package/zapsdk/context/reactive-compact.ts +44 -11
  32. package/zapsdk/context/request-cache.ts +76 -0
  33. package/zapsdk/core/llm.ts +3 -0
  34. package/zapsdk/core/provider-request.ts +11 -1
  35. package/zapsdk/core/providers/anthropic.ts +4 -2
  36. package/zapsdk/core/providers/openai-compatible.ts +4 -2
  37. package/zapsdk/core/providers/openai-responses.ts +2 -2
  38. package/zapsdk/execution/root-git.ts +106 -0
  39. package/zapsdk/execution/sandbox.ts +29 -6
  40. package/zapsdk/index.ts +3 -0
  41. package/zapsdk/memory/conversation.ts +81 -92
  42. package/zapsdk/policy/engine.ts +2 -2
  43. package/zapsdk/policy/types.ts +3 -0
  44. package/zapsdk/tools/executor.ts +12 -3
@@ -1,3 +1,4 @@
1
+ import { RequestCacheTracker, scopeRequestCacheShape } from "../context/request-cache.js";
1
2
  import { backgroundTaskLifecycle, describeBackgroundTaskLifecycle, type BackgroundTaskOwner } from "../tasks/lifecycle.js";
2
3
  import { describeCheckpointCoverage } from "../checkpoint/facts.js";
3
4
  import { conciseAgentProtocol, DELIVERABLE_SCOPE_GUIDANCE, resolvePromptProfile, type PromptProfile } from "./prompt-profile.js";
@@ -62,7 +63,9 @@ import { maybePersistToolResult, PERSIST_THRESHOLD_CHARS } from "../utils/tool-r
62
63
  import { countCodePoints, sliceHeadCodePoints } from "../utils/logical-lines.js";
63
64
  import { createHash, randomUUID } from "node:crypto";
64
65
  import { TokenCounter } from "../context/token-counter.js";
65
- import { restoreRecentFiles } from "../context/restore-files.js";
66
+ import { planPrune, PruneGate } from "../context/prune.js";
67
+ import { compactBudget } from "../context/compact-budget.js";
68
+ import { CompactInputReductionError, compactDecision, compactRequestTokens, planCompact, type CompactOptions } from "../context/compact.js";
66
69
  import {
67
70
  ContextOverflowError,
68
71
  isLikelyContextLimitErrorMessage,
@@ -216,6 +219,11 @@ export interface SubagentConfig {
216
219
  * `subagentTool` from `zapsdk/builtin-tools/subagent.ts` satisfies this shape.
217
220
  */
218
221
  export interface SubagentFactoryArgs {
222
+ autoCompactEnabled?: boolean;
223
+ /** Pressure-gated old-output pruning; opt-in for legacy SDK callers. */
224
+ pruneEnabled?: boolean;
225
+ /** Non-secret Host connection identity used only for local cache statistics. */
226
+ requestCacheScope?: string;
219
227
  inheritedInstructions?: string;
220
228
  promptProfile?: PromptProfile;
221
229
  getResultSchema?: () => "outcome-v1" | "legacy";
@@ -251,6 +259,12 @@ export interface SubagentFactoryArgs {
251
259
  export type SubagentFactory = (args: SubagentFactoryArgs) => Tool;
252
260
 
253
261
  export interface LoopAgentOptions {
262
+ /** Disable proactive summaries; manual and bounded overflow recovery remain available. */
263
+ autoCompactEnabled?: boolean;
264
+ /** Pressure-gated old-output pruning; opt-in for legacy SDK callers. */
265
+ pruneEnabled?: boolean;
266
+ /** Non-secret Host connection identity used only for local cache statistics. */
267
+ requestCacheScope?: string;
254
268
  /** Already metered host maintenance for this run; never charged twice. */
255
269
  initialUsage?: TokenUsage;
256
270
  provider: LLMProvider;
@@ -435,7 +449,7 @@ function forceFinishInstruction(reason: ForceFinishReason): string {
435
449
  type AddMessage = (msg: Message) => void;
436
450
  type CommitTurn = (turn: Turn) => void;
437
451
  type GetMessages = () => Message[];
438
- type ReplaceMessages = (msgs: Message[]) => void;
452
+ type ReplaceMessages = (msgs: Message[], expectedRevision?: number) => void;
439
453
  type ErrorTracker = Map<string, Map<string, number>>;
440
454
  type SeenFiles = Map<string, string>;
441
455
 
@@ -477,6 +491,13 @@ export class LoopAgent {
477
491
  private autoCompact: AutoCompact;
478
492
  private autoCompactCharThreshold: number;
479
493
  private autoCompactTokenThreshold?: number;
494
+ private autoCompactEnabled: boolean;
495
+ private pruneEnabled: boolean;
496
+ private requestCacheScope?: string;
497
+ private localPruneGate = new PruneGate();
498
+ private localRequestCacheTracker = new RequestCacheTracker();
499
+ private compactTransientMessages: Message[] = [];
500
+ private protectedUserText?: string;
480
501
  private storageSessionId: string;
481
502
  private storageProjectCwd: string;
482
503
  private sessionId: string;
@@ -488,6 +509,7 @@ export class LoopAgent {
488
509
  // via lambda to defer `this.emitter` capture until after construction.
489
510
  private reactiveCompact = new ReactiveCompact({
490
511
  onRetry: (detail) => {
512
+ this.requestCacheTracker.markMaintenance("recovery");
491
513
  this.emitter.emit({
492
514
  type: "observation",
493
515
  kind: "reactive_compact",
@@ -556,6 +578,9 @@ export class LoopAgent {
556
578
  keepRecent: 10,
557
579
  });
558
580
  this.autoCompactTokenThreshold = options.autoCompactTokenThreshold;
581
+ this.autoCompactEnabled = options.autoCompactEnabled ?? true;
582
+ this.pruneEnabled = options.pruneEnabled ?? false;
583
+ this.requestCacheScope = options.requestCacheScope;
559
584
  this.storageSessionId = options.storageSessionId ?? randomUUID();
560
585
  this.storageProjectCwd = options.storageProjectCwd ?? process.cwd();
561
586
  this.sessionId = options.sessionId ?? "default";
@@ -610,6 +635,9 @@ export class LoopAgent {
610
635
  maxSteps: this.maxSteps, budget: this.budget, fallbackProvider: this.fallbackProvider,
611
636
  contextWindow: this.contextWindow, inputTokenLimit: this.inputTokenLimit,
612
637
  outputTokenCeiling: this.outputTokenCeiling, reservedOutputTokens: this.reservedOutputTokens,
638
+ autoCompactEnabled: this.autoCompactEnabled,
639
+ pruneEnabled: this.pruneEnabled,
640
+ requestCacheScope: this.requestCacheScope,
613
641
  storageProjectCwd: this.storageProjectCwd,
614
642
  subagent: options.subagent, factory: options.subagentFactory,
615
643
  promptProfile: options.promptProfile,
@@ -683,6 +711,7 @@ export class LoopAgent {
683
711
  private resultSchema: "outcome-v1" | "legacy" = "legacy";
684
712
 
685
713
  async run(input: string, options?: RunOptions): Promise<LoopAgentResult> {
714
+ this.protectedUserText = input;
686
715
  this.resultSchema = options?.resultSchema ?? "legacy";
687
716
  const signal = options?.signal;
688
717
  const allToolResults: ToolResult[] = [];
@@ -818,7 +847,14 @@ export class LoopAgent {
818
847
  // getMessagesRaw returns the budgeted provider view of the persistent
819
848
  // conversation, excluding transient per-turn context.
820
849
  const getMessagesRaw: GetMessages = () => {
821
- return this.conversation ? this.conversation.getMessages() : localMessages;
850
+ if (!this.conversation) return localMessages;
851
+ const view = this.conversation.getMessages();
852
+ // A bounded view must never silently omit this run's user intent. Fall
853
+ // back to backing history so normal admission/recovery can decide safely.
854
+ if (this.contextWindow && !view.some(message => message.role === "user" && message.content === input)) {
855
+ return this.conversation.getAllMessages();
856
+ }
857
+ return view;
822
858
  };
823
859
 
824
860
  // getMessagesForMaintenance returns the full persisted conversation,
@@ -901,11 +937,11 @@ export class LoopAgent {
901
937
  return [...providerMessages, transientView(deltaMessage)];
902
938
  };
903
939
 
904
- const replaceMessages: ReplaceMessages = (msgs) => {
940
+ const replaceMessages: ReplaceMessages = (msgs, expectedRevision) => {
905
941
  contextInsertionIndex = rebaseMessageBoundary(getMessagesForMaintenance(), msgs, contextInsertionIndex);
906
942
  if (this.conversation) {
907
- this.conversation.clear();
908
- msgs.forEach((m) => this.conversation!.add(m));
943
+ const revision = expectedRevision ?? this.conversation.getSnapshot().revision;
944
+ if (!this.conversation.compareAndReplace(msgs, revision)) throw new Error("Context revision conflict");
909
945
  } else {
910
946
  localMessages = msgs;
911
947
  }
@@ -914,6 +950,7 @@ export class LoopAgent {
914
950
  let revision: string | undefined;
915
951
  let canonical: Message[] = [];
916
952
  return {
953
+ protectedUserText: input,
917
954
  recoveryMessages: () => {
918
955
  canonical = getMessagesForMaintenance();
919
956
  revision = contextFingerprint(canonical);
@@ -1067,7 +1104,13 @@ export class LoopAgent {
1067
1104
  workspaceChanged,
1068
1105
  timeBudget: this.runtimeTimeBudget(startedAt),
1069
1106
  }, addMessage, budgetHints);
1070
- await this.tryAutoCompact(state, getMessagesForMaintenance, replaceMessages, { signal, startedAt });
1107
+ // Capture the actual schemas/transient messages before maintenance.
1108
+ // Full backing history, not a truncated provider view, is summarized.
1109
+ const maintenanceRequest = getMessages();
1110
+ this.compactTransientMessages = maintenanceRequest.filter(message => message.cache?.transient);
1111
+ this.conversation?.setCompactionContext(this.compactOptions(tools));
1112
+ let maintenanceChanged = await this.tryPrune(getMessagesForMaintenance, replaceMessages, { signal, startedAt, protectedUserText: input });
1113
+ maintenanceChanged = await this.tryAutoCompact(state, getMessagesForMaintenance, replaceMessages, { signal, startedAt, protectedUserText: input }) || maintenanceChanged;
1071
1114
 
1072
1115
  // Maintenance may await a remote summarizer past cancellation or the
1073
1116
  // finalization deadline. Do not claim pending input after either one.
@@ -1089,13 +1132,14 @@ export class LoopAgent {
1089
1132
  const message = createUserMessage(input.text, input.images);
1090
1133
  message.cache = { skipBreakpoint: true };
1091
1134
  addMessage(message);
1135
+ maintenanceChanged = true;
1092
1136
  acceptedSteeringIds.add(input.id);
1093
1137
  }
1094
1138
  options.onSteeringAccepted?.(input);
1095
1139
  }
1096
1140
  }
1097
1141
 
1098
- const messages = getMessages();
1142
+ const messages = maintenanceChanged ? getMessages() : maintenanceRequest;
1099
1143
  this.emitter.emit({
1100
1144
  type: "run_step",
1101
1145
  step: steps + 1,
@@ -1130,7 +1174,7 @@ export class LoopAgent {
1130
1174
  state,
1131
1175
  getMessagesForMaintenance,
1132
1176
  replaceMessages,
1133
- { force: true, signal: stepSignal, startedAt },
1177
+ { force: true, signal: stepSignal, startedAt, protectedUserText: input },
1134
1178
  );
1135
1179
  if (stepDeadline.timedOut() && !signal?.aborted) {
1136
1180
  stopped = "timeout";
@@ -1760,14 +1804,55 @@ export class LoopAgent {
1760
1804
  return decision;
1761
1805
  }
1762
1806
 
1807
+ /** One maintenance boundary after complete tool groups, before provider I/O. */
1808
+ private async tryPrune(getMessages: GetMessages, replaceMessages: ReplaceMessages,
1809
+ options: { signal?: AbortSignal; startedAt: number; protectedUserText?: string }): Promise<boolean> {
1810
+ if (!this.pruneEnabled) return false;
1811
+ const snapshot = this.conversation?.getSnapshot();
1812
+ const messages = snapshot?.messages ?? structuredClone(getMessages());
1813
+ const budget = compactBudget(this.compactOptions());
1814
+ const compactOptions = { ...this.compactOptions(), ...(budget ? { triggerAtTokens: this.autoCompactTokenThreshold ?? budget.compactAt, charThreshold: undefined } : {}), protectedUserText: options.protectedUserText, signal: options.signal };
1815
+ if (!compactDecision(messages, { ...compactOptions, autoEnabled: true }).shouldCompact) return false;
1816
+ const beforeHash = contextFingerprint(messages);
1817
+ const decision = compactDecision(messages, { ...compactOptions, autoEnabled: true });
1818
+ const threshold = compactOptions.triggerAtTokens ?? Math.floor((compactOptions.charThreshold ?? 320000) / 4);
1819
+ const gate = this.conversation?.pruneGate ?? this.localPruneGate;
1820
+ if (!gate.canAttempt(beforeHash, decision.tokens, threshold, budget?.effectiveInputLimit)) return false;
1821
+ this.emitter.emit({ type: "observation", kind: "prune_start", detail: { reason: "context_pressure" } });
1822
+ // Yield once so a pending cancellation or steering update can win the CAS.
1823
+ await Promise.resolve();
1824
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("Prune cancelled");
1825
+ if (this.progressController.shouldReserveFinalization(options.startedAt)) return false;
1826
+ const result = planPrune(messages, compactOptions);
1827
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("Prune cancelled");
1828
+ if (this.progressController.shouldReserveFinalization(options.startedAt)) return false;
1829
+ if (result.status !== "pruned") {
1830
+ if (contextFingerprint(getMessages()) === beforeHash) gate.record(beforeHash, result.outputTokens, threshold);
1831
+ this.emitter.emit({ type: "observation", kind: "prune_skipped", detail: { reason: result.status } });
1832
+ return false;
1833
+ }
1834
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("Prune cancelled");
1835
+ if (contextFingerprint(getMessages()) !== beforeHash) {
1836
+ this.emitter.emit({ type: "observation", kind: "prune_skipped", detail: { reason: "revision_conflict" } });
1837
+ return false;
1838
+ }
1839
+ replaceMessages(result.messages, snapshot?.revision);
1840
+ this.requestCacheTracker.markMaintenance("prune");
1841
+ gate.record(result.afterHash, result.outputTokens, threshold);
1842
+ const { messages: _messages, ...detail } = result;
1843
+ this.emitter.emit({ type: "observation", kind: "prune_done", detail: { ...detail, reason: "context_pressure" } });
1844
+ return true;
1845
+ }
1846
+
1763
1847
  /** Run AutoCompact if the context is large enough and has grown meaningfully
1764
1848
  * since the previous attempt. Returns true when a compact attempt happened. */
1765
1849
  private async tryAutoCompact(
1766
1850
  state: LoopState,
1767
1851
  getMessages: GetMessages,
1768
1852
  replaceMessages: ReplaceMessages,
1769
- options: { force?: boolean; signal?: AbortSignal; startedAt?: number } = {},
1853
+ options: { force?: boolean; signal?: AbortSignal; startedAt?: number; protectedUserText?: string } = {},
1770
1854
  ): Promise<boolean> {
1855
+ if (!options.force && !this.autoCompactEnabled) return false;
1771
1856
  // Circuit breaker: after N consecutive failures, stop trying. Otherwise
1772
1857
  // a flaky summarizer wedges the agent in an infinite "try to compact,
1773
1858
  // fail, hit ceiling again" loop.
@@ -1776,19 +1861,18 @@ export class LoopAgent {
1776
1861
  }
1777
1862
 
1778
1863
  const msgs = getMessages();
1864
+ const snapshot = this.conversation?.getSnapshot();
1865
+ const originalFingerprint = contextFingerprint(msgs);
1779
1866
 
1780
1867
  // Char threshold catches English-heavy / code conversations; the
1781
1868
  // token threshold catches CJK-heavy conversations where 1 token can be
1782
1869
  // <2 chars — without the second check, Chinese conversations hit the
1783
1870
  // model's real token ceiling before the char threshold trips, and the
1784
1871
  // next API call fails with `context length exceeded`.
1785
- const byChars = this.autoCompact.shouldCompact(msgs);
1786
- const tokenEstimate = this.currentAutoCompactTokenEstimate(msgs);
1787
- const byTokens =
1788
- this.autoCompactTokenThreshold !== undefined &&
1789
- tokenEstimate > this.autoCompactTokenThreshold;
1790
-
1791
- if (!options.force && !byChars && !byTokens) return false;
1872
+ const compactOptions = this.compactOptions();
1873
+ const decision = compactDecision(msgs, { ...compactOptions, force: options.force });
1874
+ const tokenEstimate = decision.tokens;
1875
+ if (!decision.shouldCompact) return false;
1792
1876
  if (!this.shouldAttemptAutoCompactAgain(state, tokenEstimate, this.autoCompact.totalChars(msgs))) {
1793
1877
  return false;
1794
1878
  }
@@ -1801,31 +1885,38 @@ export class LoopAgent {
1801
1885
  this.emitter.emit({
1802
1886
  type: "observation",
1803
1887
  kind: "autocompact_start",
1804
- detail: { charCount, tokenEstimate, messageCount, trigger: byTokens ? "tokens" : "chars" },
1888
+ detail: { charCount, tokenEstimate, messageCount, trigger: decision.trigger },
1805
1889
  });
1806
1890
 
1807
1891
  const deadline = options.startedAt === undefined ? undefined : this.createStepDeadlineSignal(options.startedAt, options.signal);
1808
1892
  const compactSignal = deadline?.signal ?? options.signal;
1809
1893
  try {
1810
- const { messages: compacted, summary, failureReason } = await this.autoCompact.compact(
1894
+ const result = await this.autoCompact.compact(
1811
1895
  msgs,
1812
1896
  this.meterProvider(this.summarizer ?? this.provider, "maintenance"),
1813
1897
  { signal: compactSignal, deadline: compactSignal ? this.providerDeadlines.get(compactSignal) : undefined },
1898
+ { ...compactOptions, force: options.force, protectedUserText: options.protectedUserText },
1814
1899
  );
1900
+ const { messages: finalMessages, summary, failureReason } = result;
1901
+ if (result.status === "needs_input_reduction") {
1902
+ const plan = planCompact(msgs, compactOptions);
1903
+ const withoutTransient = compactRequestTokens([...plan.system, ...plan.retained],
1904
+ { ...compactOptions, transientMessages: [] }, this.budgetTokenCounter);
1905
+ // Oversized host context can still use the existing transient-only
1906
+ // recovery route. Protected user/tool content may never take that route.
1907
+ if (this.compactTransientMessages.length && plan.hardLimit !== undefined && withoutTransient <= plan.hardLimit) {
1908
+ throw new Error("Transient host context requires bounded request recovery");
1909
+ }
1910
+ throw new CompactInputReductionError(failureReason);
1911
+ }
1815
1912
  if (!summary.trim()) {
1816
1913
  throw new Error(failureReason ?? "autocompact produced no usable summary");
1817
1914
  }
1818
1915
 
1819
- // Reuse successful historical read results within remaining headroom.
1820
- // Fresh filesystem reads always go through the authorized tool boundary.
1821
- const restored = await restoreRecentFiles(msgs, { counter: this.budgetTokenCounter,
1822
- maxTokens: Math.min(2048, Math.max(0, (this.autoCompactTokenThreshold ?? this.contextWindow ?? 0)
1823
- - this.reservedOutputTokens - this.budgetTokenCounter.countMessages(compacted))) });
1824
- const finalMessages = restored
1825
- ? [...compacted, createRunLocalUserMessage(restored)]
1826
- : compacted;
1827
-
1828
- replaceMessages(finalMessages);
1916
+ if (compactSignal?.aborted) throw compactSignal.reason ?? new Error("Compact cancelled");
1917
+ if (contextFingerprint(getMessages()) !== originalFingerprint) throw new Error("Context changed during compaction (revision conflict)");
1918
+ replaceMessages(finalMessages, snapshot?.revision);
1919
+ this.requestCacheTracker.markMaintenance("summary");
1829
1920
  state.lastAutoCompactAfterTokens = this.currentAutoCompactTokenEstimate(finalMessages);
1830
1921
  state.lastAutoCompactAfterChars = this.autoCompact.totalChars(finalMessages);
1831
1922
  state.consecutiveAutoCompactFailures = 0; // success — reset breaker
@@ -1836,7 +1927,9 @@ export class LoopAgent {
1836
1927
  summary,
1837
1928
  messagesBefore: messageCount,
1838
1929
  messagesAfter: finalMessages.length,
1839
- filesRestored: restored ? (restored.match(/^### /gm)?.length ?? 0) : 0,
1930
+ filesRestored: result.filesRestored ?? 0,
1931
+ status: result.status, inputTokens: result.inputTokens, outputTokens: result.outputTokens,
1932
+ sourceTruncated: result.sourceTruncated,
1840
1933
  },
1841
1934
  });
1842
1935
  } catch (err) {
@@ -1857,6 +1950,7 @@ export class LoopAgent {
1857
1950
  state.consecutiveAutoCompactFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES,
1858
1951
  },
1859
1952
  });
1953
+ if (err instanceof CompactInputReductionError) throw err;
1860
1954
  // Don't re-throw — let the next LLM call try, possibly hitting
1861
1955
  // ReactiveCompact as a last resort.
1862
1956
  } finally {
@@ -1891,9 +1985,10 @@ export class LoopAgent {
1891
1985
  replaceMessages: ReplaceMessages,
1892
1986
  ): boolean {
1893
1987
  const before = getMessagesForMaintenance();
1894
- const { messages: compacted, compacted: didCompact } = this.reactiveCompact.compactMessages(before, this.budgetTokenCounter);
1988
+ const { messages: compacted, compacted: didCompact } = this.reactiveCompact.compactMessages(before, this.budgetTokenCounter, this.protectedUserText);
1895
1989
  if (!didCompact) return false;
1896
1990
  replaceMessages(compacted);
1991
+ this.requestCacheTracker.markMaintenance("recovery");
1897
1992
  this.emitter.emit({
1898
1993
  type: "observation",
1899
1994
  kind: "reactive_compact",
@@ -1922,7 +2017,7 @@ export class LoopAgent {
1922
2017
  }
1923
2018
 
1924
2019
  const providerView = getMessages();
1925
- const { messages: compacted, compacted: didCompact } = this.reactiveCompact.compactMessages(providerView, this.budgetTokenCounter);
2020
+ const { messages: compacted, compacted: didCompact } = this.reactiveCompact.compactMessages(providerView, this.budgetTokenCounter, this.protectedUserText);
1926
2021
  if (!didCompact) return null;
1927
2022
  this.emitter.emit({
1928
2023
  type: "observation",
@@ -1935,13 +2030,31 @@ export class LoopAgent {
1935
2030
  charsAfter: this.autoCompact.totalChars(compacted),
1936
2031
  },
1937
2032
  });
2033
+ this.requestCacheTracker.markMaintenance("recovery");
1938
2034
  const result = await this.streamWithTools(compacted, tools, steps, signal, executionHooks);
1939
2035
  this.retainTransientRecovery?.(providerView, compacted);
1940
2036
  return result;
1941
2037
  }
1942
2038
 
2039
+ private get requestCacheTracker(): RequestCacheTracker {
2040
+ return this.conversation?.requestCacheTracker ?? this.localRequestCacheTracker;
2041
+ }
2042
+
1943
2043
  private currentAutoCompactTokenEstimate(messages: Message[]): number {
1944
- return this.conversation?.estimatedTokens ?? this.budgetTokenCounter.countMessages(messages);
2044
+ return compactRequestTokens(messages, this.compactOptions(), this.budgetTokenCounter);
2045
+ }
2046
+
2047
+ private compactOptions(tools = this.registry.definitions()): CompactOptions {
2048
+ const limits = { contextWindow: this.contextWindow, inputTokenLimit: this.inputTokenLimit,
2049
+ reservedOutputTokens: this.reservedOutputTokens, outputTokenCeiling: this.outputTokenCeiling };
2050
+ const budget = compactBudget(limits);
2051
+ const triggerTarget = this.autoCompactTokenThreshold !== undefined
2052
+ ? Math.floor(this.autoCompactTokenThreshold * 0.5) : Math.floor(this.autoCompactCharThreshold / 8);
2053
+ return { ...limits, counter: this.budgetTokenCounter, tools,
2054
+ triggerAtTokens: this.autoCompactTokenThreshold, charThreshold: this.autoCompactCharThreshold,
2055
+ autoEnabled: this.autoCompactEnabled,
2056
+ transientMessages: this.compactTransientMessages,
2057
+ targetTokens: budget ? Math.min(budget.keepFloorTokens, Math.max(1, triggerTarget)) : undefined, restoreFiles: true };
1945
2058
  }
1946
2059
 
1947
2060
  /**
@@ -2126,8 +2239,14 @@ export class LoopAgent {
2126
2239
 
2127
2240
  private providerCallOptions(step: number, maxOutputTokens: number | undefined, signal?: AbortSignal): LLMCallOptions {
2128
2241
  const requestId = nextContentId("request");
2242
+ let observedAttempt: number | undefined;
2129
2243
  const options: LLMCallOptions = { maxOutputTokens, signal,
2130
2244
  deadline: signal ? this.providerDeadlines.get(signal) : undefined, onRequestEvent: request => {
2245
+ if (request.cacheShape && observedAttempt !== request.attempt) {
2246
+ observedAttempt = request.attempt;
2247
+ const detail = this.requestCacheTracker.observe(scopeRequestCacheShape(request.cacheShape, this.requestCacheScope));
2248
+ this.emitter.emit({ type: "observation", kind: "request_cache_shape", detail: { ...detail } });
2249
+ }
2131
2250
  this.emitter.emit({ type: "provider_request", step, requestId, request });
2132
2251
  } };
2133
2252
  assertProviderRequestAllowed(options);
@@ -2466,7 +2585,7 @@ export class LoopAgent {
2466
2585
  * the (400 + json) heuristic and got mis-labeled as context overflow,
2467
2586
  * triggering a useless compaction retry that always fails the same way. */
2468
2587
  private isContextError(err: unknown): boolean {
2469
- if (err instanceof RequestRecoveryError) return false;
2588
+ if (err instanceof RequestRecoveryError || err instanceof CompactInputReductionError) return false;
2470
2589
  if (err instanceof ContextOverflowError) return true;
2471
2590
  const msg = err instanceof Error ? err.message : String(err);
2472
2591
  return isLikelyContextLimitErrorMessage(msg);
@@ -49,6 +49,9 @@ export function assembleSubagentTool(input: AssemblyInput): { registry: ToolRegi
49
49
  inputTokenLimit: input.inputTokenLimit,
50
50
  outputTokenCeiling: input.outputTokenCeiling,
51
51
  reservedOutputTokens: input.reservedOutputTokens,
52
+ autoCompactEnabled: input.autoCompactEnabled,
53
+ pruneEnabled: input.pruneEnabled,
54
+ requestCacheScope: input.requestCacheScope,
52
55
  storageProjectCwd: input.storageProjectCwd,
53
56
  workspaceManager: config.workspaceManager,
54
57
  mergeCoordinator: config.mergeCoordinator,
@@ -24,6 +24,8 @@ export interface ExecuteCommandOptions {
24
24
  * launch an interpreter; the execution broker owns that decision. */
25
25
  executionShell?: string;
26
26
  sandboxTemporaryDirectory?: ExecutionEnvironmentFacts["sandboxTemporaryDirectory"];
27
+ /** Host advertises its scoped, sandboxed root Git adapter. */
28
+ sandboxGitIntegration?: boolean;
27
29
  /** Inject a shared TaskStore to enable the `run_in_background:true`
28
30
  * flag. When omitted (or when `ZAPCODE_DISABLE_BACKGROUND_TASKS=1` is
29
31
  * set), background fields are stripped from the schema entirely — the
@@ -243,6 +245,9 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
243
245
  "Exit 0 reports final shell status only. Inspect stderr for warnings or masked failures; do not auto-replay side effects. Chain dependencies with &&. Pipelines report the last stage: check stages or use supported pipefail. Use check_steps for independent checks; each uses a fresh shell and stops on nonzero.",
244
246
  "cwd selects the starting directory, not a narrower workspace. For external inputs/outputs declare read_paths/write_paths (relative to cwd); these need file authorization. A prior Read alone does not grant Bash access. Sandboxed .git/.zapcode remain read-only.",
245
247
  );
248
+ if (options.sandboxGitIntegration) {
249
+ promptLines.push("For root-repository Git writes, use standalone Bash calls: git add <paths>, git commit -m <message>, git stash push/pop, git rebase <ref>. The Host runs supported commands using trusted Git inside the OS sandbox. Do not combine them with &&, cd, redirects, -c/-C or interactive options. Arbitrary shell writes to .git remain blocked; unsupported or executable Git config retains the normal approval path.");
250
+ }
246
251
  if (options.sandboxTemporaryDirectory) {
247
252
  promptLines.push(
248
253
  `Local sandbox: expand ${options.sandboxTemporaryDirectory.environmentVariables.join(", ")} for a private writable scratch directory; avoid hard-coded /tmp or disposable project files.`,
@@ -61,6 +61,9 @@ export interface SubagentToolOptions {
61
61
  /** Char threshold for auto-compaction inside the subagent run. Defaults
62
62
  * to 200_000 chars (~50k tokens). Set to 0 to disable. */
63
63
  subagentAutoCompactThreshold?: number;
64
+ autoCompactEnabled?: boolean;
65
+ pruneEnabled?: boolean;
66
+ requestCacheScope?: string;
64
67
  /** Context window + ceiling inherited from parent LoopAgent for per-call
65
68
  * budget planning. Subagents typically use a narrower slice of the full
66
69
  * context but the absolute bounds are shared with the parent provider. */
@@ -835,6 +838,9 @@ function createDirectSubagentTool(options: SubagentToolOptions): Tool {
835
838
  // Char-based autocompact inside the subagent so long explorations
836
839
  // with big file reads don't blow past the context window. 0 disables.
837
840
  autoCompactThreshold: autoCompactThreshold > 0 ? autoCompactThreshold : undefined,
841
+ autoCompactEnabled: options.autoCompactEnabled !== false && autoCompactThreshold > 0,
842
+ pruneEnabled: options.pruneEnabled ?? false,
843
+ requestCacheScope: options.requestCacheScope,
838
844
  });
839
845
 
840
846
  if (options.onEvent) {