@oh-my-pi/pi-agent-core 19.2.0 → 19.3.0

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,6 +2,39 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [19.3.0] - 2026-11-28
6
+
7
+ ### Added
8
+
9
+ - Added `Agent.inheritToolDescriptions()` and `Agent.normalizedTools()` so forked agents can reuse their parent’s prompt cache when tool descriptions differ only in wording.
10
+ - Added `CompactionSettings.summaryMaxTokens` to control the output token budget for regular compaction summaries. Compaction preserves history that fits alongside the previous summary and the requested output budget ([#18688](https://github.com/can1357/oh-my-pi/issues/18688)).
11
+
12
+ ### Changed
13
+
14
+ - Capped the default reserve-based compaction threshold at 690,000 tokens for large context windows. Explicit percentage and fixed thresholds, as well as `baseWindowTokens` overrides, remain uncapped.
15
+
16
+ ### Fixed
17
+
18
+ - Turn-end hooks can now identify calls that did not name a tool through `AgentTurnEndContext.unresolvedToolCallIds` ([#10876](https://github.com/can1357/oh-my-pi/issues/10876)).
19
+ - `generateHandoffFromContext` now sets an output limit so handoffs cannot stream indefinitely on servers without their own limit. Handoffs that reach the limit without finishing report an incomplete-output error ([#18031](https://github.com/can1357/oh-my-pi/issues/18031)).
20
+ - Reduced authentication-gateway request sizes by excluding internal host state from tool definitions.
21
+ - OpenTelemetry chat spans now report the model that actually served the response.
22
+ - Fixed shake recovery increasing context size by replacing tool results that were smaller than the replacement text ([#7204](https://github.com/can1357/oh-my-pi/issues/7204)).
23
+ - Fixed context token counts used by the status line and compaction to include `$` Python output, `@file` mentions, and terminal images from `!` commands, while excluding `!!` output that is not sent to the model ([#20834](https://github.com/can1357/oh-my-pi/pull/20834) by [@sjawhar](https://github.com/sjawhar)).
24
+ - Fixed token counting failing on stored custom messages whose content is neither text nor content blocks ([#20834](https://github.com/can1357/oh-my-pi/pull/20834) by [@sjawhar](https://github.com/sjawhar)).
25
+ - Compaction now stops in-flight summary requests and avoids sending new ones after cancellation or failure, including during split-turn compaction ([#20713](https://github.com/can1357/oh-my-pi/pull/20713) by [@sjawhar](https://github.com/sjawhar), [#20887](https://github.com/can1357/oh-my-pi/pull/20887) by [@sjawhar](https://github.com/sjawhar)).
26
+
27
+ ## [19.2.1] - 2026-11-25
28
+
29
+ ### Added
30
+
31
+ - Added `Agent.peekDeliveringMessages(queue?)` for queued input on its way into the next request that the transcript has not recorded yet; queue listeners hear when it lands.
32
+ - Added `Agent.continue(signal, { queuedOnly: true })` to start an idle turn using queued input without making a separate model call for the current context.
33
+
34
+ ### Changed
35
+
36
+ - Debug logs now time the wait between dequeuing input and the model request that carries it, by phase.
37
+
5
38
  ## [19.2.0] - 2026-11-25
6
39
 
7
40
  ### Added
@@ -5,6 +5,7 @@
5
5
  import { type AssistantMessage, type Context, EventStream, type ToolResultMessage } from "@oh-my-pi/pi-ai";
6
6
  import { type Dialect } from "@oh-my-pi/pi-ai/dialect";
7
7
  import { type AgentRunCoverage, type AgentRunSummary } from "./run-collector.js";
8
+ import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
8
9
  import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool, SteeringQueueState, StreamFn } from "./types.js";
9
10
  /**
10
11
  * A tool's batch concurrency for one call: an unset mode is shared, and a
@@ -129,6 +130,8 @@ export interface NormalizeToolsOptions {
129
130
  intentDescription?: string;
130
131
  /** Strip descriptions from the wire specs when the catalog rides in the system prompt. */
131
132
  pruneDescriptions?: boolean;
133
+ /** A fork's owner-worded descriptions; see {@link InheritedToolDescriptions}. */
134
+ inheritedDescriptions?: InheritedToolDescriptions;
132
135
  }
133
136
  export declare function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"];
134
137
  /** Split a traced call's intent (`i`, trimmed, trailing periods dropped) from the arguments its tool reads. */
@@ -1,10 +1,10 @@
1
- import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type ToolChoice, type ToolResultMessage } from "@oh-my-pi/pi-ai";
1
+ import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type Tool, type ToolChoice, type ToolResultMessage } from "@oh-my-pi/pi-ai";
2
2
  import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
3
3
  import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
4
4
  import type { AppendOnlyContextManager } from "./append-only-context.js";
5
5
  import { SentToolDefinitions } from "./sent-tool-definitions.js";
6
6
  import { Tokenizer } from "./tokenizer.js";
7
- import type { AgentBeforeModelCall, AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideBoundary, AsideMessage, PrepareQueuedMessages, QueuedMessageGate, SpeculativeToolExecutionConfig, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types.js";
7
+ import type { AgentBeforeModelCall, AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideBoundary, AsideMessage, PrepareQueuedMessages, QueuedMessageGate, QueuedMessageQueue, SpeculativeToolExecutionConfig, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types.js";
8
8
  export declare class AgentBusyError extends Error {
9
9
  constructor(message?: string);
10
10
  }
@@ -315,6 +315,18 @@ export declare class Agent {
315
315
  * names `keep` rejects.
316
316
  */
317
317
  copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions;
318
+ /**
319
+ * Provider-bound specs of the tools the next request to the active model declares, before the
320
+ * provider-context transform; empty without a model or under an owned dialect. A fork passes
321
+ * its owner's to {@link inheritToolDescriptions}.
322
+ */
323
+ normalizedTools(): Tool[];
324
+ /**
325
+ * Send `owner`'s wording for every current tool that differs from it only in description, so
326
+ * this fork's requests open with the owner's cached prefix. Call once the fork's tool set is
327
+ * final; see {@link InheritedToolDescriptions}.
328
+ */
329
+ inheritToolDescriptions(owner: readonly Tool[]): void;
318
330
  /**
319
331
  * Fields added to every log record written while this agent runs (the
320
332
  * owning session's `sessionId`), so in-process agents' records stay apart.
@@ -586,6 +598,10 @@ export declare class Agent {
586
598
  * requeues them, so the session's empty-submit interrupt counts them as
587
599
  * pending input even though {@link peekSteeringQueue} no longer does. */
588
600
  peekUndeliveredQueuedMessages(): AgentMessage[];
601
+ /** Messages dequeued from `queue` (both queues when omitted) for the next model request that the
602
+ * transcript has not recorded yet, oldest first. Their events only emit once the request opens,
603
+ * so queue displays keep listing them until then. */
604
+ peekDeliveringMessages(queue?: QueuedMessageQueue): AgentMessage[];
589
605
  /** Non-consuming view of the pending follow-up queue. See
590
606
  * {@link peekSteeringQueue}. */
591
607
  peekFollowUpQueue(): readonly AgentMessage[];
@@ -624,5 +640,11 @@ export declare class Agent {
624
640
  prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
625
641
  prompt(input: string, options?: AgentPromptOptions): Promise<void>;
626
642
  prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
627
- continue(signal?: AbortSignal): Promise<void>;
643
+ /**
644
+ * Retry the current context or start a turn with queued input. Set `queuedOnly`
645
+ * to drain the queue without making a model call on its own when nothing is delivered.
646
+ */
647
+ continue(signal?: AbortSignal, options?: {
648
+ queuedOnly?: boolean;
649
+ }): Promise<void>;
628
650
  }
@@ -14,6 +14,7 @@
14
14
  * message delta is a cache miss each turn.
15
15
  */
16
16
  import type { Context, Message, Tool } from "@oh-my-pi/pi-ai";
17
+ import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
17
18
  import type { AgentContext } from "./types.js";
18
19
  /** Frozen system prompt + tool spec snapshot. */
19
20
  export interface StablePrefixSnapshot {
@@ -29,6 +30,8 @@ export interface BuildOptions {
29
30
  intentDescription?: string;
30
31
  /** Strip tool descriptions from the provider-bound specs (must match normalizeTools). */
31
32
  pruneToolDescriptions?: boolean;
33
+ /** A fork's owner-worded descriptions (must match normalizeTools). */
34
+ inheritedToolDescriptions?: InheritedToolDescriptions;
32
35
  }
33
36
  /**
34
37
  * A frozen prefix (system prompt + tools) that produces stable byte
@@ -58,6 +58,13 @@ export interface CompactionSettings {
58
58
  * explicit value — even one equal to the default — is always honored.
59
59
  */
60
60
  reserveTokens?: number;
61
+ /**
62
+ * Opt-in output budget for regular history summaries, replacing the default
63
+ * `min(floor(0.8 × reserveTokens), MAX_SUMMARY_TOKENS)` and clamped to the
64
+ * summarizer's own output limit. Turn-prefix and provider-native summaries
65
+ * keep their defaults. Unset keeps the default budget.
66
+ */
67
+ summaryMaxTokens?: number;
61
68
  keepRecentTokens: number;
62
69
  autoContinue?: boolean;
63
70
  remoteEnabled?: boolean;
@@ -67,6 +74,14 @@ export interface CompactionSettings {
67
74
  }
68
75
  /** Reserve applied when {@link CompactionSettings.reserveTokens} is unset. */
69
76
  export declare const DEFAULT_RESERVE_TOKENS = 16384;
77
+ /**
78
+ * Ceiling on the default compaction trigger (`thresholdPercent`/`thresholdTokens`
79
+ * unset). Every request re-reads the whole context from the prompt cache, so the
80
+ * cost of a long cycle grows with absolute size, not with the window's share:
81
+ * 1M-class windows (past ~812K, where 85% would land above this) compact here.
82
+ * A configured percentage, fixed trigger, or model base is not capped.
83
+ */
84
+ export declare const DEFAULT_THRESHOLD_CEILING_TOKENS = 690000;
70
85
  /**
71
86
  * Hysteresis band under the compaction trigger. Maintenance counts as having
72
87
  * resolved threshold pressure only when residual context lands at or below
@@ -208,6 +223,8 @@ export interface SummaryOptions {
208
223
  /** Additional summary context fetched only when a compaction request consumes it. */
209
224
  loadExtraContext?: () => Promise<string[] | undefined>;
210
225
  remoteEndpoint?: string;
226
+ /** Configured regular-summary output budget; see {@link CompactionSettings.summaryMaxTokens}. */
227
+ summaryMaxTokens?: number;
211
228
  /** Stable system-prompt segments from the live turn, preserved for provider cache reuse. */
212
229
  remoteSystemPrompt?: string[];
213
230
  initiatorOverride?: MessageAttribution;
@@ -330,8 +347,8 @@ export interface HandoffFromContextOptions {
330
347
  * session's payload/response hooks. Sending the same routing + payload shape
331
348
  * the main loop uses is what lets the handoff oneshot READ the provider
332
349
  * prompt cache the live turn populated instead of cold-missing the whole
333
- * prefix. `reasoning` and `toolChoice` are set internally and override
334
- * anything provided here.
350
+ * prefix. `maxTokens`, `reasoning` and `toolChoice` are set internally and
351
+ * override anything provided here.
335
352
  */
336
353
  streamOptions: SimpleStreamOptions;
337
354
  /** Optional completion transport override for host-level request wrappers. */
@@ -32,6 +32,8 @@ export interface BranchSummaryMessage {
32
32
  }
33
33
  export interface CompactionSummaryMessage {
34
34
  role: "compactionSummary";
35
+ /** Runtime replay state: a spoken delegation was still open at the retained-history boundary. */
36
+ liveVoiceOpen?: true;
35
37
  summary: string;
36
38
  shortSummary?: string;
37
39
  tokensBefore: number;
@@ -1,5 +1,6 @@
1
1
  export * from "./agent.js";
2
2
  export * from "./agent-loop.js";
3
+ export * from "./inherited-tool-descriptions.js";
3
4
  export * from "./append-only-context.js";
4
5
  export * from "./compaction.js";
5
6
  export * from "./output-budget.js";
@@ -0,0 +1,23 @@
1
+ import type { Tool } from "@oh-my-pi/pi-ai";
2
+ /**
3
+ * Tool descriptions a fork sends in its owner's wording, so its requests open
4
+ * with the owner's cached prefix.
5
+ *
6
+ * A fork (`/tan`) continues its owner's transcript, but its tools render their
7
+ * descriptions from session state it does not share: no UI, no TUI transcript,
8
+ * a headless approval mode. Any byte of that drift sits ahead of the transcript,
9
+ * so the fork misses the owner's prompt cache entirely and, on prefix-bound
10
+ * reasoning (Claude, GPT-6.2), the provider drops every inherited thinking block.
11
+ *
12
+ * Only wording is inherited: a tool whose wire schema differs from the owner's
13
+ * keeps its own spec, so the model never sees arguments the fork's tool rejects.
14
+ * A pin holds while the fork's own description still renders as it did when
15
+ * pinned; once it changes (a setting, an MCP reload), the fork's own wording wins.
16
+ */
17
+ export declare class InheritedToolDescriptions {
18
+ #private;
19
+ /** Pin `owner`'s description of every tool `own` declares with the same wire schema but other wording. */
20
+ constructor(own: readonly Tool[], owner: readonly Tool[]);
21
+ /** The description to send for `name`, given the one the fork renders now. */
22
+ resolve(name: string, description: string): string;
23
+ }
@@ -3,6 +3,7 @@ import type { Dialect } from "@oh-my-pi/pi-ai/dialect";
3
3
  import type { HarmonyAuditEvent } from "@oh-my-pi/pi-ai/utils/harmony-leak";
4
4
  import type { AppendOnlyContextManager } from "./append-only-context.js";
5
5
  import type { AgentRunCoverage, AgentRunSummary } from "./run-collector.js";
6
+ import type { InheritedToolDescriptions } from "./inherited-tool-descriptions.js";
6
7
  import type { SentToolDefinitions } from "./sent-tool-definitions.js";
7
8
  import type { AgentTelemetryConfig } from "./telemetry.js";
8
9
  /** Stream function - can return sync or Promise for async config lookup */
@@ -63,6 +64,8 @@ export interface AgentTurnEndContext {
63
64
  additionalMessages?: AgentMessage[];
64
65
  /** True when the current tool-loop batch is continuing without yielding to post-turn steering. */
65
66
  willContinue: boolean;
67
+ /** Tool calls in `message` that resolved to no tool (unknown name), so nothing ran. */
68
+ unresolvedToolCallIds?: string[];
66
69
  }
67
70
  export interface AgentPreModelCallStop {
68
71
  /** Stop the agent loop before sending the next provider request. */
@@ -227,6 +230,8 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
227
230
  transformProviderContext?: (context: Context, model: Model, signal?: AbortSignal) => Context | Promise<Context>;
228
231
  /** Remembers sent tool definitions to fill {@link Context.inactiveTools}. */
229
232
  sentToolDefinitions?: SentToolDefinitions;
233
+ /** A fork's owner-worded tool descriptions; see {@link InheritedToolDescriptions}. */
234
+ inheritedToolDescriptions?: InheritedToolDescriptions;
230
235
  /**
231
236
  * Resolves the API key or resolver for the current model before each LLM call.
232
237
  *
@@ -1002,7 +1007,7 @@ export type ToolLoadMode = "essential" | "discoverable";
1002
1007
  * - object form — adds a `reason` (shown in the prompt) and/or `override: true`
1003
1008
  * (force-prompt even in modes that would otherwise auto-approve this tier).
1004
1009
  * `policy: "deny"` blocks the call at the approval gate.
1005
- * - function — dynamic, given parsed args. Returns either form above.
1010
+ * - function — dynamic, given parsed args and an optional {@link ToolApprovalQuery}. Returns either form above.
1006
1011
  *
1007
1012
  * Omitted approvals are treated as "exec" by callers that enforce approvals.
1008
1013
  */
@@ -1012,7 +1017,16 @@ export type ToolApprovalDecision = ToolTier | {
1012
1017
  override?: boolean;
1013
1018
  policy?: "allow" | "deny" | "prompt";
1014
1019
  };
1015
- export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
1020
+ export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext, query?: ToolApprovalQuery) => ToolApprovalDecision);
1021
+ /** How the caller of a dynamic {@link ToolApproval} uses its decision. */
1022
+ export interface ToolApprovalQuery {
1023
+ /**
1024
+ * `false` when only `tier` and an explicit `policy` can affect the outcome: the gate
1025
+ * auto-approves every tier (yolo), or the caller reads just the tier. The tool may then
1026
+ * skip work that only feeds a prompt (`override`, `reason`). Absent means it may prompt.
1027
+ */
1028
+ prompts?: boolean;
1029
+ }
1016
1030
  /**
1017
1031
  * Context passed to tool execution.
1018
1032
  * Apps can extend via declaration merging.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@oh-my-pi/pi-agent-core",
4
- "version": "19.2.0",
4
+ "version": "19.3.0",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://omp.sh",
7
7
  "author": {
@@ -38,19 +38,19 @@
38
38
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
39
39
  },
40
40
  "dependencies": {
41
- "@oh-my-pi/pi-ai": "19.2.0",
42
- "@oh-my-pi/pi-catalog": "19.2.0",
43
- "@oh-my-pi/pi-natives": "19.2.0",
44
- "@oh-my-pi/pi-utils": "19.2.0",
45
- "@oh-my-pi/pi-wire": "19.2.0",
46
- "@oh-my-pi/snapcompact": "19.2.0",
47
- "@opentelemetry/api": "^1.9.1"
41
+ "@oh-my-pi/pi-ai": "19.3.0",
42
+ "@oh-my-pi/pi-catalog": "19.3.0",
43
+ "@oh-my-pi/pi-natives": "19.3.0",
44
+ "@oh-my-pi/pi-utils": "19.3.0",
45
+ "@oh-my-pi/pi-wire": "19.3.0",
46
+ "@oh-my-pi/snapcompact": "19.3.0",
47
+ "@opentelemetry/api": "^1.10.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@oh-my-pi/omptype": "19.2.0",
51
- "@opentelemetry/context-async-hooks": "2.9.0",
52
- "@opentelemetry/sdk-trace-base": "2.9.0",
53
- "@types/bun": "^1.3.14"
50
+ "@oh-my-pi/omptype": "19.3.0",
51
+ "@opentelemetry/context-async-hooks": "3.1.1",
52
+ "@opentelemetry/sdk-trace": "3.1.1",
53
+ "@types/bun": "^1.4.5"
54
54
  },
55
55
  "engines": {
56
56
  "bun": ">=1.4.4"
package/src/agent-loop.ts CHANGED
@@ -16,12 +16,14 @@ import {
16
16
  seedApiKeyResolver,
17
17
  streamSimple,
18
18
  stripSchemaDescriptions,
19
+ type Tool,
19
20
  type ToolCallProviderMetadata,
20
21
  type ToolChoice,
21
22
  type ToolResultMessage,
22
23
  type ToolResultProviderMetadata,
23
24
  type TSchema,
24
25
  toolWireSchema,
26
+ withRequestServiceTier,
25
27
  type UserMessage,
26
28
  } from "@oh-my-pi/pi-ai";
27
29
  import {
@@ -53,7 +55,7 @@ import {
53
55
  signalListLabel,
54
56
  } from "@oh-my-pi/pi-ai/utils/harmony-leak";
55
57
  import { isDsmlLeakRecoveryTarget, removeDsmlToolMarkupLeak } from "@oh-my-pi/pi-ai/utils/dsml-leak";
56
- import { cloneJsonTree, logger, sanitizeText, structuredCloneJSON, toError } from "@oh-my-pi/pi-utils";
58
+ import { cloneJsonTree, Laps, logger, sanitizeText, structuredCloneJSON, toError } from "@oh-my-pi/pi-utils";
57
59
  import { INTENT_FIELD } from "@oh-my-pi/pi-wire";
58
60
  import { LiveSteeringChannel } from "./live-steering";
59
61
  import { agentPauseGate } from "./pause";
@@ -75,6 +77,7 @@ import {
75
77
  startExecuteToolSpan,
76
78
  startInvokeAgentSpan,
77
79
  } from "./telemetry";
80
+ import type { InheritedToolDescriptions } from "./inherited-tool-descriptions";
78
81
  import { validateAgentToolArguments } from "./tool-arguments";
79
82
  import {
80
83
  createAdditionalContextMessage,
@@ -1090,6 +1093,8 @@ export interface NormalizeToolsOptions {
1090
1093
  intentDescription?: string;
1091
1094
  /** Strip descriptions from the wire specs when the catalog rides in the system prompt. */
1092
1095
  pruneDescriptions?: boolean;
1096
+ /** A fork's owner-worded descriptions; see {@link InheritedToolDescriptions}. */
1097
+ inheritedDescriptions?: InheritedToolDescriptions;
1093
1098
  }
1094
1099
 
1095
1100
  export function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"] {
@@ -1111,7 +1116,7 @@ export function normalizeTools(tools: AgentContext["tools"], options: NormalizeT
1111
1116
  const parameters = (
1112
1117
  doInjectIntent ? memoizedInjectIntentIntoSchema(stripped, intentMode, undefined) : stripped
1113
1118
  ) as TSchema;
1114
- return { ...t, parameters, description: "" };
1119
+ return toolSpec(t, parameters, "");
1115
1120
  }
1116
1121
  const wire = toolWireSchema(t);
1117
1122
  const parameters = (
@@ -1120,10 +1125,31 @@ export function normalizeTools(tools: AgentContext["tools"], options: NormalizeT
1120
1125
  const description = t.description ?? "";
1121
1126
  const examplesBlock = renderToolExamples({ ...t, parameters }, doInjectIntent ? INTENT_FIELD : undefined);
1122
1127
  const finalDescription = examplesBlock ? `${description}\n\n${examplesBlock}` : description;
1123
- return { ...t, parameters, description: finalDescription };
1128
+ return toolSpec(
1129
+ t,
1130
+ parameters,
1131
+ options.inheritedDescriptions?.resolve(t.name, finalDescription) ?? finalDescription,
1132
+ );
1124
1133
  });
1125
1134
  }
1126
1135
 
1136
+ /**
1137
+ * The provider-bound spec of `t`: its {@link Tool} fields and nothing else.
1138
+ * Tool instances carry host state (a tool's `session`, renderers, caches) that a
1139
+ * spread would copy into the context, where transports serializing it whole
1140
+ * (`pi-native`, proxy) ship it with every request.
1141
+ */
1142
+ function toolSpec(t: AgentTool, parameters: TSchema, description: string): Tool {
1143
+ const spec: Tool = { name: t.name, description, parameters };
1144
+ if (t.strict !== undefined) spec.strict = t.strict;
1145
+ if (t.deferLoading !== undefined) spec.deferLoading = t.deferLoading;
1146
+ if (t.customFormat !== undefined) spec.customFormat = t.customFormat;
1147
+ if (t.customWireName !== undefined) spec.customWireName = t.customWireName;
1148
+ if (t.native !== undefined) spec.native = t.native;
1149
+ if (t.examples !== undefined) spec.examples = t.examples;
1150
+ return spec;
1151
+ }
1152
+
1127
1153
  function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional" | "omit" {
1128
1154
  if (typeof intent === "function") return "omit";
1129
1155
  if (intent === "optional" || intent === "omit") return intent;
@@ -1299,6 +1325,9 @@ async function runLoopBody(
1299
1325
  let preserveSoftRequirementState = false;
1300
1326
 
1301
1327
  let pendingMessages: AgentMessage[] = [];
1328
+ // From the run's start or a dequeue of input to the request carrying it: that input shows in
1329
+ // the transcript only once the request opens, so the wait is logged (debug) with its phases.
1330
+ let deliveryLaps: Laps | undefined = new Laps();
1302
1331
  // Steering the provider took from the queue during the last response:
1303
1332
  // `liveAccepted` reached the model inside it, `liveDeferred` did not.
1304
1333
  let liveAccepted: AgentMessage[] = [];
@@ -1334,6 +1363,7 @@ async function runLoopBody(
1334
1363
  // the messages in a run that is about to die.
1335
1364
  try {
1336
1365
  pendingMessages = signal?.aborted ? [] : (await config.getSteeringMessages?.(signal)) || [];
1366
+ deliveryLaps.lap("steeringMs");
1337
1367
  } catch (error) {
1338
1368
  if (signal?.aborted && (await endAbortedBeforeModel(messagesToEmit, false))) return;
1339
1369
  stream.push({ type: "turn_start" });
@@ -1391,9 +1421,11 @@ async function runLoopBody(
1391
1421
  );
1392
1422
  await emitTurnEnd(stream, currentContext, resumeTail, executionResult.toolResults, config, signal, {
1393
1423
  willContinue: !isDeadlineExceeded(config.deadline),
1424
+ unresolvedToolCallIds: executionResult.unresolvedToolCallIds,
1394
1425
  ...(resumeContextMessage ? { additionalMessages: [resumeContextMessage] } : {}),
1395
1426
  });
1396
1427
  turnOpen = false;
1428
+ deliveryLaps.lap("resumedToolsMs");
1397
1429
  // A tool hook may mark its completed result as terminal (e.g. subagent
1398
1430
  // yield) — same stop-before-next-model-call rule as the main loop.
1399
1431
  if (signal?.reason === TERMINAL_TOOL_RESULT_ABORT_REASON) {
@@ -1416,7 +1448,12 @@ async function runLoopBody(
1416
1448
  // Park at the turn boundary while the process-wide pause gate is
1417
1449
  // engaged (host /pause). An external abort releases the park so a
1418
1450
  // cancelled run still unwinds while everything else stays frozen.
1419
- if (agentPauseGate.paused) await waitForProcessPause(config, signal);
1451
+ if (agentPauseGate.paused) {
1452
+ await waitForProcessPause(config, signal);
1453
+ deliveryLaps?.lap("pausedMs");
1454
+ }
1455
+ let laps = deliveryLaps;
1456
+ deliveryLaps = undefined;
1420
1457
 
1421
1458
  // Build the provider-bound context before opening the turn. Queue
1422
1459
  // messages are added now but their events remain deferred until
@@ -1436,6 +1473,11 @@ async function runLoopBody(
1436
1473
  let preparedProviderCall: PreparedProviderCall;
1437
1474
  let gateResult: AgentPreModelCallResult;
1438
1475
  const emitTurnInputs = () => {
1476
+ if (laps) {
1477
+ laps.lap("requestSetupMs");
1478
+ logger.debug("Input reached its model request", { count: turnMessages.length, ...laps.record() });
1479
+ laps = undefined;
1480
+ }
1439
1481
  emitInputMessages(
1440
1482
  stream,
1441
1483
  signal?.aborted
@@ -1447,6 +1489,7 @@ async function runLoopBody(
1447
1489
  if (config.syncContextBeforeModelCall) {
1448
1490
  await config.syncContextBeforeModelCall(currentContext, signal);
1449
1491
  }
1492
+ laps?.lap("syncContextMs");
1450
1493
  if (signal?.aborted && (await endAbortedBeforeModel(turnMessages, turnOpen))) return;
1451
1494
 
1452
1495
  if (!directiveResolvedForTurn) {
@@ -1477,9 +1520,11 @@ async function runLoopBody(
1477
1520
  }
1478
1521
 
1479
1522
  preparedProviderCall = await prepareProviderCall(currentContext, config, signal);
1523
+ laps?.lap("prepareProviderMs");
1480
1524
  if (signal?.aborted && (await endAbortedBeforeModel(turnMessages, turnOpen))) return;
1481
1525
  preparedProviderCall.liveSteering = openLiveSteering(config, signal, preparedProviderCall);
1482
1526
  gateResult = (await config.beforeModelCall?.(preparedProviderCall.context, signal)) || undefined;
1527
+ laps?.lap("beforeModelCallMs");
1483
1528
  } catch (error) {
1484
1529
  if (signal?.aborted && (await endAbortedBeforeModel(turnMessages, turnOpen))) return;
1485
1530
  if (!turnOpen) {
@@ -1738,6 +1783,7 @@ async function runLoopBody(
1738
1783
 
1739
1784
  const toolResults: ToolResultMessage[] = [];
1740
1785
  const additionalMessages: AgentMessage[] = [];
1786
+ let unresolvedToolCallIds: string[] | undefined;
1741
1787
  if (softNonCompliant && softRequiredTool !== undefined) {
1742
1788
  SpeculativeOperationCoordinator.discardForMessage(message, "soft tool requirement deferred execution");
1743
1789
  // A soft-required tool is pending but the model called something else
@@ -1792,6 +1838,7 @@ async function runLoopBody(
1792
1838
  [...liveAccepted, ...liveDeferred],
1793
1839
  );
1794
1840
  toolResults.push(...executionResult.toolResults);
1841
+ unresolvedToolCallIds = executionResult.unresolvedToolCallIds;
1795
1842
 
1796
1843
  for (const result of toolResults) {
1797
1844
  currentContext.messages.push(result);
@@ -1876,6 +1923,7 @@ async function runLoopBody(
1876
1923
  await emitTurnEnd(stream, currentContext, message, toolResults, config, signal, {
1877
1924
  additionalMessages,
1878
1925
  willContinue: hasMoreToolCalls && !isDeadlineExceeded(config.deadline),
1926
+ unresolvedToolCallIds,
1879
1927
  });
1880
1928
  turnOpen = false;
1881
1929
 
@@ -1906,12 +1954,16 @@ async function runLoopBody(
1906
1954
  // for the next boundary (or is steered into that response).
1907
1955
  pendingMessages = live;
1908
1956
  } else {
1957
+ const steeringLaps = new Laps();
1909
1958
  const steering = signal?.aborted
1910
1959
  ? []
1911
1960
  : [...live, ...((await config.getSteeringMessages?.(signal)) || [])];
1961
+ steeringLaps.lap("steeringMs");
1962
+ if (steering.length > 0) deliveryLaps = steeringLaps;
1912
1963
  if (hasMoreToolCalls) {
1913
1964
  // Mid-work: fold any non-interrupting asides into the next turn alongside steering.
1914
1965
  const asides = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.("work"));
1966
+ steeringLaps.lap("asidesMs");
1915
1967
  pendingMessages = asides.length > 0 ? [...steering, ...asides] : steering;
1916
1968
  } else {
1917
1969
  // Stop boundary: only steering (live user input) forces another turn here. Leave
@@ -1928,7 +1980,9 @@ async function runLoopBody(
1928
1980
  }
1929
1981
 
1930
1982
  // Agent would stop here. Drain non-interrupting asides + follow-up messages.
1983
+ const yieldLaps = new Laps();
1931
1984
  await config.onBeforeYield?.();
1985
+ yieldLaps.lap("beforeYieldMs");
1932
1986
 
1933
1987
  if (isDeadlineExceeded(config.deadline)) {
1934
1988
  endAgentStream(stream, newMessages, telemetry, stepCounter.count);
@@ -1939,11 +1993,15 @@ async function runLoopBody(
1939
1993
  // above and this yield point (e.g. queued while onBeforeYield ran). Without
1940
1994
  // this poll it would strand in the queue until the next manual prompt.
1941
1995
  const lateSteering = signal?.aborted ? [] : (await config.getSteeringMessages?.(signal)) || [];
1996
+ yieldLaps.lap("steeringMs");
1942
1997
  const asideMessages = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.("stop"));
1998
+ yieldLaps.lap("asidesMs");
1943
1999
  const followUpMessages = signal?.aborted ? [] : (await config.getFollowUpMessages?.(signal)) || [];
2000
+ yieldLaps.lap("followUpMs");
1944
2001
  if (lateSteering.length > 0 || asideMessages.length > 0 || followUpMessages.length > 0) {
1945
2002
  // Set as pending so the inner loop processes them before stopping.
1946
2003
  pendingMessages = [...lateSteering, ...asideMessages, ...followUpMessages];
2004
+ if (lateSteering.length > 0 || followUpMessages.length > 0) deliveryLaps = yieldLaps;
1947
2005
  continue;
1948
2006
  }
1949
2007
 
@@ -2075,6 +2133,7 @@ async function prepareProviderCall(
2075
2133
  injectIntent: !!config.intentTracing,
2076
2134
  intentDescription: config.intentDescription,
2077
2135
  pruneDescriptions: !!config.pruneToolDescriptions && !ownedDialect,
2136
+ inheritedDescriptions: config.inheritedToolDescriptions,
2078
2137
  };
2079
2138
  let llmContext: Context;
2080
2139
  if (config.appendOnlyContext) {
@@ -2083,6 +2142,7 @@ async function prepareProviderCall(
2083
2142
  intentTracing: toolOptions.injectIntent,
2084
2143
  intentDescription: toolOptions.intentDescription,
2085
2144
  pruneToolDescriptions: toolOptions.pruneDescriptions,
2145
+ inheritedToolDescriptions: toolOptions.inheritedDescriptions,
2086
2146
  });
2087
2147
  } else {
2088
2148
  llmContext = {
@@ -2176,7 +2236,11 @@ async function streamAssistantResponse(
2176
2236
  : providerAbortSignals.length === 1
2177
2237
  ? providerAbortSignals[0]!
2178
2238
  : AbortSignal.any(providerAbortSignals);
2179
- const requestApiKey = (config.getApiKey ? await config.getApiKey(model) : undefined) ?? config.apiKey;
2239
+ // The credential is chosen for the tier this request will ask for.
2240
+ const requestApiKey = withRequestServiceTier(
2241
+ (config.getApiKey ? await config.getApiKey(model) : undefined) ?? config.apiKey,
2242
+ effectiveServiceTier,
2243
+ );
2180
2244
  let resolvedCredential: ApiKeyResolution;
2181
2245
  const resolvedApiKey = await resolveApiKeyOnce(requestApiKey, finalRequestSignal, resolved => {
2182
2246
  resolvedCredential = resolved;
@@ -3392,7 +3456,7 @@ async function executeToolCalls(
3392
3456
  // Steering the provider took off the queue during the response that emitted
3393
3457
  // this batch; it injects at this batch's boundary like queued steering.
3394
3458
  liveSteering: readonly AgentMessage[],
3395
- ): Promise<{ toolResults: ToolResultMessage[]; additionalContext?: string }> {
3459
+ ): Promise<{ toolResults: ToolResultMessage[]; additionalContext?: string; unresolvedToolCallIds: string[] }> {
3396
3460
  const tools = currentContext.tools;
3397
3461
  const {
3398
3462
  hasSteeringMessages,
@@ -4035,7 +4099,7 @@ async function executeToolCalls(
4035
4099
  const approval = record.tool?.approval;
4036
4100
  let decision: ToolApprovalDecision | undefined;
4037
4101
  try {
4038
- decision = typeof approval === "function" ? approval(record.args) : approval;
4102
+ decision = typeof approval === "function" ? approval(record.args, undefined, { prompts: false }) : approval;
4039
4103
  } catch {
4040
4104
  decision = undefined;
4041
4105
  }
@@ -4083,6 +4147,7 @@ async function executeToolCalls(
4083
4147
  return {
4084
4148
  toolResults: emittedToolResults,
4085
4149
  ...(additionalContext !== undefined ? { additionalContext } : {}),
4150
+ unresolvedToolCallIds: records.filter(record => record.tool === undefined).map(record => record.toolCall.id),
4086
4151
  };
4087
4152
  }
4088
4153