@sayknow-cli/agent-core 0.7.6 → 0.7.8

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/CHANGELOG.md CHANGED
@@ -2,7 +2,17 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
- ## [0.7.6] - 2026-10-05
5
+ ## [0.7.8] - 2026-10-09
6
+
7
+ ### Changed
8
+
9
+ - `hideThinkingSummary` is display-only state and is no longer forwarded to the provider. Asking a provider to omit reasoning made long thinking stream only keepalives, so the idle watchdog aborted healthy answers as stalled. Callers that need provider-side omission set `SimpleStreamOptions.hideThinkingSummary` on the stream call directly.
10
+
11
+ ## [0.7.7] - 2026-10-06
12
+
13
+ ### Added
14
+
15
+ - `Agent.setToolFilter()` narrows the tools a run exposes to the model and may execute (including a forced tool choice) without changing the selected tool set. An upstream lease can observe each settled attempt through `onAttemptSettled`.
6
16
 
7
17
  ## [0.7.4] - 2026-10-03
8
18
 
@@ -70,7 +70,7 @@ export interface AgentOptions {
70
70
  * Resolves an API key dynamically for each LLM call.
71
71
  * Useful for expiring tokens (e.g., GitHub Copilot OAuth).
72
72
  */
73
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
73
+ getApiKey?: AgentLoopConfig["getApiKey"];
74
74
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
75
75
  /**
76
76
  * Inspect or replace provider payloads before they are sent.
@@ -111,9 +111,9 @@ export interface AgentOptions {
111
111
  repetitionPenalty?: number;
112
112
  serviceTier?: ServiceTier;
113
113
  /**
114
- * If true, request that the underlying provider omit reasoning/thinking summaries
115
- * from the response. The model still reasons internally; only the human-readable
116
- * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
114
+ * Local display state: whether the UI hides thinking blocks. It never changes the
115
+ * provider request; reasoning keeps streaming so long thinking still counts as
116
+ * stream progress for the idle watchdog.
117
117
  */
118
118
  hideThinkingSummary?: boolean;
119
119
  /**
@@ -183,6 +183,8 @@ export interface AgentPromptOptions {
183
183
  onManagedAttemptAccepted?: AgentLoopConfig["onManagedAttemptAccepted"];
184
184
  /** Receives a discarded managed attempt without exposing assistant lifecycle events. */
185
185
  onManagedAttemptOutcome?: AgentLoopConfig["onManagedAttemptOutcome"];
186
+ /** Produces recovery evidence for a committed partial failure. Excluded from provider wire options. */
187
+ getRecoveryEvidence?: AgentLoopConfig["getRecoveryEvidence"];
186
188
  }
