@linxiraos/pi-agent-core 1.4.4 → 1.4.7

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/src/agent-loop.ts CHANGED
@@ -109,7 +109,17 @@ import {
109
109
  isSoftToolRequirement,
110
110
  SPECULATIVE_STREAM_SESSION,
111
111
  } from "./types";
112
- import { yieldIfDue } from "./utils/yield";
112
+
113
+ async function waitForProcessPause(config: AgentLoopConfig, signal?: AbortSignal): Promise<void> {
114
+ try {
115
+ while (agentPauseGate.paused && !signal?.aborted) {
116
+ config.onPauseChange?.(true);
117
+ await agentPauseGate.waitUntilResumed(signal);
118
+ }
119
+ } finally {
120
+ config.onPauseChange?.(false);
121
+ }
122
+ }
113
123
  /** Stop-details marker for a provider error after assistant content/tool args already streamed. */
114
124
  export const STREAM_INTERRUPTED_AFTER_CONTENT_STOP_DETAIL = "stream_interrupted_after_content";
115
125
 
@@ -933,7 +943,8 @@ export function normalizeMessagesForProvider(
933
943
  });
934
944
  }
935
945
 
936
- 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";
937
948
  const INTENT_SCHEMA_UNION_KEYS = ["anyOf", "oneOf"] as const;
938
949
 
939
950
  // Memoize injection per input schema identity: normalizeTools runs on every
@@ -1010,7 +1021,7 @@ function injectIntentIntoSchema(
1010
1021
  ...schemaRecord,
1011
1022
  properties: {
1012
1023
  [INTENT_FIELD]: describeIntent
1013
- ? { type: "string", description: INTENT_FIELD_DESCRIPTION }
1024
+ ? { type: "string", description: Bun.env.PI_INTENT_DESC || DEFAULT_INTENT_FIELD_DESCRIPTION }
1014
1025
  : { type: "string" },
1015
1026
  ...properties,
1016
1027
  },
@@ -1061,9 +1072,8 @@ function resolveIntentMode(intent: AgentTool["intent"]): "require" | "optional"
1061
1072
  }
1062
1073
 
1063
1074
  /**
1064
- * Longest `i` value accepted as an intent. The injected field is described as
1065
- * a "concise intent" (INTENT_FIELD_DESCRIPTION); anything past this is a tool
1066
- * payload the model put in the wrong field, not a label.
1075
+ * Longest `i` value accepted as an intent; anything past this is a tool
1076
+ * payload the model put in the wrong field, not an intent.
1067
1077
  */
1068
1078
  const MAX_INTENT_LENGTH = 200;
1069
1079
 
@@ -1125,6 +1135,9 @@ interface StepCounter {
1125
1135
  count: number;
1126
1136
  }
1127
1137
 
1138
+ /** Largest setTimeout delay before 32-bit overflow (Node/Bun fire in ~1 ms past this). */
1139
+ const MAX_TIMER_MS = 2_147_483_647;
1140
+
1128
1141
  function isDeadlineExceeded(deadline: number | undefined): boolean {
1129
1142
  return deadline !== undefined && Date.now() >= deadline;
1130
1143
  }
