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 { prepareRootGit } from "./root-git.js";
1
2
  import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
2
3
  import { homedir, tmpdir } from "node:os";
3
4
  import { delimiter, dirname, join, resolve } from "node:path";
@@ -10,7 +11,7 @@ import type {
10
11
  } from "./types.js";
11
12
  import { WINDOWS_APPCONTAINER_HELPER } from "./windows-appcontainer.js";
12
13
  import { localExecutionShell } from "./shell.js";
13
- import { linkedWorktreeReadRoots, privateGitWriteRoot, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
+ import { linkedWorktreeReadRoots, privateGitWriteRoot, integrationGitWriteRoots, macToolShimPath, workspaceRuntimeDirectory, workspaceRuntimeEnvironment, workspaceRuntimeTemporaryDirectory } from "./workspace-runtime.js";
14
15
  import { NODE_PROXY_PRELOAD } from "./node-proxy-preload.generated.js";
15
16
  import { ExecutionBoundaryError, operationFailure } from "./failure.js";
16
17
 
@@ -23,6 +24,9 @@ export interface PlatformSandboxOptions {
23
24
  /** Host-owned, workspace-scoped home/cache/scratch. Omitted for strict,
24
25
  * stateless SDK sandboxes and remote runtimes. */
25
26
  workspaceStateRoot?: string;
27
+ /** Trusted Host opt-in for strictly parsed single Git commands in an authorized root workspace.
28
+ * Never applies to readonly/shared or isolated child workspaces. */
29
+ rootWorkspaceGitWrites?: boolean;
26
30
  /** Embedder-owned paths that stay writable inside the process sandbox.
27
31
  * These are not derived from model/tool grants and must only be supplied by
28
32
  * a trusted runtime boundary such as a per-Computer persistent tool store. */
@@ -63,6 +67,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
63
67
  trustedEnvironmentNames: string[] = [],
64
68
  networkProxy?: NetworkProxy | (() => NetworkProxy | undefined),
65
69
  workspaceStateRoot?: string,
70
+ private readonly rootWorkspaceGitWrites = false,
66
71
  ) {
67
72
  this.networkProxy = networkProxy;
68
73
  this.workspaceStateRoot = workspaceStateRoot;
@@ -86,7 +91,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
86
91
  },
87
92
  ): { executable: string; args: string[]; release?: () => void };
88
93
 