187
189
  export type AgentQueueSnapshot = {
188
190
  steering: AgentMessage[];
@@ -192,8 +194,9 @@ export declare class Agent {
192
194
  #private;
193
195
  get intentTracing(): boolean;
194
196
  streamFn: StreamFn;
195
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
197
+ getApiKey?: AgentLoopConfig["getApiKey"];
196
198
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
199
+ getUpstreamRequestLease?: AgentLoopConfig["getUpstreamRequestLease"];
197
200
  /**
198
201
  * Hook invoked after tool arguments are validated and before execution.
199
202
  * Reassign at any time to swap the implementation (e.g. on extension reload).
@@ -337,6 +340,11 @@ export declare class Agent {
337
340
  setInterruptMode(mode: "immediate" | "wait"): void;
338
341
  getInterruptMode(): "immediate" | "wait";
339
342
  setTools(t: AgentTool<any>[]): void;
343
+ /**
344
+ * Restricts the tools a run exposes to the model and may execute, without
345
+ * changing the selected tool set (`state.tools`). Pass `undefined` to clear.
346
+ */
347
+ setToolFilter(filter: ((tools: AgentTool<any>[]) => AgentTool<any>[]) | undefined): void;
340
348
  replaceMessages(ms: AgentMessage[]): void;
341
349
  appendMessage(m: AgentMessage): void;
342
350
  popMessage(): AgentMessage | undefined;
@@ -5,6 +5,24 @@ import type { AgentRunCoverage, AgentRunSummary } from "./run-collector";
5
5
  import type { AgentTelemetryConfig } from "./telemetry";
6
6
  /** Stream function - can return sync or Promise for async config lookup */
7
7
  export type StreamFn = (...args: Parameters<typeof streamSimple>) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;
8
+ /** Immutable owner lease captured for one invocation, never rebound to a successor. */
9
+ export interface UpstreamRequestLease {
10
+ readonly onRequest: NonNullable<SimpleStreamOptions["onUpstreamRequest"]>;
11
+ readonly validate: () => void;
12
+ readonly onRecoverableFailure: () => void;
13
+ readonly signal: AbortSignal;
14
+ /** Records opaque remote work (broker/custom auth) that makes automatic recovery unsafe. */
15
+ readonly onUncertainUpstream?: (reason: string) => void;
16
+ /**
17
+ * Called exactly once per settled model attempt of this lease with the final
18
+ * assistant message, so the owner can track consecutive no-output timeouts.
19
+ */
20
+ readonly onAttemptSettled?: (message: AssistantMessage) => void;
21
+ }
22
+ /** Request-scoped credential options; HTTP must use `fetch` so token wires share the owner budget. */
23
+ export type CredentialRequestOptions = Pick<SimpleStreamOptions, "signal" | "fetch" | "onUpstreamRequest" | "onUncertainUpstream">;
24
+ /** Local safety stop: a tool identity is never executed twice in the same transcript. */
25
+ export declare const TOOL_CALL_REENTRY_ERROR_CODE = "tool_call_identity_reentry";
8
26
  /** Stable identifier for a managed logical run, shared by all of its retry attempts. */
9
27
  export type ManagedLogicalRunId = number;
10
28
  /** Terminal completion requested for a logical run. */
@@ -31,6 +49,35 @@ export interface ManagedAttemptContinuationOwnership {
31
49
  }
32
50
  /** Runs after a discarded attempt is idle, only while its ownership token remains current. */
33
51
  export type ManagedAttemptContinuation = (ownership: ManagedAttemptContinuationOwnership) => void | Promise<void>;
52
+ /** Owner identity for a recovery-eligible committed partial failure. */
53
+ export interface RecoveryOwner {
54
+ logicalRunId: number | string;
55
+ stepId: string;
56
+ generation: number;
57
+ attemptId: string;
58
+ }
59
+ /** Classification of the committed assistant message tail at the failure boundary. */
60
+ export type RecoveryTail = "plain_text" | "signed_thinking" | "partial_tool" | "opaque";
61
+ /** Full evidence package produced by the recovery-evidence callback for a committed partial failure. */
62
+ export interface RecoveryEvidence extends RecoveryOwner {
63
+ visibleCommitted: boolean;
64
+ checkpointEntryId?: string;
65
+ visibleMessageIds: string[];
66
+ completedTools: Array<{
67
+ toolCallId: string;
68
+ callEntryId: string;
69
+ resultEntryId: string;
70
+ }>;
71
+ uncertainTools: Array<{
72
+ toolCallId?: string;
73
+ operationId?: string;
74
+ reason: string;
75
+ }>;
76
+ tail: RecoveryTail;
77
+ failureClass: string;
78
+ provider: string;
79
+ model: string;
80
+ }
34
81
  /** Decision returned by managed fallback policy for one provisional attempt. */
35
82
  export type ManagedAttemptDecision = {
36
83
  type: "retry";
@@ -38,6 +85,10 @@ export type ManagedAttemptDecision = {
38
85
  } | {
39
86
  type: "maintenance";
40
87
  continuation: ManagedAttemptContinuation;
88
+ } | {
89
+ type: "pause";
90
+ reason: string;
91
+ checkpointEntryId?: string;
41
92
  } | {
42
93
  type: "terminal";
43
94
  terminal: RunTerminalRequest;
@@ -53,6 +104,14 @@ export type ManagedAttemptOutcome = {
53
104
  } | {
54
105
  type: "context_overflow_discarded";
55
106
  message: AssistantMessage;
107
+ } | {
108
+ type: "visible_interrupted";
109
+ message: AssistantMessage;
110
+ evidence: RecoveryEvidence;
111
+ } | {
112
+ type: "unsafe_interrupted";
113
+ message: AssistantMessage;
114
+ evidence: RecoveryEvidence;
56
115
  } | {
57
116
  type: "run_terminal";
58
117
  reason: "cancelled" | "error" | "exhausted";
@@ -81,6 +140,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
81
140
  onManagedAttemptAccepted?: () => void | Promise<void>;
82
141
  /** Receives a managed invocation outcome without publishing provisional lifecycle events. */
83
142
  onManagedAttemptOutcome?: ManagedAttemptOutcomeHandler;
143
+ /** Persist and validate ownership before resolving credentials or sending any request. */
144
+ getUpstreamRequestLease?: (context: AgentContext, signal?: AbortSignal) => Promise<UpstreamRequestLease>;
84
145
  /**
85
146
  * When to interrupt tool execution for steering messages.
86
147
  * - "immediate" = check after each tool call (default)
@@ -155,7 +216,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
155
216
  * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire
156
217
  * during long-running tool execution phases.
157
218
  */
158
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
219
+ getApiKey?: (provider: string, options?: CredentialRequestOptions) => Promise<string | undefined> | string | undefined;
159
220
  /** Returns the credential type selected by the most recent getApiKey call for this session/provider. */
160
221
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
161
222
  /**
@@ -302,6 +363,14 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
302
363
  * capture, cost estimator, agent identity).
303
364
  */
304
365
  telemetry?: AgentTelemetryConfig;
366
+ /**
367
+ * Produces recovery evidence for a committed partial failure.
368
+ * When set and the attempt committed before a non-retryable error, the loop
369
+ * calls this instead of the existing fail-closed terminal path, allowing the
370
+ * session owner to inspect the evidence and decide whether to continue from
371
+ * a checkpoint or terminate. Excluded from provider wire options.
372
+ */
373
+ getRecoveryEvidence?: (message: AssistantMessage, context: AgentContext, tail: RecoveryEvidence["tail"], visibleCommitted: boolean) => Promise<RecoveryEvidence>;
305
374
  }
306
375
  /**
307
376
  * Batch/sequencing metadata for the tool call currently being processed.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/agent-core",
4
- "version": "0.7.6",
4
+ "version": "0.7.8",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -35,9 +35,9 @@
35
35
  "fmt": "biome format --write ."
36
36
  },
37
37
  "dependencies": {
38
- "@sayknow-cli/ai": "0.7.6",
39
- "@sayknow-cli/natives": "0.7.6",
40
- "@sayknow-cli/utils": "0.7.6",
38
+ "@sayknow-cli/ai": "0.7.8",
39
+ "@sayknow-cli/natives": "0.7.8",
40
+ "@sayknow-cli/utils": "0.7.8",
41
41
  "@opentelemetry/api": "^1.9.0"
42
42
  },
43
43
  "devDependencies": {
package/src/agent-loop.ts CHANGED
@@ -10,7 +10,9 @@ import {
10
10
  type Context,
11
11
  classifyContextOverflow,
12
12
  classifyFallbackTrigger,
13
+ createUpstreamAdmission,
13
14
  EventStream,
15
+ isRecoveryAdmissionErrorMessage,
14
16
  isZodSchema,
15
17
  streamSimple,
16
18
  type ToolResultMessage,
@@ -59,8 +61,10 @@ import type {
59
61
  AgentTool,
60
62
  AgentToolResult,
61
63
  ManagedAttemptOutcome,
64
+ RecoveryEvidence,
62
65
  StreamFn,
63
66
  } from "./types";
67
+ import { TOOL_CALL_REENTRY_ERROR_CODE } from "./types";
64
68
 
65
69
  /** Sentinel returned by the abort race in `streamAssistantResponse`. */
66
70
  /**
@@ -251,6 +255,18 @@ function managedFailureOutcome(message: AssistantMessage): ManagedAttemptOutcome
251
255
  function managedContextOverflowOutcome(message: AssistantMessage): ManagedAttemptOutcome {
252
256
  return { type: "context_overflow_discarded", message };
253
257
  }
258
+ function classifyRecoveryTail(message: AssistantMessage, config: AgentLoopConfig): RecoveryEvidence["tail"] {
259
+ if (config.model.transport === "pi-native" || config.model.api === "cursor-agent") {
260
+ return "opaque";
261
+ }
262
+ const hasThinking = message.content.some(c => c.type === "thinking" || c.type === "redactedThinking");
263
+ if (hasThinking) return "signed_thinking";
264
+ const hasToolCall = message.content.some(c => c.type === "toolCall");
265
+ if (hasToolCall) return "partial_tool";
266
+ const hasText = message.content.some(c => c.type === "text");
267
+ if (hasText) return "plain_text";
268
+ return "opaque";
269
+ }
254
270
 
255
271
  function managedFailureMessage(error: unknown, config: AgentLoopConfig): AssistantMessage {
256
272
  const errorMessage = managedProperty(error, "message");
@@ -2643,6 +2659,17 @@ async function runLoopBody(
2643
2659
  const wasRecoveryAttempt = recoveryState.pending;
2644
2660
 
2645
2661
  if (message.stopReason === "error" || message.stopReason === "aborted") {
2662
+ // Committed partial failure: when getRecoveryEvidence is configured and this is a
2663
+ // non-retryable error on a published attempt, produce a typed recovery outcome instead
2664
+ // of the fail-closed terminal. Evidence is collected before placeholder tool results
2665
+ // are appended so the callback observes the committed context unchanged.
2666
+ let recovery: { evidence: RecoveryEvidence; visibleCommitted: boolean } | undefined;
2667
+ if (config.fallbackManaged && message.stopReason === "error" && config.getRecoveryEvidence != null) {
2668
+ const tail = classifyRecoveryTail(message, config);
2669
+ const visibleCommitted = tail === "plain_text";
2670
+ const evidence = await config.getRecoveryEvidence(message, currentContext, tail, visibleCommitted);
2671
+ recovery = { evidence, visibleCommitted };
2672
+ }
2646
2673
  // Create placeholder tool results for any tool calls in the aborted message
2647
2674
  // This maintains the tool_use/tool_result pairing that the API requires
2648
2675
  type ToolCallContent = Extract<AssistantMessage["content"][number], { type: "toolCall" }>;
@@ -2666,7 +2693,16 @@ async function runLoopBody(
2666
2693
  });
2667
2694
  }
2668
2695
  stream.push({ type: "turn_end", message, toolResults });
2669
- stream.push(buildAgentEndEvent(newMessages, telemetry, stepCounter.count));
2696
+ if (recovery) {
2697
+ // The session owner receives evidence and decides how to proceed.
2698
+ await config.onManagedAttemptOutcome?.({
2699
+ type: recovery.visibleCommitted ? "visible_interrupted" : "unsafe_interrupted",
2700
+ message,
2701
+ evidence: recovery.evidence,
2702
+ });
2703
+ } else {
2704
+ stream.push(buildAgentEndEvent(newMessages, telemetry, stepCounter.count));
2705
+ }
2670
2706
  stream.end(newMessages);
2671
2707
  return;
2672
2708
  }
@@ -2675,6 +2711,46 @@ async function runLoopBody(
2675
2711
  const toolCalls = message.content.filter(c => c.type === "toolCall");
2676
2712
  hasMoreToolCalls = toolCalls.length > 0;
2677
2713
 
2714
+ // Reusing an already-seen call identity cannot establish a new operation.
2715
+ // Stop the whole batch before any tool starts, including unresolved calls
2716
+ // whose remote outcome is unknown. New identities retain normal approval.
2717
+ // Blank ids carry no identity (some providers emit "" for unnamed calls).
2718
+ const hasIdentity = (id: string): boolean => id.trim().length > 0;
2719
+ const priorCallIds = new Set<string>();
2720
+ for (const prior of currentContext.messages.slice(0, -1)) {
2721
+ if (prior.role === "toolResult" && hasIdentity(prior.toolCallId)) priorCallIds.add(prior.toolCallId);
2722
+ if (prior.role === "assistant") {
2723
+ for (const block of prior.content) {
2724
+ if (block.type === "toolCall" && hasIdentity(block.id)) priorCallIds.add(block.id);
2725
+ }
2726
+ }
2727
+ }
2728
+ const seenCallIds = new Set<string>();
2729
+ const repeatedCall = toolCalls.find(call => {
2730
+ if (!hasIdentity(call.id)) return false;
2731
+ const repeated = priorCallIds.has(call.id) || seenCallIds.has(call.id);
2732
+ seenCallIds.add(call.id);
2733
+ return repeated;
2734
+ });
2735
+ if (repeatedCall) {
2736
+ const failure: AssistantMessage = {
2737
+ ...message,
2738
+ content: [],
2739
+ stopReason: "error",
2740
+ errorCode: TOOL_CALL_REENTRY_ERROR_CODE,
2741
+ errorMessage:
2742
+ "A previously observed tool call identity was reused; execution is paused to avoid repeating its effects.",
2743
+ };
2744
+ currentContext.messages.push(failure);
2745
+ newMessages.push(failure);
2746
+ stream.push({ type: "message_start", message: failure });
2747
+ stream.push({ type: "message_end", message: failure });
2748
+ stream.push({ type: "turn_end", message: failure, toolResults: [] });
2749
+ stream.push(buildAgentEndEvent(newMessages, telemetry, stepCounter.count));
2750
+ stream.end(newMessages);
2751
+ return;
2752
+ }
2753
+
2678
2754
  const toolResults: ToolResultMessage[] = [];
2679
2755
  let repeatedMalformedToolCall = false;
2680
2756
  if (hasMoreToolCalls) {
@@ -2875,8 +2951,51 @@ async function streamAssistantResponse(
2875
2951
  // Resolve API key (important for expiring tokens) — do this before resolving
2876
2952
  // metadata so that the session-sticky credential recorded by getApiKey is
2877
2953
  // visible to metadataResolver (e.g. for the correct account_uuid in metadata.user_id).
2878
- const resolvedApiKey =
2879
- (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
2954
+ // Capture a permanently bound owner lease. Its persistence barrier finishes
2955
+ // before credentials or transport work, and local preparation spends wire 0.
2956
+ // A pre-cancelled invocation takes no lease (no checkpoint, wire 0) and reaches the
2957
+ // standard aborted-message path through the request signal below.
2958
+ const upstreamLease = signal?.aborted ? undefined : await config.getUpstreamRequestLease?.(context, signal);
2959
+ if (!signal?.aborted) upstreamLease?.validate();
2960
+ const upstreamHook = upstreamLease?.onRequest ?? config.onUpstreamRequest;
2961
+ const upstreamAdmission = upstreamHook
2962
+ ? createUpstreamAdmission(
2963
+ upstreamHook,
2964
+ config.fetch,
2965
+ upstreamLease?.validate,
2966
+ upstreamLease?.onRecoverableFailure,
2967
+ )
2968
+ : undefined;
2969
+ let resolvedApiKey = config.apiKey;
2970
+ const credentialSignal = AbortSignal.any([
2971
+ ...(signal ? [signal] : []),
2972
+ ...(upstreamLease ? [upstreamLease.signal] : []),
2973
+ ]);
2974
+ // A cancelled invocation resolves no credentials (token wire 0) and falls through to the
2975
+ // standard aborted-message path below, whose request signal carries the same aborts.
2976
+ if (config.getApiKey && !credentialSignal.aborted) {
2977
+ const credentialAbort = Promise.withResolvers<undefined>();
2978
+ const onCredentialAbort = () => credentialAbort.resolve(undefined);
2979
+ credentialSignal.addEventListener("abort", onCredentialAbort, { once: true });
2980
+ try {
2981
+ // A resolver that ignores its signal still yields a finite local terminal.
2982
+ resolvedApiKey =
2983
+ (await Promise.race([
2984
+ config.getApiKey(config.model.provider, {
2985
+ signal: credentialSignal,
2986
+ fetch: upstreamAdmission?.credentialFetch,
2987
+ onUpstreamRequest: upstreamAdmission?.onUpstreamRequest,
2988
+ onUncertainUpstream: upstreamLease?.onUncertainUpstream,
2989
+ }),
2990
+ credentialAbort.promise,
2991
+ ])) || config.apiKey;
2992
+ } catch (error) {
2993
+ if (!credentialSignal.aborted) throw error;
2994
+ } finally {
2995
+ credentialSignal.removeEventListener("abort", onCredentialAbort);
2996
+ }
2997
+ if (!credentialSignal.aborted) upstreamLease?.validate();
2998
+ }
2880
2999
 
2881
3000
  // Re-resolve metadata after credential selection so the per-request value
2882
3001
  // reflects the credential actually used, not the snapshot from AgentLoopConfig construction.
@@ -2896,6 +3015,7 @@ async function streamAssistantResponse(
2896
3015
  const requestSignal = AbortSignal.any([
2897
3016
  ...(signal ? [signal] : []),
2898
3017
  ...(harmonyAbortController ? [harmonyAbortController.signal] : []),
3018
+ ...(upstreamLease ? [upstreamLease.signal] : []),
2899
3019
  attemptAbortController.signal,
2900
3020
  ]);
2901
3021
  const effectiveTemperature =
@@ -2934,6 +3054,7 @@ async function streamAssistantResponse(
2934
3054
  };
2935
3055
 
2936
3056
  const finishChat = async (message: AssistantMessage): Promise<void> => {
3057
+ upstreamLease?.onAttemptSettled?.(message);
2937
3058
  await finishChatSpan(telemetry, chatSpan, message, {
2938
3059
  stepNumber: chatStepNumber,
2939
3060
  serviceTier: config.serviceTier,
@@ -2956,6 +3077,17 @@ async function streamAssistantResponse(
2956
3077
  reasoning: effectiveReasoning,
2957
3078
  temperature: effectiveTemperature,
2958
3079
  signal: requestSignal,
3080
+ // A session-owned step decides every resend from the observed failure (including
3081
+ // Retry-After); SDK-internal request retries would hide waits and resends from it.
3082
+ ...(upstreamLease ? { requestMaxRetries: 0 } : {}),
3083
+ ...(upstreamAdmission
3084
+ ? {
3085
+ fetch: upstreamAdmission.fetch,
3086
+ credentialFetch: upstreamAdmission.credentialFetch,
3087
+ onUpstreamRequest: upstreamAdmission.onUpstreamRequest,
3088
+ onUncertainUpstream: upstreamLease?.onUncertainUpstream,
3089
+ }
3090
+ : {}),
2959
3091
  onResponse: captureOnResponse,
2960
3092
  });
2961
3093
 
@@ -2971,7 +3103,14 @@ async function streamAssistantResponse(
2971
3103
  let detachAbortListener: (() => void) | undefined;
2972
3104
  if (requestSignal) {
2973
3105
  if (requestSignal.aborted) {
2974
- const aborted = emitAbortedAssistantMessage(partialMessage, addedPartial, context, config, stream);
3106
+ const aborted = emitAbortedAssistantMessage(
3107
+ partialMessage,
3108
+ addedPartial,
3109
+ context,
3110
+ config,
3111
+ stream,
3112
+ requestSignal.reason,
3113
+ );
2975
3114
  await finishChat(aborted);
2976
3115
  return aborted;
2977
3116
  }
@@ -2989,7 +3128,14 @@ async function streamAssistantResponse(
2989
3128
  const result = await Promise.race([responseIterator.next(), abortRacePromise]);
2990
3129
  if (result === ABORTED) {
2991
3130
  responseIterator.return?.()?.catch(() => {});
2992
- const aborted = emitAbortedAssistantMessage(partialMessage, addedPartial, context, config, stream);
3131
+ const aborted = emitAbortedAssistantMessage(
3132
+ partialMessage,
3133
+ addedPartial,
3134
+ context,
3135
+ config,
3136
+ stream,
3137
+ requestSignal.reason,
3138
+ );
2993
3139
  await finishChat(aborted);
2994
3140
  return aborted;
2995
3141
  }
@@ -2998,7 +3144,14 @@ async function streamAssistantResponse(
2998
3144
  next = await responseIterator.next();
2999
3145
  }
3000
3146
  if (requestSignal?.aborted) {
3001
- const aborted = emitAbortedAssistantMessage(partialMessage, addedPartial, context, config, stream);
3147
+ const aborted = emitAbortedAssistantMessage(
3148
+ partialMessage,
3149
+ addedPartial,
3150
+ context,
3151
+ config,
3152
+ stream,
3153
+ requestSignal.reason,
3154
+ );
3002
3155
  await finishChat(aborted);
3003
3156
  return aborted;
3004
3157
  }
@@ -3094,8 +3247,10 @@ function emitAbortedAssistantMessage(
3094
3247
  context: AgentContext,
3095
3248
  config: AgentLoopConfig,
3096
3249
  stream: EventStream<AgentEvent, AgentMessage[]>,
3250
+ reason?: unknown,
3097
3251
  ): AssistantMessage {
3098
- const errorMessage = "Request was aborted";
3252
+ const recoveryError = reason instanceof Error && isRecoveryAdmissionErrorMessage(reason.message);
3253
+ const errorMessage = recoveryError ? reason.message : "Request was aborted";
3099
3254
  const now = Date.now();
3100
3255
  const abortedMessage: AssistantMessage = {
3101
3256
  role: "assistant",
@@ -3111,7 +3266,7 @@ function emitAbortedAssistantMessage(
3111
3266
  totalTokens: 0,
3112
3267
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
3113
3268
  },
3114
- stopReason: "aborted",
3269
+ stopReason: recoveryError ? "error" : "aborted",
3115
3270
  errorMessage,
3116
3271
  timestamp: now,
3117
3272
  };
package/src/agent.ts CHANGED
@@ -173,7 +173,7 @@ export interface AgentOptions {
173
173
  * Resolves an API key dynamically for each LLM call.
174
174
  * Useful for expiring tokens (e.g., GitHub Copilot OAuth).
175
175
  */
176
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
176
+ getApiKey?: AgentLoopConfig["getApiKey"];
177
177
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
178
178
 
179
179
  /**
@@ -218,9 +218,9 @@ export interface AgentOptions {
218
218
  repetitionPenalty?: number;
219
219
  serviceTier?: ServiceTier;
220
220
  /**
221
- * If true, request that the underlying provider omit reasoning/thinking summaries
222
- * from the response. The model still reasons internally; only the human-readable
223
- * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
221
+ * Local display state: whether the UI hides thinking blocks. It never changes the
222
+ * provider request; reasoning keeps streaming so long thinking still counts as
223
+ * stream progress for the idle watchdog.
224
224
  */
225
225
  hideThinkingSummary?: boolean;
226
226
 
@@ -300,6 +300,8 @@ export interface AgentPromptOptions {
300
300
  onManagedAttemptAccepted?: AgentLoopConfig["onManagedAttemptAccepted"];
301
301
  /** Receives a discarded managed attempt without exposing assistant lifecycle events. */
302
302
  onManagedAttemptOutcome?: AgentLoopConfig["onManagedAttemptOutcome"];
303
+ /** Produces recovery evidence for a committed partial failure. Excluded from provider wire options. */
304
+ getRecoveryEvidence?: AgentLoopConfig["getRecoveryEvidence"];
303
305
  }
304
306
 
305
307
  /** Buffered Cursor tool result with text position at time of call */
@@ -368,6 +370,7 @@ export class Agent {
368
370
  #transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
369
371
  #intentTracing: boolean;
370
372
  #getToolChoice?: () => ToolChoice | undefined;
373
+ #toolFilter?: (tools: AgentTool<any>[]) => AgentTool<any>[];
371
374
  #onPayload?: SimpleStreamOptions["onPayload"];
372
375
  #onResponse?: SimpleStreamOptions["onResponse"];
373
376
  #onSseEvent?: SimpleStreamOptions["onSseEvent"];
@@ -390,8 +393,10 @@ export class Agent {
390
393
  #managedLogicalRunOwner?: ManagedLogicalRunId;
391
394
 
392
395
  streamFn: StreamFn;
393
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
396
+ getApiKey?: AgentLoopConfig["getApiKey"];
394
397
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
398
+
399
+ getUpstreamRequestLease?: AgentLoopConfig["getUpstreamRequestLease"];
395
400
  /**
396
401
  * Hook invoked after tool arguments are validated and before execution.
397
402
  * Reassign at any time to swap the implementation (e.g. on extension reload).
@@ -906,6 +911,20 @@ export class Agent {
906
911
  this.#contextRevision++;
907
912
  }
908
913
 
914
+ /**
915
+ * Restricts the tools a run exposes to the model and may execute, without
916
+ * changing the selected tool set (`state.tools`). Pass `undefined` to clear.
917
+ */
918
+ setToolFilter(filter: ((tools: AgentTool<any>[]) => AgentTool<any>[]) | undefined) {
919
+ this.#toolFilter = filter;
920
+ this.#contextRevision++;
921
+ }
922
+
923
+ /** Tools a run exposes to the model: the selected set narrowed by the active tool filter. */
924
+ #projectedTools(): AgentTool<any>[] {
925
+ return this.#toolFilter ? this.#toolFilter(this.#state.tools) : this.#state.tools;
926
+ }
927
+
909
928
  replaceMessages(ms: AgentMessage[]) {
910
929
  this.#state.messages = ms.slice();
911
930
  this.#contextRevision++;
@@ -1373,7 +1392,7 @@ export class Agent {
1373
1392
  const context: AgentContext = {
1374
1393
  systemPrompt: this.#state.systemPrompt,
1375
1394
  messages: this.#state.messages.slice(),
1376
- tools: this.#state.tools,
1395
+ tools: this.#projectedTools(),
1377
1396
  };
1378
1397
 
1379
1398
  const cursorOnToolResult =
@@ -1403,8 +1422,13 @@ export class Agent {
1403
1422
  }
1404
1423
  : undefined;
1405
1424
 
1406
- const getToolChoice = () =>
1407
- this.#getToolChoice?.() ?? refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
1425
+ const getToolChoice = () => {
1426
+ if (!this.#toolFilter) {
1427
+ return this.#getToolChoice?.() ?? refreshToolChoiceForActiveTools(options?.toolChoice, this.#state.tools);
1428
+ }
1429
+ // A forced choice must never name a tool the filter withholds.
1430
+ return refreshToolChoiceForActiveTools(this.#getToolChoice?.() ?? options?.toolChoice, this.#projectedTools());
1431
+ };
1408
1432
  const cursorExecHandlers = fallbackManaged ? undefined : this.#cursorExecHandlersForRun(runId);
1409
1433
  let managedDecision: ManagedAttemptDecision | undefined;
1410
1434
  let managedOutcome: ManagedAttemptOutcome | undefined;
@@ -1420,7 +1444,9 @@ export class Agent {
1420
1444
  presencePenalty: this.#presencePenalty,
1421
1445
  repetitionPenalty: this.#repetitionPenalty,
1422
1446
  serviceTier: this.#serviceTier,
1423
- hideThinkingSummary: this.#hideThinkingSummary,
1447
+ // Hiding thinking is a local display preference and never changes the request:
1448
+ // a provider told to omit reasoning streams only keepalives during long
1449
+ // thinking, and the idle watchdog then cuts a healthy answer as stalled.
1424
1450
  interruptMode: this.#interruptMode,
1425
1451
  sessionId: this.#sessionId,
1426
1452
  providerSessionId: this.#providerSessionId,
@@ -1436,6 +1462,7 @@ export class Agent {
1436
1462
  fallbackManaged: true,
1437
1463
  nextFallbackAttempt: options?.nextFallbackAttempt,
1438
1464
  onManagedAttemptAccepted: options?.onManagedAttemptAccepted,
1465
+ getRecoveryEvidence: options?.getRecoveryEvidence,
1439
1466
  onManagedAttemptOutcome: async outcome => {
1440
1467
  managedOutcome = outcome;
1441
1468
  managedDecision = (await options?.onManagedAttemptOutcome?.(outcome)) ?? {
@@ -1456,13 +1483,14 @@ export class Agent {
1456
1483
  signal: abortController.signal,
1457
1484
  getApiKey: this.getApiKey,
1458
1485
  getAuthCredentialType: this.getAuthCredentialType,
1486
+ getUpstreamRequestLease: this.getUpstreamRequestLease,
1459
1487
  getToolContext: this.#getToolContext,
1460
1488
  syncContextBeforeModelCall: async context => {
1461
1489
  if (this.#listeners.size > 0) {
1462
1490
  await Bun.sleep(0);
1463
1491
  }
1464
1492
  context.systemPrompt = this.#state.systemPrompt;
1465
- context.tools = this.#state.tools;
1493
+ context.tools = this.#projectedTools();
1466
1494
  },
1467
1495
  ...(cursorExecHandlers ? { cursorExecHandlers } : {}),
1468
1496
  ...(cursorOnToolResult ? { cursorOnToolResult } : {}),
@@ -1627,6 +1655,8 @@ export class Agent {
1627
1655
  if (managedOutcome) {
1628
1656
  if (managedDecision?.type === "terminal") {
1629
1657
  this.requestRunTerminal(managedLogicalRunOwner ?? runId, managedDecision.terminal);
1658
+ } else if (managedDecision?.type === "pause") {
1659
+ this.requestRunTerminal(managedLogicalRunOwner ?? runId, { stopReason: "error" });
1630
1660
  } else if (managedOutcome.type === "run_terminal") {
1631
1661
  this.requestRunTerminal(managedLogicalRunOwner ?? runId, { stopReason: managedOutcome.reason });
1632
1662
  } else if (managedDecision?.type !== "retry" && managedDecision?.type !== "maintenance") {
package/src/types.ts CHANGED
@@ -26,6 +26,30 @@ export type StreamFn = (
26
26
  ...args: Parameters<typeof streamSimple>
27
27
  ) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;
28
28
 
29
+ /** Immutable owner lease captured for one invocation, never rebound to a successor. */
30
+ export interface UpstreamRequestLease {
31
+ readonly onRequest: NonNullable<SimpleStreamOptions["onUpstreamRequest"]>;
32
+ readonly validate: () => void;
33
+ readonly onRecoverableFailure: () => void;
34
+ readonly signal: AbortSignal;
35
+ /** Records opaque remote work (broker/custom auth) that makes automatic recovery unsafe. */
36
+ readonly onUncertainUpstream?: (reason: string) => void;
37
+ /**
38
+ * Called exactly once per settled model attempt of this lease with the final
39
+ * assistant message, so the owner can track consecutive no-output timeouts.
40
+ */
41
+ readonly onAttemptSettled?: (message: AssistantMessage) => void;
42
+ }
43
+
44
+ /** Request-scoped credential options; HTTP must use `fetch` so token wires share the owner budget. */
45
+ export type CredentialRequestOptions = Pick<
46
+ SimpleStreamOptions,
47
+ "signal" | "fetch" | "onUpstreamRequest" | "onUncertainUpstream"
48
+ >;
49
+
50
+ /** Local safety stop: a tool identity is never executed twice in the same transcript. */
51
+ export const TOOL_CALL_REENTRY_ERROR_CODE = "tool_call_identity_reentry";
52
+
29
53
  /** Stable identifier for a managed logical run, shared by all of its retry attempts. */
30
54
  export type ManagedLogicalRunId = number;
31
55
 
@@ -55,11 +79,35 @@ export interface ManagedAttemptContinuationOwnership {
55
79
 
56
80
  /** Runs after a discarded attempt is idle, only while its ownership token remains current. */
57
81
  export type ManagedAttemptContinuation = (ownership: ManagedAttemptContinuationOwnership) => void | Promise<void>;
82
+ /** Owner identity for a recovery-eligible committed partial failure. */
83
+ export interface RecoveryOwner {
84
+ logicalRunId: number | string;
85
+ stepId: string;
86
+ generation: number;
87
+ attemptId: string;
88
+ }
89
+
90
+ /** Classification of the committed assistant message tail at the failure boundary. */
91
+ export type RecoveryTail = "plain_text" | "signed_thinking" | "partial_tool" | "opaque";
92
+
93
+ /** Full evidence package produced by the recovery-evidence callback for a committed partial failure. */
94
+ export interface RecoveryEvidence extends RecoveryOwner {
95
+ visibleCommitted: boolean;
96
+ checkpointEntryId?: string;
97
+ visibleMessageIds: string[];
98
+ completedTools: Array<{ toolCallId: string; callEntryId: string; resultEntryId: string }>;
99
+ uncertainTools: Array<{ toolCallId?: string; operationId?: string; reason: string }>;
100
+ tail: RecoveryTail;
101
+ failureClass: string;
102
+ provider: string;
103
+ model: string;
104
+ }
58
105
 
59
106
  /** Decision returned by managed fallback policy for one provisional attempt. */
60
107
  export type ManagedAttemptDecision =
61
108
  | { type: "retry"; continuation: ManagedAttemptContinuation }
62
109
  | { type: "maintenance"; continuation: ManagedAttemptContinuation }
110
+ | { type: "pause"; reason: string; checkpointEntryId?: string }
63
111
  | { type: "terminal"; terminal: RunTerminalRequest };
64
112
 
65
113
  /** Structured result for one managed upstream invocation. */
@@ -73,6 +121,8 @@ export type ManagedAttemptOutcome =
73
121
  };
74
122
  }
75
123
  | { type: "context_overflow_discarded"; message: AssistantMessage }
124
+ | { type: "visible_interrupted"; message: AssistantMessage; evidence: RecoveryEvidence }
125
+ | { type: "unsafe_interrupted"; message: AssistantMessage; evidence: RecoveryEvidence }
76
126
  | { type: "run_terminal"; reason: "cancelled" | "error" | "exhausted" };
77
127
 
78
128
  export type ManagedAttemptOutcomeHandler = (
@@ -104,6 +154,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
104
154
 
105
155
  /** Receives a managed invocation outcome without publishing provisional lifecycle events. */
106
156
  onManagedAttemptOutcome?: ManagedAttemptOutcomeHandler;
157
+ /** Persist and validate ownership before resolving credentials or sending any request. */
158
+ getUpstreamRequestLease?: (context: AgentContext, signal?: AbortSignal) => Promise<UpstreamRequestLease>;
107
159
 
108
160
  /**
109
161
  * When to interrupt tool execution for steering messages.
@@ -184,7 +236,10 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
184
236
  * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire
185
237
  * during long-running tool execution phases.
186
238
  */
187
- getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
239
+ getApiKey?: (
240
+ provider: string,
241
+ options?: CredentialRequestOptions,
242
+ ) => Promise<string | undefined> | string | undefined;
188
243
 
189
244
  /** Returns the credential type selected by the most recent getApiKey call for this session/provider. */
190
245
  getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
@@ -353,6 +408,19 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
353
408
  * capture, cost estimator, agent identity).
354
409
  */
355
410
  telemetry?: AgentTelemetryConfig;
411
+ /**
412
+ * Produces recovery evidence for a committed partial failure.
413
+ * When set and the attempt committed before a non-retryable error, the loop
414
+ * calls this instead of the existing fail-closed terminal path, allowing the
415
+ * session owner to inspect the evidence and decide whether to continue from
416
+ * a checkpoint or terminate. Excluded from provider wire options.
417
+ */
418
+ getRecoveryEvidence?: (
419
+ message: AssistantMessage,
420
+ context: AgentContext,
421
+ tail: RecoveryEvidence["tail"],
422
+ visibleCommitted: boolean,
423
+ ) => Promise<RecoveryEvidence>;
356
424
  }
357
425
 
358
426
  /**