@@ -1211,16 +1224,17 @@ async function runLoopBody(
1211
1224
  ): Promise<void> {
1212
1225
  let deadlineTimer: Timer | undefined;
1213
1226
  if (config.deadline !== undefined) {
1227
+ const deadline = config.deadline;
1214
1228
  const deadlineAbortController = new AbortController();
1215
1229
  const deadlineReason = new DOMException("Deadline exceeded", "TimeoutError");
1216
- const delay = config.deadline - Date.now();
1217
- if (delay <= 0) {
1218
- deadlineAbortController.abort(deadlineReason);
1219
- } else {
1220
- deadlineTimer = setTimeout(() => {
1221
- deadlineAbortController.abort(deadlineReason);
1222
- }, delay);
1223
- }
1230
+ // setTimeout overflows past 2^31-1 ms and fires in ~1 ms, so a valid `--max-time 600h`
1231
+ // aborted the first turn at once: wait in bounded slices and recheck the deadline.
1232
+ const armDeadline = (): void => {
1233
+ const delay = deadline - Date.now();
1234
+ if (delay <= 0) deadlineAbortController.abort(deadlineReason);
1235
+ else deadlineTimer = setTimeout(armDeadline, Math.min(delay, MAX_TIMER_MS));
1236
+ };
1237
+ armDeadline();
1224
1238
  signal = signal ? AbortSignal.any([signal, deadlineAbortController.signal]) : deadlineAbortController.signal;
1225
1239
  }
1226
1240
 
@@ -1321,13 +1335,10 @@ async function runLoopBody(
1321
1335
  endAgentStream(stream, newMessages, telemetry, stepCounter.count);
1322
1336
  return;
1323
1337
  }
1324
- // Yield at the top of each iteration to prevent busy-wait when
1325
- // the agent loop is executing tool calls back-to-back.
1326
- await yieldIfDue();
1327
1338
  // Park at the turn boundary while the process-wide pause gate is
1328
1339
  // engaged (host /pause). An external abort releases the park so a
1329
1340
  // cancelled run still unwinds while everything else stays frozen.
1330
- if (agentPauseGate.paused) await agentPauseGate.waitUntilResumed(signal);
1341
+ if (agentPauseGate.paused) await waitForProcessPause(config, signal);
1331
1342
 
1332
1343
  // Build the provider-bound context before opening the turn. Queue
1333
1344
  // messages are added now but their events remain deferred until
@@ -1439,6 +1450,7 @@ async function runLoopBody(
1439
1450
  let recovered: HarmonyRecoveredToolCall | undefined;
1440
1451
  let message: AssistantMessage;
1441
1452
  try {
1453
+ if (agentPauseGate.paused) await waitForProcessPause(config, signal);
1442
1454
  message = await streamAssistantResponse(
1443
1455
  currentContext,
1444
1456
  config,
@@ -1789,7 +1801,7 @@ async function runLoopBody(
1789
1801
  : [...live, ...((await config.getSteeringMessages?.(signal)) || [])];
1790
1802
  if (hasMoreToolCalls) {
1791
1803
  // Mid-work: fold any non-interrupting asides into the next turn alongside steering.
1792
- const asides = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.());
1804
+ const asides = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.("work"));
1793
1805
  pendingMessages = asides.length > 0 ? [...steering, ...asides] : steering;
1794
1806
  } else {
1795
1807
  // Stop boundary: only steering (live user input) forces another turn here. Leave
@@ -1817,7 +1829,7 @@ async function runLoopBody(
1817
1829
  // above and this yield point (e.g. queued while onBeforeYield ran). Without
1818
1830
  // this poll it would strand in the queue until the next manual prompt.
1819
1831
  const lateSteering = signal?.aborted ? [] : (await config.getSteeringMessages?.(signal)) || [];
1820
- const asideMessages = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.());
1832
+ const asideMessages = signal?.aborted ? [] : resolveAsides(await config.getAsideMessages?.("stop"));
1821
1833
  const followUpMessages = signal?.aborted ? [] : (await config.getFollowUpMessages?.(signal)) || [];
1822
1834
  if (lateSteering.length > 0 || asideMessages.length > 0 || followUpMessages.length > 0) {
1823
1835
  // Set as pending so the inner loop processes them before stopping.
@@ -2363,10 +2375,6 @@ async function streamAssistantResponse(
2363
2375
  return await finishAbortedStream();
2364
2376
  }
2365
2377
 
2366
- // Yield to the event loop periodically to prevent busy-wait
2367
- // when the LLM is streaming chunks faster than the loop can rest.
2368
- await yieldIfDue();
2369
-
2370
2378
  if (event.type === "toolcall_start") {
2371
2379
  const block = event.partial.content[event.contentIndex];
2372
2380
  if (block?.type === "toolCall") {
@@ -2774,14 +2782,7 @@ function buildToolCallAbortMessages(
2774
2782
  * `signal.reason` is the default `AbortError` `DOMException`) falls back to the
2775
2783
  * generic sentinel that downstream renderers treat as "no specific reason". */
2776
2784
  export function abortReasonText(signal: AbortSignal | undefined): string {
2777
- const scopedReason = toolScopedAbortReason(signal);
2778
- if (scopedReason) return scopedReason.message;
2779
- const reason = signal?.reason;
2780
- if (typeof reason === "string" && reason.trim().length > 0) return reason;
2781
- if (reason instanceof Error && reason.name !== "AbortError" && reason.message.trim().length > 0) {
2782
- return reason.message;
2783
- }
2784
- return "Request was aborted";
2785
+ return toolScopedAbortReason(signal)?.message ?? AIError.callerAbortReason(signal) ?? "Request was aborted";
2785
2786
  }
2786
2787
 
2787
2788
  function emitAbortedAssistantMessage(
@@ -3345,6 +3346,7 @@ async function executeToolCalls(
3345
3346
  tool,
3346
3347
  args,
3347
3348
  interruptible,
3349
+ handlesToolInterrupt: interruptible && tool?.handlesToolInterrupt === true,
3348
3350
  signal: interruptible ? interruptibleSignal : nonInterruptibleSignal,
3349
3351
  started: false,
3350
3352
  result: undefined as AgentToolResult<any> | undefined,
@@ -3363,6 +3365,22 @@ async function executeToolCalls(
3363
3365
  };
3364
3366
  });
3365
3367
 
3368
+ // Derive batch readiness from existing dispatch records, not extra participants.
3369
+ const refreshPauseState = (): void => {
3370
+ config.onPauseChange?.(
3371
+ agentPauseGate.paused &&
3372
+ !signal?.aborted &&
3373
+ !speculationCoordinator?.isRunning &&
3374
+ records.some(record => !record.started && !record.skipped && !record.toolResultMessage) &&
3375
+ !records.some(record => record.started && !record.toolResultMessage),
3376
+ );
3377
+ };
3378
+ if (speculationCoordinator) speculationCoordinator.onIdle = refreshPauseState;
3379
+
3380
+ const isToolAborted = (record: (typeof records)[number]): boolean =>
3381
+ signal?.aborted === true ||
3382
+ (record.signal.aborted && !(record.handlesToolInterrupt && record.signal.reason === TOOL_INTERRUPT_ABORT_REASON));
3383
+
3366
3384
  const checkAsideInterrupts = async (): Promise<void> => {
3367
3385
  // Asides only fire once: an interrupt already recorded on interruptState
3368
3386
  // must not re-abort, and (unlike steering) never re-consumes a queue.
@@ -3425,9 +3443,9 @@ async function executeToolCalls(
3425
3443
  // interruptMode is "wait") raises the cooperative soft signal for
3426
3444
  // everything else: the boundary dequeue
3427
3445
  // below injects the message as soon as running tools finish (or
3428
- // background themselves), and not-yet-started interruptible waits
3429
- // are skipped. Idempotent — a second steer poll after the abort is
3430
- // a no-op.
3446
+ // background themselves). Not-yet-started interruptible tools are
3447
+ // skipped unless they can drain the queued wake. Idempotent — a
3448
+ // second steer poll after the abort is a no-op.
3431
3449
  if (!steeringAbortController.signal.aborted) {
3432
3450
  interruptState.triggered = true;
3433
3451
  interruptState.source = steeringSource ?? "unknown";
@@ -3490,8 +3508,8 @@ async function executeToolCalls(
3490
3508
  };
3491
3509
 
3492
3510
  const runTool = async (record: (typeof records)[number], index: number): Promise<void> => {
3493
- // A pending interrupt preempts not-yet-started *interruptible* waits so
3494
- // the message injects promptly instead of sitting out a `wait`.
3511
+ // A pending interrupt preempts not-yet-started interruptible tools,
3512
+ // except receivers that drain the wake with an already-aborted signal.
3495
3513
  // Non-interruptible work is never skipped, whatever the source: the
3496
3514
  // expensive part — generating the call — is already paid, the tool
3497
3515
  // itself is cheap, and a skip only makes the model re-emit the same
@@ -3501,7 +3519,7 @@ async function executeToolCalls(
3501
3519
  // the parent steers mid-stream (#10645). The steer still injects at the
3502
3520
  // batch boundary; the cooperative soft signal lets long-running tools
3503
3521
  // step aside on their own.
3504
- if (interruptState.triggered && record.interruptible) {
3522
+ if (interruptState.triggered && record.interruptible && !record.handlesToolInterrupt) {
3505
3523
  // Skip both span emission and the collector orphan record here. The
3506
3524
  // tail sweep below (after `Promise.allSettled`) is the single path
3507
3525
  // that handles "no result message was produced" — it calls
@@ -3513,7 +3531,11 @@ async function executeToolCalls(
3513
3531
  // Park before starting this tool while the process-wide pause gate is
3514
3532
  // engaged. Tools already executing are unaffected (pausing never aborts);
3515
3533
  // a batch interrupted mid-pause unwinds via the signal checks below.
3516
- if (agentPauseGate.paused) await agentPauseGate.waitUntilResumed(record.signal);
3534
+ while (agentPauseGate.paused && !record.signal.aborted) {
3535
+ refreshPauseState();
3536
+ await agentPauseGate.waitUntilResumed(record.signal);
3537
+ }
3538
+ config.onPauseChange?.(false);
3517
3539
 
3518
3540
  const { toolCall, tool } = record;
3519
3541
  // Validation (and the beforeToolCall hook) ran in the prepare phase; a
@@ -3531,14 +3553,14 @@ async function executeToolCalls(
3531
3553
  return;
3532
3554
  }
3533
3555
  const effectiveArgs = record.args;
3534
- if (record.signal.aborted) {
3556
+ if (isToolAborted(record)) {
3535
3557
  record.skipped = true;
3536
3558
  recordSkippedTool(telemetry, {
3537
3559
  toolCallId: toolCall.id,
3538
3560
  toolName: toolCall.name,
3539
3561
  status: "aborted",
3540
3562
  });
3541
- emitToolResult(record, createToolSignalAbortedResult(record.signal), true);
3563
+ emitToolResult(record, createToolSignalAbortedResult(signal?.aborted ? signal : record.signal), true);
3542
3564
  return;
3543
3565
  }
3544
3566
  record.started = true;
@@ -3566,17 +3588,19 @@ async function executeToolCalls(
3566
3588
  let caughtError: unknown;
3567
3589
  let completedToolExecution = false;
3568
3590
  let executionStarted = false;
3591
+ const abortBeforeToolExecution = (): boolean => {
3592
+ if (!isToolAborted(record)) return false;
3593
+ result = createToolSignalAbortedResult(signal?.aborted ? signal : record.signal);
3594
+ isError = true;
3595
+ return true;
3596
+ };
3569
3597
 
3570
3598
  await runInActiveSpan(toolSpan, async () => {
3571
3599
  try {
3572
3600
  if (!tool) {
3573
3601
  throw new Error(formatToolNotFoundMessage(toolCall.name, tools, suggestFallbackToolNames?.()));
3574
3602
  }
3575
- if (record.signal.aborted) {
3576
- result = createToolSignalAbortedResult(record.signal);
3577
- isError = true;
3578
- return;
3579
- }
3603
+ if (abortBeforeToolExecution()) return;
3580
3604
 
3581
3605
  if (record.prepareError !== undefined) throw record.prepareError;
3582
3606
  if (record.blocked) {
@@ -3587,6 +3611,9 @@ async function executeToolCalls(
3587
3611
  record.executionArgs ??
3588
3612
  (transformToolCallArguments ? transformToolCallArguments(effectiveArgs, toolCall.name) : effectiveArgs);
3589
3613
  record.args = executionArgs;
3614
+ // A transform or awaited claim can cancel the external run after
3615
+ // a queued wake already fixed the combined signal's reason.
3616
+ if (abortBeforeToolExecution()) return;
3590
3617
 
3591
3618
  const speculativeOutcome = speculationCoordinator
3592
3619
  ? await speculationCoordinator.claim(tool, toolCall, executionArgs)
@@ -3603,6 +3630,7 @@ async function executeToolCalls(
3603
3630
  }
3604
3631
 
3605
3632
  if (!completedToolExecution) {
3633
+ if (abortBeforeToolExecution()) return;
3606
3634
  // The cooperative steering signal and the passive-context sink
3607
3635
  // ride the loop-owned ToolCallContext (surfacing as
3608
3636
  // `ctx.toolCall.*`); the host surfaces the sink on the context it
@@ -3627,9 +3655,12 @@ async function executeToolCalls(
3627
3655
  } else if (streamSession && !streamSession.contextIndependent) {
3628
3656
  await streamSession.discard("outer tool context cannot carry stream speculation");
3629
3657
  }
3630
- executionStarted = true;
3631
3658
  let rawResult: unknown;
3632
3659
  try {
3660
+ // Context construction and stream cleanup can also cancel;
3661
+ // nothing may await or call host code after this final check.
3662
+ if (abortBeforeToolExecution()) return;
3663
+ executionStarted = true;
3633
3664
  rawResult = await tool.execute(
3634
3665
  toolCall.id,
3635
3666
  executionArgs,
@@ -3709,10 +3740,10 @@ async function executeToolCalls(
3709
3740
  const interrupted = interruptState.triggered;
3710
3741
  const perToolAborted = record.signal.aborted;
3711
3742
  const abortedDuringExecution = perToolAborted && isError && !completedToolExecution;
3712
- if (record.interruptible && interrupted && abortedDuringExecution) {
3743
+ if (record.interruptible && interrupted && abortedDuringExecution && !signal?.aborted) {
3713
3744
  // Queued steering/asides abort only interruptible tools. An external
3714
- // user abort can also fail a non-interruptible tool (e.g. cancelled
3715
- // ask); keep its actual error instead of attributing it to the queue.
3745
+ // user abort takes priority even if a queued interrupt fixed the
3746
+ // combined signal's reason first; keep the actual cancellation error.
3716
3747
  record.skipped = true;
3717
3748
  emitToolResult(record, createSkippedToolResult(interruptState.source, executionStarted), true);
3718
3749
  } else {
@@ -3769,7 +3800,7 @@ async function executeToolCalls(
3769
3800
  (softInterrupts || records.some(record => record.interruptible)) &&
3770
3801
  (hasSteeringMessages !== undefined || hasAsidePeek);
3771
3802
  // Live-taken steering is already pending: interrupt before any call starts
3772
- // so not-yet-started interruptible waits are skipped outright.
3803
+ // so interruptible tools skip or drain the queued wake without blocking.
3773
3804
  if (liveSteering.length > 0) await checkSteering();
3774
3805
  const eventDrivenSteeringWatch =
3775
3806
  watchSteeringWhileRunning && config.waitForSteeringMessages !== undefined && hasSteeringMessages !== undefined;
@@ -3847,7 +3878,13 @@ async function executeToolCalls(
3847
3878
  concurrency = concurrencyMode ?? "shared";
3848
3879
  }
3849
3880
  const start = concurrency === "exclusive" ? Promise.all([lastExclusive, ...sharedTasks]) : lastExclusive;
3850
- const task = start.then(() => runTool(record, index));
3881
+ const task = start.then(async () => {
3882
+ try {
3883
+ await runTool(record, index);
3884
+ } finally {
3885
+ refreshPauseState();
3886
+ }
3887
+ });
3851
3888
  tasks.push(task);
3852
3889
  if (concurrency === "exclusive") {
3853
3890
  lastExclusive = task;
@@ -3859,13 +3896,12 @@ async function executeToolCalls(
3859
3896
  try {
3860
3897
  await Promise.allSettled(tasks);
3861
3898
  } finally {
3899
+ if (speculationCoordinator) speculationCoordinator.onIdle = undefined;
3900
+ config.onPauseChange?.(false);
3862
3901
  steeringWatchAbortController.abort();
3863
3902
  await steeringWatchPromise?.catch(() => undefined);
3864
3903
  clearInterval(steeringWatchTimer);
3865
3904
  }
3866
- // Yield after batch tool execution to let GC and I/O catch up,
3867
- // especially when tool results are large (e.g. bash output).
3868
- await yieldIfDue();
3869
3905
 
3870
3906
  for (const record of records) {
3871
3907
  if (!record.toolResultMessage) {
package/src/agent.ts CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  type ToolResultMessage,
24
24
  } from "@linxiraos/pi-ai";
25
25
  import type { Dialect } from "@linxiraos/pi-ai/dialect";
26
- import { openAIResponsesReplaysNativeHistory } from "@linxiraos/pi-ai/providers/openai-responses";
26
+ import { openAIResponsesReplaysNativeHistory } from "@linxiraos/pi-ai/providers/openai-responses-state";
27
27
  import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
28
28
  import { getBundledModel } from "@linxiraos/pi-catalog/models";
29
29
  import { logger } from "@linxiraos/pi-utils";
@@ -39,6 +39,7 @@ import {
39
39
  unpairedToolCallTail,
40
40
  } from "./agent-loop";
41
41
  import type { AppendOnlyContextManager } from "./append-only-context";
42
+ import { agentPauseGate } from "./pause";
42
43
  import { isProviderRefusalMessage } from "./replay-policy";
43
44
  import { SentToolDefinitions } from "./sent-tool-definitions";
44
45
  import { Tokenizer } from "./tokenizer";
@@ -58,6 +59,7 @@ import type {
58
59
  AgentTool,
59
60
  AgentToolContext,
60
61
  AgentTurnEndContext,
62
+ AsideBoundary,
61
63
  AsideMessage,
62
64
  PrepareQueuedMessages,
63
65
  QueuedMessageQueue,
@@ -67,7 +69,6 @@ import type {
67
69
  ToolChoiceDirective,
68
70
  } from "./types";
69
71
  import { isSoftToolRequirement } from "./types";
70
- import { EventLoopKeepalive } from "./utils/yield";
71
72
 
72
73
  /**
73
74
  * Default convertToLlm: Keep only LLM-compatible replay messages.
@@ -473,6 +474,12 @@ export class Agent {
473
474
  #cwdResolver?: () => string | undefined;
474
475
 
475
476
  #runningPrompt?: Promise<void>;
477
+ #isPaused = false;
478
+
479
+ /** True while this unfinished turn is safely parked by the process pause gate. */
480
+ get isPaused(): boolean {
481
+ return this.#isPaused && agentPauseGate.paused && !this.#abortController?.signal.aborted;
482
+ }
476
483
  #resolveRunningPrompt?: () => void;
477
484
  #kimiApiFormat?: "openai" | "anthropic";
478
485
  #preferWebsockets?: boolean;
@@ -499,7 +506,7 @@ export class Agent {
499
506
  #onModelCallSystemPrompt?: (systemPrompt: string[]) => void;
500
507
  #beforeModelCall?: AgentBeforeModelCall;
501
508
  #additionalBeforeModelCalls = new Set<AgentBeforeModelCall>();
502
- #asideMessageProvider?: () => AsideMessage[] | Promise<AsideMessage[]>;
509
+ #asideMessageProvider?: (boundary: AsideBoundary) => AsideMessage[] | Promise<AsideMessage[]>;
503
510
  #telemetry?: AgentLoopConfig["telemetry"];
504
511
  #appendOnlyContext?: AppendOnlyContextManager;
505
512
  #beforeQueuedMessageDequeueHooks = new Set<(signal?: AbortSignal) => Promise<void> | void>();
@@ -635,6 +642,12 @@ export class Agent {
635
642
  this.#promptCacheKey = value;
636
643
  }
637
644
 
645
+ /**
646
+ * Fields added to every log record written while this agent runs (the
647
+ * owning session's `sessionId`), so in-process agents' records stay apart.
648
+ */
649
+ logContext: Readonly<Record<string, unknown>> | undefined;
650
+
638
651
  /**
639
652
  * Static metadata forwarded to every API request when no resolver is installed
640
653
  * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
@@ -811,6 +824,23 @@ export class Agent {
811
824
  this.#pruneToolDescriptions = value;
812
825
  }
813
826
 
827
+ /**
828
+ * Whether requests to `model` actually ship description-stripped tool specs.
829
+ * Owned dialects render full definitions in-band, so they never prune; the
830
+ * loop applies the same rule (`pruneToolDescriptions && !ownedDialect`).
831
+ * Context accounting reads this instead of the raw setting.
832
+ */
833
+ prunesToolDescriptions(model: Model | undefined): boolean {
834
+ return this.#pruneToolDescriptions && model !== undefined && !this.#ownedDialect(model);
835
+ }
836
+
837
+ #ownedDialect(model: Model): Dialect | undefined {
838
+ return (
839
+ (this.#dialectResolver ? this.#dialectResolver(model) : this.#dialect) ??
840
+ resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT)
841
+ );
842
+ }
843
+
814
844
  /** Inject/strip the intent field on tool calls; applies from the next prompt run. */
815
845
  get intentTracing(): boolean {
816
846
  return this.#intentTracing;
@@ -920,9 +950,7 @@ export class Agent {
920
950
  ): Promise<Context> {
921
951
  const model = this.#state.model;
922
952
  if (!model) throw new Error("No active model on agent");
923
- const ownedDialect =
924
- (this.#dialectResolver ? this.#dialectResolver(model) : this.#dialect) ??
925
- resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
953
+ const ownedDialect = this.#ownedDialect(model);
926
954
  const messages = normalizeMessagesForProvider(llmMessages, model);
927
955
  const tools = ownedDialect
928
956
  ? []
@@ -1204,7 +1232,9 @@ export class Agent {
1204
1232
  * aborts foreground tools; an interruptible `wait` may end early through the
1205
1233
  * peek hooks. See `AgentLoopConfig.getAsideMessages`.
1206
1234
  */
1207
- setAsideMessageProvider(fn: (() => AsideMessage[] | Promise<AsideMessage[]>) | undefined): void {
1235
+ setAsideMessageProvider(
1236
+ fn: ((boundary: AsideBoundary) => AsideMessage[] | Promise<AsideMessage[]>) | undefined,
1237
+ ): void {
1208
1238
  this.#asideMessageProvider = fn;
1209
1239
  }
1210
1240
 
@@ -1643,7 +1673,7 @@ export class Agent {
1643
1673
  promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
1644
1674
  }
1645
1675
 
1646
- await this.#runLoop(msgs, promptOptions);
1676
+ await this.#inLogContext(() => this.#runLoop(msgs, promptOptions));
1647
1677
  }
1648
1678
 
1649
1679
  /**
@@ -1667,7 +1697,12 @@ export class Agent {
1667
1697
  return signals.length === 1 ? signals[0] : AbortSignal.any(signals);
1668
1698
  }
1669
1699
 
1670
- async continue(signal?: AbortSignal) {
1700
+ continue(signal?: AbortSignal): Promise<void> {
1701
+ // Queued-message hooks run before the loop and are this agent's work too.
1702
+ return this.#inLogContext(() => this.#continue(signal));
1703
+ }
1704
+
1705
+ async #continue(signal?: AbortSignal) {
1671
1706
  if (this.#state.isStreaming) {
1672
1707
  throw new AgentBusyError();
1673
1708
  }
@@ -1749,6 +1784,11 @@ export class Agent {
1749
1784
  }
1750
1785
  }
1751
1786
 
1787
+ /** Run `fn` with {@link logContext} on every record it logs. */
1788
+ #inLogContext<T>(fn: () => T): T {
1789
+ return this.logContext ? logger.withContext(this.logContext, fn) : fn();
1790
+ }
1791
+
1752
1792
  /**
1753
1793
  * Run the agent loop.
1754
1794
  * If messages are provided, starts a new conversation turn with those messages.
@@ -1764,7 +1804,6 @@ export class Agent {
1764
1804
  if (!model) throw new Error("No model configured");
1765
1805
 
1766
1806
  let skipInitialSteeringPoll = options?.skipInitialSteeringPoll === true;
1767
- using _ = new EventLoopKeepalive();
1768
1807
  if (!runStateClaimed) {
1769
1808
  const { promise, resolve } = Promise.withResolvers<void>();
1770
1809
  this.#runningPrompt = promise;
@@ -1780,6 +1819,7 @@ export class Agent {
1780
1819
  this.#state.isStreaming = true;
1781
1820
  this.#state.streamMessage = null;
1782
1821
  this.#state.error = undefined;
1822
+ this.#isPaused = false;
1783
1823
 
1784
1824
  // Clear Cursor tool result buffer at start of each run
1785
1825
  this.#cursorToolResultBuffer = [];
@@ -1952,6 +1992,9 @@ export class Agent {
1952
1992
  onAssistantMessageEvent: this.#onAssistantMessageEvent,
1953
1993
  onHarmonyLeak: this.#onHarmonyLeak,
1954
1994
  onTurnEnd: (messages, signal, context) => this.#onTurnEnd?.(messages, signal, context),
1995
+ onPauseChange: paused => {
1996
+ this.#isPaused = paused;
1997
+ },
1955
1998
  getToolChoice,
1956
1999
  softToolRequirementState: this.#softToolRequirementState,
1957
2000
  onToolChoiceRejected: () => {
@@ -1981,7 +2024,7 @@ export class Agent {
1981
2024
  hasBackgroundCompletions: this.hasBackgroundCompletions,
1982
2025
  hasQueuedAsides: this.hasQueuedAsides,
1983
2026
  getFollowUpMessages: signal => this.#dequeueFollowUpMessagesAfterHooks(signal ?? loopSignal),
1984
- getAsideMessages: async () => (await this.#asideMessageProvider?.()) ?? [],
2027
+ getAsideMessages: async boundary => (await this.#asideMessageProvider?.(boundary)) ?? [],
1985
2028
  onBeforeYield: () => this.#onBeforeYield?.(),
1986
2029
  onDetachedToolUpdate: event => this.emitExternalEvent(event),
1987
2030
  telemetry: this.#telemetry,
@@ -2202,6 +2245,7 @@ export class Agent {
2202
2245
  this.#emit({ type: "agent_end", messages: [errorMsg] });
2203
2246
  }
2204
2247
  } finally {
2248
+ this.#isPaused = false;
2205
2249
  this.#restoreUndeliveredQueuedMessages(loopAbortController);
2206
2250
  resolveRun?.();
2207
2251
  if (this.#abortController === loopAbortController) {
@@ -18,7 +18,6 @@ import type {
18
18
  Usage,
19
19
  } from "@linxiraos/pi-ai";
20
20
  import * as AIError from "@linxiraos/pi-ai/error";
21
- import { resolveAnthropicCompactionEffort } from "@linxiraos/pi-ai/providers/anthropic";
22
21
  import {
23
22
  supportsAnthropicCompaction,
24
23
  supportsBedrockConverseCompaction,
@@ -251,6 +250,14 @@ export async function requestAnthropicNativeCompaction(
251
250
  signal: AbortSignal | undefined,
252
251
  options: AnthropicNativeCompactionOptions,
253
252
  ): Promise<AnthropicNativeCompactionResponse> {
253
+ // Pure compaction policy checks must not load the provider; only an actual request needs it.
254
+ const reasoning = isAnthropicMessagesModel(model)
255
+ ? (await import("@linxiraos/pi-ai/providers/anthropic")).resolveAnthropicCompactionEffort(
256
+ model,
257
+ request.context.messages,
258
+ request.reasoning,
259
+ )
260
+ : request.reasoning;
254
261
  const response = await instrumentedCompleteSimple(
255
262
  model,
256
263
  request.context,
@@ -258,9 +265,7 @@ export async function requestAnthropicNativeCompaction(
258
265
  apiKey,
259
266
  signal,
260
267
  maxTokens: request.maxTokens,
261
- reasoning: isAnthropicMessagesModel(model)
262
- ? resolveAnthropicCompactionEffort(model, request.context.messages, request.reasoning)
263
- : request.reasoning,
268
+ reasoning,
264
269
  initiatorOverride: options.initiatorOverride,
265
270
  metadata: options.metadata,
266
271
  fetch: options.fetch,