89
- createContext(input: Parameters<OsSandbox["createContext"]>[0]): SandboxExecutionContext {
94
+ createContext(input: Parameters<OsSandbox["createContext"]>[0], gitOperation = false): SandboxExecutionContext {
90
95
  const status = this.status();
91
96
  if (!status.available || status.provider === "none") {
92
97
  throw new Error(status.reason ?? "OS sandbox is unavailable");
@@ -95,10 +100,14 @@ abstract class CommandWrappingSandbox implements OsSandbox {
95
100
  ? workspaceRuntimeDirectory(this.workspaceStateRoot, input.workspace.root) : undefined;
96
101
  const runtimeTemp = runtimeDirectory ? workspaceRuntimeTemporaryDirectory(runtimeDirectory) : undefined;
97
102
  const privateGit = privateGitWriteRoot(input.workspace);
103
+ const rootGit = gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
104
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))
105
+ ? integrationGitWriteRoots(input.workspace.root) : [];
98
106
  const writablePaths = [...new Set([
99
107
  ...(input.grant.filesystem?.write ?? []),
100
108
  ...this.trustedWritablePaths,
101
109
  ...(privateGit ? [privateGit] : []),
110
+ ...rootGit,
102
111
  ...(runtimeDirectory ? [runtimeDirectory] : []),
103
112
  ...(runtimeTemp ? [runtimeTemp] : []),
104
113
  ].map((path) => canonicalPath(resolve(input.workspace.root, path))))];
@@ -114,7 +123,7 @@ abstract class CommandWrappingSandbox implements OsSandbox {
114
123
  && input.grant.filesystem?.write.some(path => canonicalPath(path) === canonicalPath(join(input.workspace.root, ".git")));
115
124
  const protectedPaths = [".git", ".zapcode"]
116
125
  .map((name) => canonicalPath(resolve(input.workspace.root, name)))
117
- .filter((path) => path !== privateGit && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
126
+ .filter((path) => path !== privateGit && !rootGit.includes(path) && !(integrationGit && path === canonicalPath(join(input.workspace.root, ".git"))));
118
127
  const provider = status.provider;
119
128
  const prepare = (
120
129
  executable: string,
@@ -184,6 +193,20 @@ abstract class CommandWrappingSandbox implements OsSandbox {
184
193
  networkAllowed,
185
194
  prepareCommand: prepare,
186
195
  prepareShell: (command, options) => {
196
+ if (!gitOperation && this.rootWorkspaceGitWrites && input.workspace.mode === "root"
197
+ && input.grant.filesystem?.write.some(path => canonicalPath(resolve(input.workspace.root, path)) === canonicalPath(input.workspace.root))) {
198
+ let git: ReturnType<typeof prepareRootGit>;
199
+ try { git = prepareRootGit(command, input.workspace.root, options.cwd); } catch { /* Unsupported repository: retain normal sandbox protection. */ }
200
+ if (git) {
201
+ const prepared = this.createContext(input, true).prepareCommand(git.executable, git.args, { ...options, environment: {} });
202
+ // Remove inherited GIT_* overrides after normal sandbox environment
203
+ // construction; untrusted tool environment cannot redirect Git.
204
+ if (process.platform !== "win32") prepared.env.PATH = `${dirname(git.executable)}:/usr/bin:/bin:/usr/sbin:/sbin`;
205
+ for (const key of Object.keys(prepared.env)) if (/^GIT_/i.test(key)) delete prepared.env[key];
206
+ for (const [key, value] of Object.entries(git.environment)) if (/^GIT_/i.test(key)) prepared.env[key] = value;
207
+ return prepared;
208
+ }
209
+ }
187
210
  const { executable, argsPrefix } = localExecutionShell();
188
211
  return prepare(executable, [...argsPrefix, command], options);
189
212
  },
@@ -196,7 +219,7 @@ class MacOsSeatbeltSandbox extends CommandWrappingSandbox {
196
219
  protected override readonly enforcesNetworkProxy = true;
197
220
 
198
221
  constructor(options: PlatformSandboxOptions) {
199
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot);
222
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, options.networkProxy, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
200
223
  this.executable = options.sandboxExecPath ?? "/usr/bin/sandbox-exec";
201
224
  }
202
225
 
@@ -264,7 +287,7 @@ class LinuxBubblewrapSandbox extends CommandWrappingSandbox {
264
287
  private readonly executable: string;
265
288
 
266
289
  constructor(options: PlatformSandboxOptions) {
267
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
290
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
268
291
  this.executable = options.bwrapPath ?? findOnPath("bwrap") ?? "bwrap";
269
292
  }
270
293
 
@@ -366,7 +389,7 @@ class WindowsHelperSandbox extends CommandWrappingSandbox {
366
389
  private readonly trace: boolean;
367
390
 
368
391
  constructor(options: PlatformSandboxOptions) {
369
- super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot);
392
+ super(options.tempRoot, options.trustedWritablePaths, options.trustedEnvironmentNames, undefined, options.workspaceStateRoot, options.rootWorkspaceGitWrites);
370
393
  this.executable = options.windowsHelperPath
371
394
  ?? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
372
395
  this.trace = options.trace === true;
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";
@@ -1,9 +1,13 @@
1
+ import { PruneGate } from "../context/prune.js";
2
+ import { RequestCacheTracker } from "../context/request-cache.js";
1
3
  import type { Message, ToolCallRequest } from "../core/types.js";
2
4
  import type { LLMProvider } from "../core/llm.js";
3
5
  import { HistoricalImageRetention, type HistoricalImagePolicy } from "../context/historical-images.js";
4
6
  import { mergeRecoveredProviderView } from "../context/request-recovery.js";
5
7
  import { TokenCounter } from "../context/token-counter.js";
6
- import { STRUCTURED_COMPACT_PROMPT, compactSummaryFailureReason, previewMessageForCompact, sanitizeCompactSummary } from "../context/autocompact.js";
8
+ import { compactDecision, executeCompact, type CompactOptions, type CompactResult } from "../context/compact.js";
9
+ import { contextFingerprint } from "../context/request-recovery.js";
10
+ import { compactBudget } from "../context/compact-budget.js";
7
11
  import {
8
12
  type Turn,
9
13
  type CompletedCall,
@@ -19,6 +23,11 @@ export interface CompressResult {
19
23
  before: number;
20
24
  /** Surviving non-system messages (tail kept), excluding the new summary message. */
21
25
  after: number;
26
+ status?: CompactResult["status"];
27
+ inputTokens?: number;
28
+ outputTokens?: number;
29
+ filesRestored?: number;
30
+ sourceTruncated?: boolean;
22
31
  }
23
32
 
24
33
  export interface ConversationManagerOptions {
@@ -46,7 +55,7 @@ export interface ConversationManagerOptions {
46
55
  autoCompress?: boolean;
47
56
  }
48
57
 
49
- interface CompressOptions {
58
+ export interface CompressOptions extends CompactOptions {
50
59
  force?: boolean;
51
60
  targetTokens?: number;
52
61
  signal?: AbortSignal;
@@ -79,6 +88,10 @@ interface PendingToolTurn {
79
88
  * to keep these in sync" bugs (issue #12 was one of them).
80
89
  */
81
90
  export class ConversationManager {
91
+ private revision = 0;
92
+ readonly pruneGate = new PruneGate();
93
+ readonly requestCacheTracker = new RequestCacheTracker();
94
+ private compactionContext: CompactOptions = {};
82
95
  private turns: Turn[] = [];
83
96
  private pending: PendingToolTurn | null = null;
84
97
  /** Recovery keeps omitted history readable without reintroducing it into requests. */
@@ -374,114 +387,85 @@ export class ConversationManager {
374
387
  return this._lastCompressionFailureReason;
375
388
  }
376
389
 
390
+ /** Request metadata only, never changes/persists conversation contents. */
391
+ setCompactionContext(context: CompactOptions): void {
392
+ this.compactionContext = { ...context, transientMessages: structuredClone(context.transientMessages ?? []) };
393
+ }
394
+
395
+ getCompactionContext(): CompactOptions {
396
+ return { ...this.compactionContext, tools: this.compactionContext.tools?.slice(),
397
+ transientMessages: structuredClone(this.compactionContext.transientMessages ?? []) };
398
+ }
399
+
400
+ getSnapshot(): { messages: Message[]; revision: number } {
401
+ this.flushPending();
402
+ return { messages: structuredClone(this.getAllMessages()), revision: this.revision };
403
+ }
404
+
405
+ compareAndReplace(messages: Message[], expectedRevision: number, counter = this.counter): boolean {
406
+ this.flushPending();
407
+ if (this.revision !== expectedRevision) return false;
408
+ const turns = rederiveTurns(messages);
409
+ const tokens = counter.countMessages(turnsToMessages(turns));
410
+ this.turns = turns;
411
+ this.counter = counter;
412
+ this.providerViewFloor = 0;
413
+ this.historicalImages?.reset();
414
+ this._estimatedTokens = tokens;
415
+ this.revision++;
416
+ return true;
417
+ }
418
+
377
419
  /**
378
420
  * Compress conversation by LLM summarization. Keeps the most recent turns
379
421
  * whose total token count fits under `targetTokens` (defaults to
380
422
  * `targetTokensAfterCompress`, which defaults to 50% of the trigger);
381
423
  * earlier turns become a single summary turn.
382
424
  */
383
- async compress(
384
- provider?: LLMProvider,
385
- options: CompressOptions = {},
386
- ): Promise<CompressResult | null> {
425
+ async compress(provider?: LLMProvider, options: CompressOptions = {}): Promise<CompressResult | null> {
387
426
  this.flushPending();
388
427
  this._lastCompressionFailureReason = undefined;
389
-
390
- const force = options.force ?? false;
391
- const targetTokens = nonNegativeInteger(options.targetTokens)
392
- ?? this.targetTokensAfterCompress
393
- ?? (this.triggerAtTokens ? Math.floor(this.triggerAtTokens * 0.5) : undefined);
394
-
395
428
  const summarizer = provider ?? this.summarizer;
396
429
  if (!summarizer) return null;
397
-
398
- const allMessages = turnsToMessages(this.turns);
399
-
400
- const overMessages = allMessages.length > this.maxMessages;
401
- const overTokens = this.maxTokens ? this._estimatedTokens > this.maxTokens : false;
402
- const overSoftTrigger = this.triggerAtTokens ? this._estimatedTokens > this.triggerAtTokens : false;
403
-
404
- if (!force && !overMessages && !overTokens && !overSoftTrigger) return null;
430
+ const snapshot = this.getSnapshot();
431
+ const context = { ...this.compactionContext, ...options, counter: options.counter ?? this.counter };
432
+ const targetTokens = options.targetTokens ?? this.targetTokensAfterCompress
433
+ ?? compactBudget(context)?.keepFloorTokens
434
+ ?? (this.triggerAtTokens ? Math.floor(this.triggerAtTokens * 0.5) : undefined);
405
435
  if (targetTokens === undefined) return null;
406
-
407
- // Preserve only the leading system prefix. Non-leading system turns are
408
- // historical content and must not be hoisted ahead of earlier user turns.
409
- const { systemTurns, nonSystemTurns: nonSystem } = splitLeadingSystemPrefix(this.turns);
410
-
411
- // Greedy keep-from-tail: include turns at the end while we fit under
412
- // targetTokens. Each turn is treated as an indivisible unit (matches
413
- // the wire-level pairing invariant — never split an assistant from
414
- // its tool_results).
415
- const systemMsgsTokens = systemTurns.reduce((sum, t) => sum + countTurnTokens(this.counter, t), 0);
416
- let keepStart = nonSystem.length;
417
- let keepTokens = systemMsgsTokens;
418
- while (keepStart > 0) {
419
- const next = keepStart - 1;
420
- const t = nonSystem[next];
421
- const tTokens = countTurnTokens(this.counter, t);
422
- if (keepTokens + tTokens > targetTokens) break;
423
- keepStart = next;
424
- keepTokens += tTokens;
425
- }
426
- if (!force && keepStart === nonSystem.length && nonSystem.length > 0) {
427
- keepStart = nonSystem.length - 1;
428
- }
429
- if (force && nonSystem.length > 1) {
430
- const cap = Math.max(0, nonSystem.length - 10);
431
- if (keepStart < cap) keepStart = cap;
432
- }
433
-
434
- const toSummarize = nonSystem.slice(0, keepStart);
435
- const toKeep = nonSystem.slice(keepStart);
436
-
437
- if (toSummarize.length === 0) return null;
438
-
439
- // Convert summarized turns to messages for the LLM input. Counting
440
- // before/after at the message level keeps backward-compat with the
441
- // CompressResult shape consumers display.
442
- const summarizedMsgs = toSummarize.flatMap((t) => turnToMessages(t));
443
- const before = nonSystem.flatMap((t) => turnToMessages(t)).length;
444
-
445
- const historyText = summarizedMsgs
446
- .map((m) => {
447
- const role = m.role === "tool_result" ? "tool_result" : m.role;
448
- return `[${role}]: ${previewMessageForCompact(role, m.content)}`;
449
- })
450
- .join("\n\n");
451
-
452
- let response: Awaited<ReturnType<LLMProvider["call"]>>;
436
+ const over = snapshot.messages.length > this.maxMessages
437
+ || (this.maxTokens !== undefined && this._estimatedTokens > this.maxTokens)
438
+ || (this.triggerAtTokens !== undefined && this._estimatedTokens > this.triggerAtTokens);
439
+ if (context.contextWindow !== undefined) {
440
+ if (!compactDecision(snapshot.messages, { ...context, force: options.force,
441
+ triggerAtTokens: context.triggerAtTokens ?? this.triggerAtTokens }).shouldCompact) return null;
442
+ } else if (!options.force && !over) return null;
443
+ let result: CompactResult;
453
444
  try {
454
- response = await summarizer.call([
455
- { role: "system", content: STRUCTURED_COMPACT_PROMPT },
456
- { role: "user", content: historyText },
457
- ], undefined, { signal: options.signal });
445
+ result = await executeCompact(snapshot.messages, summarizer, { ...context, targetTokens,
446
+ legacyForce: options.force, restoreFiles: context.contextWindow !== undefined && context.restoreFiles !== false });
458
447
  } catch (err) {
459
- const message = err instanceof Error ? err.message : String(err);
460
- this._lastCompressionFailureReason = `summarizer failed: ${message}`;
448
+ this._lastCompressionFailureReason = `summarizer failed: ${err instanceof Error ? err.message : String(err)}`;
461
449
  throw err;
462
450
  }
463
- if (options.signal?.aborted) {
464
- throw options.signal.reason ?? new Error("compression aborted");
451
+ if (!result.summary) {
452
+ this._lastCompressionFailureReason = result.failureReason;
453
+ return null;
465
454
  }
466
- const summary = sanitizeCompactSummary(response.text);
467
- const failureReason = compactSummaryFailureReason(summary);
468
- if (failureReason) {
469
- this._lastCompressionFailureReason = failureReason;
455
+ if (options.signal?.aborted) throw options.signal.reason ?? new Error("compression aborted");
456
+ if (contextFingerprint(this.getAllMessages()) !== contextFingerprint(snapshot.messages)
457
+ || !this.compareAndReplace(result.messages, snapshot.revision, context.counter)) {
458
+ this._lastCompressionFailureReason = "Context changed during compaction (revision conflict)";
470
459
  return null;
471
460
  }
472
-
473
- const summaryTurn: Turn = {
474
- kind: "user",
475
- content: `[Context compacted — ${summarizedMsgs.length} earlier messages summarized]\n${summary}`,
476
- };
477
-
478
- this.turns = [...systemTurns, summaryTurn, ...toKeep];
479
- this.providerViewFloor = 0;
480
- this.recalculateTokens();
481
-
482
- const after = toKeep.flatMap((t) => turnToMessages(t)).length;
483
-
484
- return { summary, before, after };
461
+ this.requestCacheTracker.markMaintenance("summary");
462
+ let systemCount = 0;
463
+ while (snapshot.messages[systemCount]?.role === "system") systemCount++;
464
+ const before = snapshot.messages.length - systemCount;
465
+ return { summary: result.summary, before,
466
+ after: result.messages.length - systemCount - 1, status: result.status,
467
+ inputTokens: result.inputTokens, outputTokens: result.outputTokens,
468
+ filesRestored: result.filesRestored, sourceTruncated: result.sourceTruncated };
485
469
  }
486
470
 
487
471
  async waitForCompression(provider?: LLMProvider, options: { signal?: AbortSignal } = {}): Promise<void> {
@@ -521,6 +505,10 @@ export class ConversationManager {
521
505
  }
522
506
 
523
507
  clear(): void {
508
+ this.requestCacheTracker.clear();
509
+ this.pruneGate.clear();
510
+ this.revision++;
511
+ this.compactionContext = {};
524
512
  this.historicalImages?.reset();
525
513
  this.providerViewFloor = 0;
526
514
  this.turns = [];
@@ -680,6 +668,7 @@ export class ConversationManager {
680
668
  }
681
669
 
682
670
  private recalculateTokens(): void {
671
+ this.revision++;
683
672
  const msgs = turnsToMessages(this.turns);
684
673
  this._estimatedTokens = this.counter.countMessages(msgs);
685
674
  }
@@ -97,14 +97,14 @@ export class DefaultToolPolicyEngine implements ToolPolicyEngine {
97
97
  if (permission === "confirm") {
98
98
  return {
99
99
  decision: "ask",
100
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
100
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
101
101
  reason: "tool requires confirmation",
102
102
  };
103
103
  }
104
104
  if (request.effects.confidence === "unknown" && this.askOnUnknownEffects) {
105
105
  return {
106
106
  decision: "ask",
107
- request: { call: request.call, effects: request.effects, proposedGrant: grant },
107
+ request: { call: request.call, effects: request.effects, proposedGrant: grant, grantTtlMs: this.grantTtlMs },
108
108
  reason: "tool effects are unknown",
109
109
  };
110
110
  }
@@ -52,6 +52,9 @@ export interface ApprovalRequest {
52
52
  call: ResolvedToolCall;
53
53
  effects: ToolEffects;
54
54
  proposedGrant: CapabilityGrant;
55
+ /** Host policy opt-in: start this grant lifetime after approval completes.
56
+ * Omitted custom policies retain their absolute proposedGrant expiry. */
57
+ grantTtlMs?: number;
55
58
  }
56
59
 
57
60
  export interface PolicyRequest {
@@ -803,9 +803,18 @@ export class ToolExecutor {
803
803
  failure: operationFailure("APPROVAL_REQUIRED", "approval", context?.toolCallId),
804
804
  };
805
805
  }
806
- return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => (
807
- result === true ? authorized() : result
808
- ));
806
+ return this.requestApproval(tool, name, parsedArgs, effects, signal, context).then((result) => {
807
+ if (result !== true) return result;
808
+ const authorization = authorized();
809
+ const ttl = policy.request.grantTtlMs;
810
+ // Human/approval-queue wait consumes no execution authority lifetime.
811
+ // Only a policy that explicitly supplies a duration may activate a fresh
812
+ // expiry. Absolute custom-policy expiries and task deadlines stay intact.
813
+ if (typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0) {
814
+ authorization.grant = { ...grant, expiresAt: Date.now() + ttl };
815
+ }
816
+ return authorization;
817
+ });
809
818
  }
810
819
 
811
820
  private async requestApproval(