@linxiraos/pi-agent-core 1.4.6 → 1.4.9

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
@@ -1,8 +1,12 @@
1
1
  ## [Unreleased]
2
2
 
3
- ## [1.4.6] - 2026-10-28
3
+ ## [1.4.9] - 2026-11-03
4
+
5
+ - Synced with upstream OMP v18.16.0; user-visible changes ride the coding-agent package.
4
6
 
5
- - Released as part of Zeta 1.4.6; no package-specific user-visible changes.
7
+ ### Changed
8
+
9
+ - Switched from local `@linxiraos/pi-ai` to upstream `@mariozechner/pi-ai` package
6
10
 
7
11
  ## [9.2.2] - 2026-01-31
8
12
 
@@ -79,10 +83,6 @@
79
83
 
80
84
  ## [3.21.0] - 2026-01-06
81
85
 
82
- ### Changed
83
-
84
- - Switched from local `@linxiraos/pi-ai` to upstream `@mariozechner/pi-ai` package
85
-
86
86
  ### Added
87
87
 
88
88
  - Added `sessionId` option for provider caching (e.g., OpenAI Codex session-based prompt caching)
@@ -134,6 +134,17 @@
134
134
 
135
135
  Initial release under @oh-my-pi scope. See previous releases at [badlogic/pi-mono](https://github.com/badlogic/pi-mono).
136
136
 
137
+ ## [1.4.6] - 2026-10-28
138
+
139
+ ### Breaking Changes
140
+
141
+ - Removed the Bun event-loop workaround utilities from `@oh-my-pi/pi-agent-core/utils/yield`; agent loops no longer insert cooperative sleeps while streaming or between tool calls.
142
+
143
+ ### Added
144
+
145
+ - Added `AgentTool.approvalRestrictionPaths` so tools can report the paths they read, allowing restricted-folder approvals to cover those paths without remembering approval separately for each path.
146
+ - Added `Agent.logContext`, which adds custom context fields to every log record written during an agent run.
147
+
137
148
  ## [1.4.5] - 2026-10-28
138
149
 
139
150
  - Synced with upstream OMP v18.13.2: a subagent's final report is no longer consumed as its reply to a peer message that arrived as the run finished; same-workspace peers can message each other.
@@ -2,6 +2,7 @@ import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Co
2
2
  import type { Dialect } from "@linxiraos/pi-ai/dialect";
3
3
  import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
4
4
  import type { AppendOnlyContextManager } from "./append-only-context.js";
5
+ import { SentToolDefinitions } from "./sent-tool-definitions.js";
5
6
  import { Tokenizer } from "./tokenizer.js";
6
7
  import type { AgentBeforeModelCall, AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideBoundary, AsideMessage, PrepareQueuedMessages, SpeculativeToolExecutionConfig, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types.js";
7
8
  export declare class AgentBusyError extends Error {
@@ -64,6 +65,11 @@ export interface AgentOptions {
64
65
  * Shared provider state map for session-scoped transport/session caches.
65
66
  */
66
67
  providerSessionState?: Map<string, ProviderSessionState>;
68
+ /**
69
+ * Tool definitions already sent, for an Agent that replays another Agent's request history
70
+ * (see {@link Agent.copySentToolDefinitions}). Defaults to an empty store.
71
+ */
72
+ sentToolDefinitions?: SentToolDefinitions;
67
73
  /**
68
74
  * Resolves an API key or resolver dynamically for each LLM call.
69
75
  * Useful for expiring tokens and model-scoped credential routing.
@@ -295,6 +301,16 @@ export declare class Agent {
295
301
  * Set the prompt cache key forwarded to providers.
296
302
  */
297
303
  set promptCacheKey(value: string | undefined);
304
+ /**
305
+ * A detached copy of the tool definitions this agent has sent (`AgentOptions.sentToolDefinitions`), without the
306
+ * names `keep` rejects.
307
+ */
308
+ copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions;
309
+ /**
310
+ * Fields added to every log record written while this agent runs (the
311
+ * owning session's `sessionId`), so in-process agents' records stay apart.
312
+ */
313
+ logContext: Readonly<Record<string, unknown>> | undefined;
298
314
  /**
299
315
  * Static metadata forwarded to every API request when no resolver is installed
300
316
  * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
@@ -379,6 +395,13 @@ export declare class Agent {
379
395
  /** Strip tool descriptions from provider-bound specs; read per request. */
380
396
  get pruneToolDescriptions(): boolean;
381
397
  set pruneToolDescriptions(value: boolean);
398
+ /**
399
+ * Whether requests to `model` actually ship description-stripped tool specs.
400
+ * Owned dialects render full definitions in-band, so they never prune; the
401
+ * loop applies the same rule (`pruneToolDescriptions && !ownedDialect`).
402
+ * Context accounting reads this instead of the raw setting.
403
+ */
404
+ prunesToolDescriptions(model: Model | undefined): boolean;
382
405
  /** Inject/strip the intent field on tool calls; applies from the next prompt run. */
383
406
  get intentTracing(): boolean;
384
407
  set intentTracing(value: boolean);
@@ -5,12 +5,12 @@
5
5
  * a summary of the branch being left so context isn't lost.
6
6
  */
7
7
  import type { Api, ApiKey, AssistantMessage, Context, Model, SimpleStreamOptions } from "@linxiraos/pi-ai";
8
+ import * as snapcompact from "@linxiraos/pi-snapcompact";
8
9
  import { type AgentTelemetry } from "../telemetry.js";
9
10
  import { Tokenizer } from "../tokenizer.js";
10
11
  import type { AgentMessage } from "../types.js";
11
12
  import type { ReadonlySessionManager, SessionEntry } from "./entries.js";
12
13
  import { type ConvertToLlm } from "./messages.js";
13
- import { type FileOperations } from "./utils.js";
14
14
  export interface BranchSummaryResult {
15
15
  summary?: string;
16
16
  readFiles?: string[];
@@ -23,12 +23,11 @@ export interface BranchSummaryDetails {
23
23
  readFiles: string[];
24
24
  modifiedFiles: string[];
25
25
  }
26
- export type { FileOperations } from "./utils.js";
27
26
  export interface BranchPreparation {
28
27
  /** Messages extracted for summarization, in chronological order */
29
28
  messages: AgentMessage[];
30
29
  /** File operations extracted from tool calls */
31
- fileOps: FileOperations;
30
+ fileOps: snapcompact.FileOperations;
32
31
  /** Total estimated tokens in messages */
33
32
  totalTokens: number;
34
33
  }
@@ -7,7 +7,7 @@
7
7
  * compaction item as replacement history.
8
8
  */
9
9
  import type { Api, CodexCompactionContext, FetchImpl, Model, ProviderSessionState } from "@linxiraos/pi-ai";
10
- import { type OpenAICodexCompactionBody } from "@linxiraos/pi-ai/providers/openai-codex-responses";
10
+ import type { OpenAICodexCompactionBody } from "@linxiraos/pi-ai/providers/openai-codex-responses";
11
11
  import type { CatalogPolicyInputs } from "@linxiraos/pi-catalog/types";
12
12
  /** Retained-message budget Codex uses after streamed V2 compaction. */
13
13
  export declare const V2_RETAINED_MESSAGE_TOKEN_BUDGET = 64000;
@@ -85,6 +85,7 @@ export declare function requestCompactionV2Streaming(model: Model, apiKey: strin
85
85
  providerSessionState?: Map<string, ProviderSessionState>;
86
86
  codexCompaction?: CodexCompactionContext;
87
87
  preferWebsockets?: boolean;
88
+ codexAccessPrograms?: boolean;
88
89
  }): Promise<CompactionV2Response>;
89
90
  /** Build Codex-style V2 replacement history from retention candidates plus compaction output. */
90
91
  export declare function buildCompactionV2ReplacementHistory(input: unknown[], compactionItem: Record<string, unknown>, retainedMessageBudget?: number): {
@@ -5,13 +5,13 @@
5
5
  * and after compaction the session is reloaded.
6
6
  */
7
7
  import { type Api, type ApiKey, type AssistantMessage, type CodexCompactionContext, type Context, type FetchImpl, type MessageAttribution, type Model, type OneshotRetryOptions, type ProviderSessionState, type SimpleStreamOptions, type Tool, type Usage } from "@linxiraos/pi-ai";
8
+ import * as snapcompact from "@linxiraos/pi-snapcompact";
8
9
  import { type AgentTelemetry } from "../telemetry.js";
9
10
  import { ThinkingLevel } from "../thinking.js";
10
11
  import { Tokenizer } from "../tokenizer.js";
11
12
  import type { AgentMessage } from "../types.js";
12
13
  import type { SessionEntry } from "./entries.js";
13
14
  import { type ConvertToLlm } from "./messages.js";
14
- import { type FileOperations } from "./utils.js";
15
15
  /** Details stored in CompactionEntry.details for file tracking */
16
16
  export interface CompactionDetails {
17
17
  readFiles: string[];
@@ -256,6 +256,8 @@ export interface SummaryOptions {
256
256
  providerSessionState?: Map<string, ProviderSessionState>;
257
257
  /** Whether Codex remote compaction should prefer the provider WebSocket transport. */
258
258
  preferWebsockets?: boolean;
259
+ /** Daybreak Blue request on Codex remote compaction; see `StreamOptions.codexAccessPrograms`. */
260
+ codexAccessPrograms?: boolean;
259
261
  /** Classification shared by every provider request in this logical compaction. */
260
262
  codexCompaction?: CodexCompactionContext;
261
263
  /** Provider-visible tools for remote compaction transports that replay native tool history. */
@@ -366,7 +368,7 @@ export interface CompactionPreparation {
366
368
  /** Preserved opaque compaction payload from the previous compaction, if any. */
367
369
  previousPreserveData?: Record<string, unknown>;
368
370
  /** File operations extracted from messagesToSummarize */
369
- fileOps: FileOperations;
371
+ fileOps: snapcompact.FileOperations;
370
372
  /** Compaction settions from settings.jsonl */
371
373
  settings: CompactionSettings;
372
374
  }
@@ -3,13 +3,14 @@
3
3
  */
4
4
  import type { Message } from "@linxiraos/pi-ai";
5
5
  import { type Dialect } from "@linxiraos/pi-ai/dialect";
6
+ import * as snapcompact from "@linxiraos/pi-snapcompact";
6
7
  import type { AgentMessage } from "../types.js";
7
- export interface FileOperations {
8
- read: Set<string>;
9
- written: Set<string>;
10
- edited: Set<string>;
11
- }
12
- export declare function createFileOps(): FileOperations;
8
+ /** @deprecated Import these from `@linxiraos/pi-snapcompact`. */
9
+ export { computeFileLists, createFileOps, type FileOperations, isUrlSchemePath, upsertFileOperations, } from "@linxiraos/pi-snapcompact";
10
+ /** @deprecated Use `upsertFileOperations("", readFiles, modifiedFiles, readSet)` from `@linxiraos/pi-snapcompact`. */
11
+ export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
12
+ /** Error text for a summarization call that hit its output limit (`stopReason: "length"`): partial text is never used. */
13
+ export declare function incompleteOutputError(prefix: string): string;
13
14
  /**
14
15
  * Split a read-tool path into its base path and trailing selector, mirroring the
15
16
  * read tool's own splitter. Single source of the grammar in this package: the
@@ -31,25 +32,10 @@ export declare function stripReadSelector(path: string): string;
31
32
  * than its plain lines: verbatim `raw` bytes or the merge `conflicts` view.
32
33
  */
33
34
  export declare function isAlternateFormReadSelector(sel: string): boolean;
34
- /**
35
- * Whether `path` references a `scheme://` URL (internal URI or web URL) rather
36
- * than a filesystem path that belongs in the compaction `<files>` summary.
37
- */
38
- export declare function isUrlSchemePath(path: string): boolean;
39
35
  /**
40
36
  * Extract file operations from tool calls in an assistant message.
41
37
  */
42
- export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void;
43
- /**
44
- * Compute final file lists from file operations.
45
- * Returns readFiles (files only read, not modified) and modifiedFiles.
46
- */
47
- export declare function computeFileLists(fileOps: FileOperations): {
48
- readFiles: string[];
49
- modifiedFiles: string[];
50
- };
51
- export declare function formatFileOperations(readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
52
- export declare function upsertFileOperations(summary: string, readFiles: string[], modifiedFiles: string[], readSet?: ReadonlySet<string>): string;
38
+ export declare function extractFileOpsFromMessage(message: AgentMessage, fileOps: snapcompact.FileOperations): void;
53
39
  /**
54
40
  * Truncate tool results to the same representation used in summarization prompts.
55
41
  */
@@ -15,4 +15,3 @@ export * from "./tool-context.js";
15
15
  export * from "./tokenizer.js";
16
16
  export * from "./tool-arguments.js";
17
17
  export * from "./types.js";
18
- export * from "./utils/yield.js";
@@ -1,4 +1,4 @@
1
- import type { Message, Tool } from "@linxiraos/pi-ai";
1
+ import type { Context, Tool } from "@linxiraos/pi-ai";
2
2
  /**
3
3
  * Last wire definition this Agent sent for each tool name, so a provider that keeps
4
4
  * withdrawn tools declared (Anthropic `tool_removal`) can re-declare them byte-identically.
@@ -9,9 +9,15 @@ export declare class SentToolDefinitions {
9
9
  /** Remember the definitions a request is about to send. */
10
10
  record(tools: readonly Tool[]): void;
11
11
  /**
12
- * Definitions for names the latest `requestControls.tools.declared` in `messages` holds
13
- * that are not in `active`; undefined when none. Names never sent by this Agent are
14
- * skipped: the provider drops them from the declaration.
12
+ * A detached copy: an Agent that replays another's request history declares the same withdrawn tools. `keep`
13
+ * leaves out a definition the copy must never declare.
15
14
  */
16
- inactiveFor(messages: readonly Message[], active: readonly Tool[]): Tool[] | undefined;
15
+ copy(keep?: (name: string) => boolean): SentToolDefinitions;
16
+ /**
17
+ * `context` with {@link Context.inactiveTools} set to the definitions for names the latest
18
+ * `requestControls.tools.declared` in its messages holds that are not in its `tools`; cleared when
19
+ * there are none or the request declares no tools. Names never sent by this Agent are skipped: the
20
+ * provider drops them from the declaration.
21
+ */
22
+ withInactiveTools(context: Context): Context;
17
23
  }
@@ -9,6 +9,8 @@ export declare function tokenizerEncodingForModel(model: Pick<Model, "tokenizer"
9
9
  type TokenizerModel = Pick<Model, "tokenizer"> & snapcompact.ShapeTarget & {
10
10
  compat?: Model["compat"];
11
11
  thinking?: Model["thinking"];
12
+ reasoning?: boolean;
13
+ requestModelId?: string;
12
14
  };
13
15
  /** Identity of the reader whose replayed reasoning a {@link Tokenizer} counts; equal keys count it alike. */
14
16
  export declare function reasoningReplayKey(model: TokenizerModel | null | undefined): string;
@@ -23,13 +25,12 @@ export interface TokenizerOptions {
23
25
  nativeHistoryReplay?: boolean;
24
26
  }
25
27
  /**
26
- * `strict` always tries an exact native count (the catalog-resolved tokenizer
27
- * when known, o200k_base otherwise), falling back to the byte upper bound when
28
- * the loaded addon does not recognize that encoding. `approximate` and
29
- * `upperbound` prefer the same exact count for known tokenizer families or
30
- * when `PI_TOKENIZER_ACCURATE=1` is set; otherwise they use a cheap heuristic:
31
- * `approximate` a bytes/4 guess, `upperbound` the raw byte length (never
32
- * undercounts).
28
+ * Every mode counts with the native tokenizer: the catalog-resolved family
29
+ * when known, o200k_base otherwise. They differ only in the fallback when the
30
+ * loaded addon does not recognize that encoding: `strict` and `upperbound`
31
+ * the raw byte length (never undercounts), `approximate` a bytes/4 guess.
32
+ * Tests (`NODE_ENV=test`) skip the native count outside `strict` and use that
33
+ * fallback.
33
34
  */
34
35
  export type TokenCountMode = "strict" | "approximate" | "upperbound";
35
36
  /** Options for {@link Tokenizer.countMessage} / {@link Tokenizer.countMessages}. */
@@ -68,8 +69,8 @@ export interface TokenBudgetCheck {
68
69
  * when the model's encoding, image or thinking-replay pricing, replay
69
70
  * identity or native-history replay state changes); one-shot flows construct
70
71
  * their own for the model that will be billed. Known tokenizer families use
71
- * exact native counts; unknown models keep the fast byte estimate (or o200k
72
- * when `PI_TOKENIZER_ACCURATE=1`).
72
+ * exact native counts; other models are counted in o200k_base, which bills
73
+ * unknown readers closer than a bytes/4 guess.
73
74
  */
74
75
  export declare class Tokenizer {
75
76
  #private;
@@ -588,7 +588,8 @@ export interface ToolCallContext {
588
588
  providerMetadata?: ToolCallProviderMetadata;
589
589
  /**
590
590
  * Cooperative steering signal: aborted when a queued user/steering message
591
- * (or an interrupting peer IRC) is detected while this tool batch runs.
591
+ * (or an interrupting peer IRC) is detected while this tool batch runs. Its
592
+ * `reason` names the source: a {@link SteeringInterruptSource} or `"irc"`.
592
593
  * Unlike the hard abort signal it NEVER kills the tool — long-running
593
594
  * tools MAY observe it (via `ctx.toolCall.steeringSignal`) to finish early
594
595
  * or background themselves so the message injects promptly; ignoring it is
@@ -967,7 +968,7 @@ export type ToolApprovalDecision = ToolTier | {
967
968
  * prompt policies to the tool it dispatches into. */
968
969
  policyKey?: string;
969
970
  };
970
- export type ToolApproval = ToolApprovalDecision | ((args: unknown) => ToolApprovalDecision);
971
+ export type ToolApproval = ToolApprovalDecision | ((args: unknown, context?: AgentToolContext) => ToolApprovalDecision);
971
972
  /**
972
973
  * Context passed to tool execution.
973
974
  * Apps can extend via declaration merging.
@@ -1111,6 +1112,11 @@ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any
1111
1112
  * approving the call can record them. Omit it (or return `undefined`) and the call prompts by tier.
1112
1113
  */
1113
1114
  approvalCacheTargets?: (args: unknown) => readonly string[] | undefined;
1115
+ /**
1116
+ * Paths a call reads beyond its working directory, matched against restricted folders when it
1117
+ * reports no `approvalCacheTargets`. Unlike cache targets they never key a remembered grant.
1118
+ */
1119
+ approvalRestrictionPaths?: (args: unknown) => readonly string[] | undefined;
1114
1120
  /** The main execution callback for this tool. */
1115
1121
  execute: AgentToolExecFn<TParameters, TDetails, TTheme>;
1116
1122
  /** Optional custom rendering for tool call display (returns UI component) */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@linxiraos/pi-agent-core",
4
- "version": "1.4.6",
4
+ "version": "1.4.9",
5
5
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
6
6
  "homepage": "https://linxira-os.github.io/zeta/",
7
7
  "author": "Linxira-OS",
@@ -35,22 +35,22 @@
35
35
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
36
36
  },
37
37
  "dependencies": {
38
- "@linxiraos/pi-ai": "1.4.6",
39
- "@linxiraos/pi-catalog": "1.4.6",
40
- "@linxiraos/pi-natives": "1.4.6",
41
- "@linxiraos/pi-utils": "1.4.6",
42
- "@linxiraos/pi-wire": "1.4.6",
43
- "@linxiraos/pi-snapcompact": "1.4.6",
38
+ "@linxiraos/pi-ai": "1.4.9",
39
+ "@linxiraos/pi-catalog": "1.4.9",
40
+ "@linxiraos/pi-natives": "1.4.9",
41
+ "@linxiraos/pi-utils": "1.4.9",
42
+ "@linxiraos/pi-wire": "1.4.9",
43
+ "@linxiraos/pi-snapcompact": "1.4.9",
44
44
  "@opentelemetry/api": "^1.9.1"
45
45
  },
46
46
  "devDependencies": {
47
- "@linxiraos/pi-omptype": "1.4.6",
47
+ "@linxiraos/pi-omptype": "1.4.9",
48
48
  "@opentelemetry/context-async-hooks": "^2.9.0",
49
49
  "@opentelemetry/sdk-trace-base": "^2.9.0",
50
- "@types/bun": "1.4.3"
50
+ "@types/bun": "1.4.4"
51
51
  },
52
52
  "engines": {
53
- "bun": ">=1.3.14"
53
+ "bun": ">=1.4.4"
54
54
  },
55
55
  "files": [
56
56
  "src",
package/src/agent-loop.ts CHANGED
@@ -53,7 +53,7 @@ import {
53
53
  signalListLabel,
54
54
  } from "@linxiraos/pi-ai/utils/harmony-leak";
55
55
  import { isDsmlLeakRecoveryTarget, removeDsmlToolMarkupLeak } from "@linxiraos/pi-ai/utils/dsml-leak";
56
- import { cloneJsonTree, logger, sanitizeText, structuredCloneJSON } from "@linxiraos/pi-utils";
56
+ import { cloneJsonTree, logger, sanitizeText, structuredCloneJSON, toError } from "@linxiraos/pi-utils";
57
57
  import { INTENT_FIELD } from "@linxiraos/pi-wire";
58
58
  import { LiveSteeringChannel } from "./live-steering";
59
59
  import { agentPauseGate } from "./pause";
@@ -109,7 +109,6 @@ import {
109
109
  isSoftToolRequirement,
110
110
  SPECULATIVE_STREAM_SESSION,
111
111
  } from "./types";
112
- import { yieldIfDue } from "./utils/yield";
113
112
 
114
113
  async function waitForProcessPause(config: AgentLoopConfig, signal?: AbortSignal): Promise<void> {
115
114
  try {
@@ -944,7 +943,8 @@ export function normalizeMessagesForProvider(
944
943
  });
945
944
  }
946
945
 
947
- const INTENT_FIELD_DESCRIPTION = "concise intent";
946
+ /** Schema description of the injected `i` field; `PI_INTENT_DESC` replaces it. */
947
+ const DEFAULT_INTENT_FIELD_DESCRIPTION = "concise intent";
948
948
  const INTENT_SCHEMA_UNION_KEYS = ["anyOf", "oneOf"] as const;
949
949
 
950
950
  // Memoize injection per input schema identity: normalizeTools runs on every
@@ -1021,7 +1021,7 @@ function injectIntentIntoSchema(
1021
1021
  ...schemaRecord,
1022
1022
  properties: {
1023
1023
  [INTENT_FIELD]: describeIntent
1024
- ? { type: "string", description: INTENT_FIELD_DESCRIPTION }
1024
+ ? { type: "string", description: Bun.env.PI_INTENT_DESC || DEFAULT_INTENT_FIELD_DESCRIPTION }
1025
1025
  : { type: "string" },
1026
1026
  ...properties,
1027
1027
  },
@@ -1071,13 +1071,6 @@ function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional"
1071
1071
  return "require";
1072
1072
  }
1073
1073
 
1074
- /**
1075
- * Longest `i` value accepted as an intent. The injected field is described as
1076
- * a "concise intent" (INTENT_FIELD_DESCRIPTION); anything past this is a tool
1077
- * payload the model put in the wrong field, not a label.
1078
- */
1079
- const MAX_INTENT_LENGTH = 200;
1080
-
1081
1074
  function extractIntent(args: Record<string, unknown>): { intent?: string; strippedArgs: Record<string, unknown> } {
1082
1075
  const { [INTENT_FIELD]: intent, ...strippedArgs } = args;
1083
1076
  if (typeof intent !== "string") {
@@ -1195,7 +1188,7 @@ function resolveAsides(entries: AsideMessage[] | undefined): AgentMessage[] {
1195
1188
  if (message) out.push(message);
1196
1189
  }
1197
1190
  } catch (error) {
1198
- discardAsides(out, error instanceof Error ? error : new Error(String(error)));
1191
+ discardAsides(out, toError(error));
1199
1192
  throw error;
1200
1193
  }
1201
1194
  return out;
@@ -1336,9 +1329,6 @@ async function runLoopBody(
1336
1329
  endAgentStream(stream, newMessages, telemetry, stepCounter.count);
1337
1330
  return;
1338
1331
  }
1339
- // Yield at the top of each iteration to prevent busy-wait when
1340
- // the agent loop is executing tool calls back-to-back.
1341
- await yieldIfDue();
1342
1332
  // Park at the turn boundary while the process-wide pause gate is
1343
1333
  // engaged (host /pause). An external abort releases the park so a
1344
1334
  // cancelled run still unwinds while everything else stays frozen.
@@ -1980,6 +1970,9 @@ async function prepareProviderCall(
1980
1970
  }),
1981
1971
  };
1982
1972
  }
1973
+ // Before the transform too, so a request-size clamp in it measures the withdrawn definitions the provider
1974
+ // re-declares; recomputed below against what the transform returns.
1975
+ if (config.sentToolDefinitions) llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
1983
1976
  if (config.transformProviderContext) {
1984
1977
  llmContext = await config.transformProviderContext(llmContext, model);
1985
1978
  }
@@ -1995,10 +1988,9 @@ async function prepareProviderCall(
1995
1988
  };
1996
1989
  }
1997
1990
  // After `transformProviderContext`, so the recorded definitions are exactly what the provider receives.
1998
- if (config.sentToolDefinitions && llmContext.tools) {
1999
- config.sentToolDefinitions.record(llmContext.tools);
2000
- const inactiveTools = config.sentToolDefinitions.inactiveFor(llmContext.messages, llmContext.tools);
2001
- if (inactiveTools) llmContext = { ...llmContext, inactiveTools };
1991
+ if (config.sentToolDefinitions) {
1992
+ if (llmContext.tools) config.sentToolDefinitions.record(llmContext.tools);
1993
+ llmContext = config.sentToolDefinitions.withInactiveTools(llmContext);
2002
1994
  }
2003
1995
  return { model, context: llmContext, promptToolWireTools, ownedDialect };
2004
1996
  }
@@ -2379,10 +2371,6 @@ async function streamAssistantResponse(
2379
2371
  return await finishAbortedStream();
2380
2372
  }
2381
2373
 
2382
- // Yield to the event loop periodically to prevent busy-wait
2383
- // when the LLM is streaming chunks faster than the loop can rest.
2384
- await yieldIfDue();
2385
-
2386
2374
  if (event.type === "toolcall_start") {
2387
2375
  const block = event.partial.content[event.contentIndex];
2388
2376
  if (block?.type === "toolCall") {
@@ -2790,14 +2778,7 @@ function buildToolCallAbortMessages(
2790
2778
  * `signal.reason` is the default `AbortError` `DOMException`) falls back to the
2791
2779
  * generic sentinel that downstream renderers treat as "no specific reason". */
2792
2780
  export function abortReasonText(signal: AbortSignal | undefined): string {
2793
- const scopedReason = toolScopedAbortReason(signal);
2794
- if (scopedReason) return scopedReason.message;
2795
- const reason = signal?.reason;
2796
- if (typeof reason === "string" && reason.trim().length > 0) return reason;
2797
- if (reason instanceof Error && reason.name !== "AbortError" && reason.message.trim().length > 0) {
2798
- return reason.message;
2799
- }
2800
- return "Request was aborted";
2781
+ return toolScopedAbortReason(signal)?.message ?? AIError.callerAbortReason(signal) ?? "Request was aborted";
2801
2782
  }
2802
2783
 
2803
2784
  function emitAbortedAssistantMessage(
@@ -3120,11 +3101,6 @@ async function prepareToolCallDispatch(
3120
3101
  ? { intent: undefined, strippedArgs: argsForExecution }
3121
3102
  : extractIntent(toolCall.arguments);
3122
3103
  argsForExecution = strippedArgs;
3123
- if (intent !== undefined && intent.length > MAX_INTENT_LENGTH && tool) {
3124
- entry.args = strippedArgs;
3125
- entry.validationErrorMessage = `\`${INTENT_FIELD}\` is a short intent label (at most ${MAX_INTENT_LENGTH} chars); the value you sent is ${intent.length} chars. The tool was not run. Put that content in the tool's own parameters and retry with a brief \`${INTENT_FIELD}\`.`;
3126
- continue;
3127
- }
3128
3104
  if (intent) {
3129
3105
  toolCall.intent = intent;
3130
3106
  } else if (typeof tool?.intent === "function") {
@@ -3426,7 +3402,7 @@ async function executeToolCalls(
3426
3402
  // also cascades: the freshly detached job's own completion re-triggers
3427
3403
  // this check for the next command, so millisecond-long commands chain
3428
3404
  // into separate background deliveries (#12869).
3429
- if (source === "irc" && softInterrupts) steeringSoftController.abort();
3405
+ if (source === "irc" && softInterrupts) steeringSoftController.abort("irc");
3430
3406
  };
3431
3407
 
3432
3408
  const checkSteering = async (): Promise<void> => {
@@ -3465,7 +3441,7 @@ async function executeToolCalls(
3465
3441
  interruptState.triggered = true;
3466
3442
  interruptState.source = steeringSource ?? "unknown";
3467
3443
  steeringAbortController.abort(TOOL_INTERRUPT_ABORT_REASON);
3468
- if (softInterrupts) steeringSoftController.abort();
3444
+ if (softInterrupts) steeringSoftController.abort(interruptState.source);
3469
3445
  }
3470
3446
  return;
3471
3447
  }
@@ -3917,9 +3893,6 @@ async function executeToolCalls(
3917
3893
  await steeringWatchPromise?.catch(() => undefined);
3918
3894
  clearInterval(steeringWatchTimer);
3919
3895
  }
3920
- // Yield after batch tool execution to let GC and I/O catch up,
3921
- // especially when tool results are large (e.g. bash output).
3922
- await yieldIfDue();
3923
3896
 
3924
3897
  for (const record of records) {
3925
3898
  if (!record.toolResultMessage) {