@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/telemetry.ts CHANGED
@@ -51,7 +51,6 @@ import {
51
51
  } from "@opentelemetry/api";
52
52
  import { AgentRunCollector, type AgentRunCoverage, type AgentRunSummary, type ToolStatus } from "./run-collector";
53
53
  import type { AgentTool } from "./types";
54
- import { EventLoopKeepalive } from "./utils/yield";
55
54
 
56
55
  /** Default tracer name. Override via {@link AgentTelemetryConfig.tracerName}. */
57
56
  export const DEFAULT_TRACER_NAME = "@linxiraos/pi-agent-core";
@@ -1840,13 +1839,6 @@ export async function instrumentedCompleteSimple<TApi extends Api>(
1840
1839
  options: SimpleStreamOptions,
1841
1840
  span: InstrumentedChatSpanOptions,
1842
1841
  ): Promise<AssistantMessage> {
1843
- // Oneshot LLM calls (handoff, compaction/branch summaries) run outside the
1844
- // agent `#runLoop`, which is where the EventLoopKeepalive normally lives.
1845
- // Without it, Bun's JSC loop stops servicing timers while parked on the
1846
- // long-lived completion promise, freezing any host spinner (e.g. the
1847
- // `/handoff` Loader) until an unrelated I/O event (a terminal resize)
1848
- // pokes the loop. Keep the loop healthy for the duration of the call.
1849
- using _keepalive = new EventLoopKeepalive();
1850
1842
  const { telemetry, parent, oneshotKind } = span;
1851
1843
  const stepNumber = span.stepNumber ?? -1;
1852
1844
  const reasoning = options.reasoning;
package/src/tokenizer.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { AssistantMessage, Model } from "@linxiraos/pi-ai";
2
2
  import { renderDemotedThinking } from "@linxiraos/pi-ai/dialect/demotion";
3
3
  import { ollamaChatDropsOwnThinking } from "@linxiraos/pi-ai/providers/ollama";
4
+ import { completionsDropsOwnThinking, isLiteLLMThinkingSignature } from "@linxiraos/pi-ai/providers/openai-completions";
4
5
  import { isColdReplayableResponsesTurn } from "@linxiraos/pi-ai/providers/openai-shared";
5
6
  import {
6
7
  isSameModelTurn,
@@ -41,7 +42,7 @@ export function tokenizerEncodingForModel(model: Pick<Model, "tokenizer"> | null
41
42
  }
42
43
 
43
44
  type TokenizerModel = Pick<Model, "tokenizer"> &
44
- snapcompact.ShapeTarget & { compat?: Model["compat"]; thinking?: Model["thinking"] };
45
+ snapcompact.ShapeTarget & { compat?: Model["compat"]; thinking?: Model["thinking"]; reasoning?: boolean };
45
46
 
46
47
  /** The model an assistant turn's native reasoning (signed thinking, Responses history) is replayed to. */
47
48
  interface ReasoningReplayReader {
@@ -213,6 +214,7 @@ export class Tokenizer {
213
214
  readonly frameBillingKey: string;
214
215
  readonly #reasoningReader: ReasoningReplayReader | undefined;
215
216
  readonly #dropsOllamaThinking: boolean;
217
+ readonly #dropsCompletionsThinking: boolean;
216
218
  /** Claude's own API and prefix-bound hosts keep another model's signature from their deployment. */
217
219
  readonly #readsDeploymentSignatures: boolean;
218
220
  readonly reasoningReplayKey: string;
@@ -251,6 +253,7 @@ export class Tokenizer {
251
253
  this.frameBillingKey = snapcompact.frameBillingKey(this.#frameBilling);
252
254
  this.#reasoningReader = reasoningReplayReader(model);
253
255
  this.#dropsOllamaThinking = ollamaChatDropsOwnThinking(model);
256
+ this.#dropsCompletionsThinking = completionsDropsOwnThinking(model);
254
257
  const compat = model?.compat;
255
258
  this.#readsDeploymentSignatures =
256
259
  model?.api === "anthropic-messages" &&
@@ -424,6 +427,9 @@ export class Tokenizer {
424
427
  const replayedReasoning = this.#replayedReasoningTokens(message);
425
428
  const ollamaReader = this.#reasoningReader?.api === "ollama-chat" ? this.#reasoningReader : undefined;
426
429
  const ownOllamaTurn = ollamaReader !== undefined && isSameModelTurn(message, ollamaReader);
430
+ const completionsReader = this.#dropsCompletionsThinking ? this.#reasoningReader : undefined;
431
+ const ownDroppedCompletionsTurn =
432
+ completionsReader !== undefined && isSameModelTurn(message, completionsReader);
427
433
  if (typeof replayedReasoning === "number") extra += replayedReasoning;
428
434
  const signaturesPriced = this.thinkingReplayTokens === "signature";
429
435
  // The replay's signature rule (`transformMessages`): an aborted or
@@ -457,6 +463,8 @@ export class Tokenizer {
457
463
  continue;
458
464
  }
459
465
  if (this.#dropsOllamaThinking && ownOllamaTurn) continue;
466
+ // Chat-completions drops it unless LiteLLM replays it in `thinking_blocks`.
467
+ if (ownDroppedCompletionsTurn && !isLiteLLMThinkingSignature(block.thinkingSignature)) continue;
460
468
  fragments.push(block.thinking);
461
469
  // Providers charge for the opaque signature/reasoning payload that
462
470
  // rides alongside the thinking text (OpenAI Responses encrypted
@@ -578,6 +586,7 @@ export class Tokenizer {
578
586
  reasoningReplayKey(model) === this.reasoningReplayKey &&
579
587
  resolveThinkingReplayTokens(model ?? {}) === this.thinkingReplayTokens &&
580
588
  ollamaChatDropsOwnThinking(model) === this.#dropsOllamaThinking &&
589
+ completionsDropsOwnThinking(model) === this.#dropsCompletionsThinking &&
581
590
  (options?.nativeHistoryReplay ?? true) === this.nativeHistoryReplay
582
591
  );
583
592
  }
package/src/types.ts CHANGED
@@ -68,6 +68,9 @@ export type CommittableAsideMessage = AgentMessage & {
68
68
  */
69
69
  export type AsideMessage = CommittableAsideMessage | (() => CommittableAsideMessage | null);
70
70
 
71
+ /** Where the loop polls asides: after a tool batch (`"work"`) or after a turn without tool calls (`"stop"`). */
72
+ export type AsideBoundary = "work" | "stop";
73
+
71
74
  export interface AgentTurnEndContext {
72
75
  /** Assistant/user message that just completed this turn boundary. */
73
76
  message: AgentMessage;
@@ -172,6 +175,9 @@ export interface SteeringQueueState {
172
175
  export interface AgentLoopConfig extends SimpleStreamOptions {
173
176
  model: Model;
174
177
 
178
+ /** Reports whether this loop has reached a safe process-pause boundary. */
179
+ onPauseChange?: (paused: boolean) => void;
180
+
175
181
  /**
176
182
  * When to interrupt tool execution for steering messages.
177
183
  * - "immediate" = cut interruptible waits short and raise the cooperative
@@ -277,7 +283,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
277
283
  *
278
284
  * Polled while a tool batch runs (in "wait" mode, only when the batch holds an
279
285
  * interruptible tool) to decide whether to abort in-flight and skip
280
- * not-yet-started *interruptible* waits;
286
+ * not-yet-started *interruptible* waits, unless they handle queued interrupts;
281
287
  * every other already-emitted call still executes and the message injects
282
288
  * at the batch boundary. The queue keeps
283
289
  * owning its messages until the loop reaches the next injection boundary and
@@ -368,8 +374,12 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
368
374
  * should reach the model between requests without waiting for the agent to
369
375
  * fully stop. Returned messages are appended to the context with normal
370
376
  * message events and keep the loop running so the model can react.
377
+ *
378
+ * `boundary` is `"work"` after a tool batch and `"stop"` when the model ended
379
+ * its turn without tool calls; a provider may hold back messages that should
380
+ * not extend a finished turn.
371
381
  */
372
- getAsideMessages?: () => Promise<AsideMessage[]>;
382
+ getAsideMessages?: (boundary: AsideBoundary) => Promise<AsideMessage[]>;
373
383
  /**
374
384
  * Hook fired right before the loop would exit.
375
385
  *
@@ -1184,6 +1194,13 @@ export interface AgentTool<
1184
1194
  * batch boundary. Honored in both `interruptMode`s.
1185
1195
  */
1186
1196
  interruptible?: boolean | ((args: Partial<Static<TParameters>>) => boolean);
1197
+ /**
1198
+ * An interruptible tool can execute with an already-aborted
1199
+ * `TOOL_INTERRUPT_ABORT_REASON` signal to drain caller-owned wake events.
1200
+ * It must not block when that signal is aborted. External/user cancellation
1201
+ * still prevents execution. Omitted tools keep the usual pre-start skip.
1202
+ */
1203
+ handlesToolInterrupt?: boolean;
1187
1204
  /**
1188
1205
  * Controls how the INTENT_FIELD (`i`) is handled for this tool.
1189
1206
  * - `"require"` (default): `i` is injected and required in the parameter schema.
@@ -1236,6 +1253,12 @@ export interface AgentTool<
1236
1253
  */
1237
1254
  approvalCacheTargets?: (args: unknown) => readonly string[] | undefined;
1238
1255
 
1256
+ /**
1257
+ * Paths a call reads beyond its working directory, matched against restricted folders when it
1258
+ * reports no `approvalCacheTargets`. Unlike cache targets they never key a remembered grant.
1259
+ */
1260
+ approvalRestrictionPaths?: (args: unknown) => readonly string[] | undefined;
1261
+
1239
1262
  /** The main execution callback for this tool. */
1240
1263
  execute: AgentToolExecFn<TParameters, TDetails, TTheme>;
1241
1264
 
@@ -1,71 +0,0 @@
1
- /**
2
- * Cooperative yield utility for preventing Bun event-loop busy-wait.
3
- *
4
- * ## Root Cause
5
- *
6
- * Bun 1.3.x (JavaScriptCore) event loop busy-waits (spins in userspace)
7
- * when the only pending work is an unresolved Promise — even if there are
8
- * active I/O watchers (stdin, child process pipes, etc.). The event loop
9
- * continuously polls for microtask resolution instead of blocking in
10
- * `epoll_wait`, consuming ~100% of a CPU core.
11
- *
12
- * This affects any `await` on a never-resolved Promise, including:
13
- * - `Promise.withResolvers()` used for user input callbacks
14
- * - `await proc.exited` for long-running child processes
15
- * - Agent loop iterations waiting for the next tool call
16
- *
17
- * ## Fix
18
- *
19
- * A recurring `setInterval` keeps the event loop sleeping in `epoll_wait`.
20
- * The `EventLoopKeepalive` class and `keepaliveWhile()` wrapper provide a
21
- * clean way to install and clean up this keepalive timer.
22
- *
23
- * The older `yieldIfDue()` and `ExponentialYield` approaches (compensated
24
- * sleep loops) are retained for the agent-loop hot-path where Promises
25
- * resolve frequently and the keepalive alone is insufficient.
26
- */
27
- export declare class EventLoopKeepalive {
28
- #private;
29
- [Symbol.dispose](): void;
30
- }
31
- /**
32
- * Cooperative yield gate. Sleeps for at least {@link YieldGateOptions.sleepMs}
33
- * but at most once every {@link YieldGateOptions.intervalMs}; hot-path callers
34
- * invoke it freely and only the slow path actually sleeps.
35
- *
36
- * The clock and sleep are injectable so tests drive the gate logic without
37
- * touching process-global `Date.now`/`scheduler.wait` — globals a concurrent
38
- * test file can restore mid-run, which previously made the shared gate flake.
39
- */
40
- export interface YieldGateOptions {
41
- now?: () => number;
42
- sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
43
- intervalMs?: number;
44
- sleepMs?: number;
45
- }
46
- export declare class YieldGate {
47
- #private;
48
- constructor(opts?: YieldGateOptions);
49
- yieldIfDue(signal?: AbortSignal): Promise<void>;
50
- }
51
- /**
52
- * Yield to the Bun event loop, sleeping for at least 20 ms — but at most once
53
- * every {@link YIELD_INTERVAL_MS} across all callers.
54
- */
55
- export declare function yieldIfDue(): Promise<void>;
56
- export declare class ExponentialYield {
57
- #private;
58
- constructor(opts?: {
59
- minMs?: number;
60
- maxMs?: number;
61
- multiplier?: number;
62
- });
63
- notifyActivity(): void;
64
- sleep(signal?: AbortSignal): Promise<number>;
65
- /**
66
- * Race `racers` against an exponentially-backed-off cooperative yield.
67
- * The losing sleep is cancelled as soon as a racer settles, so no stray
68
- * timers keep the event loop alive past the racer's resolution.
69
- */
70
- race<T>(racers: Array<Promise<T>>): Promise<T>;
71
- }
@@ -1,183 +0,0 @@
1
- /**
2
- * Cooperative yield utility for preventing Bun event-loop busy-wait.
3
- *
4
- * ## Root Cause
5
- *
6
- * Bun 1.3.x (JavaScriptCore) event loop busy-waits (spins in userspace)
7
- * when the only pending work is an unresolved Promise — even if there are
8
- * active I/O watchers (stdin, child process pipes, etc.). The event loop
9
- * continuously polls for microtask resolution instead of blocking in
10
- * `epoll_wait`, consuming ~100% of a CPU core.
11
- *
12
- * This affects any `await` on a never-resolved Promise, including:
13
- * - `Promise.withResolvers()` used for user input callbacks
14
- * - `await proc.exited` for long-running child processes
15
- * - Agent loop iterations waiting for the next tool call
16
- *
17
- * ## Fix
18
- *
19
- * A recurring `setInterval` keeps the event loop sleeping in `epoll_wait`.
20
- * The `EventLoopKeepalive` class and `keepaliveWhile()` wrapper provide a
21
- * clean way to install and clean up this keepalive timer.
22
- *
23
- * The older `yieldIfDue()` and `ExponentialYield` approaches (compensated
24
- * sleep loops) are retained for the agent-loop hot-path where Promises
25
- * resolve frequently and the keepalive alone is insufficient.
26
- */
27
-
28
- import { scheduler } from "node:timers/promises";
29
-
30
- // ---------------------------------------------------------------------------
31
- // EventLoopKeepalive — the primary fix for idle-state busy-wait
32
- // ---------------------------------------------------------------------------
33
-
34
- export class EventLoopKeepalive {
35
- #tmr = setInterval(() => {}, 86_400_000).unref();
36
- [Symbol.dispose](): void {
37
- clearInterval(this.#tmr);
38
- }
39
- }
40
-
41
- // ---------------------------------------------------------------------------
42
- // yieldIfDue — retained for agent-loop hot-path
43
- // ---------------------------------------------------------------------------
44
-
45
- const YIELD_SLEEP_MS = 20;
46
- const YIELD_INTERVAL_MS = 50;
47
-
48
- /**
49
- * Sleep for at least `ms` milliseconds of wall-clock time.
50
- * Retries the wait if it returns prematurely (which can happen when napi
51
- * callbacks wake the event loop via `uv_async_send`). When `signal` is
52
- * provided, the wait is cancellable and silently returns on abort instead
53
- * of throwing — callers race against another promise that decides what to
54
- * do next.
55
- */
56
- async function sleepAtLeast(ms: number, signal?: AbortSignal): Promise<void> {
57
- const start = performance.now();
58
- let remaining = ms;
59
- while (remaining > 0) {
60
- if (signal?.aborted) return;
61
- try {
62
- await scheduler.wait(remaining, { signal });
63
- } catch (err) {
64
- if ((err as { name?: string })?.name === "AbortError") return;
65
- throw err;
66
- }
67
- remaining = ms - (performance.now() - start);
68
- }
69
- }
70
-
71
- /**
72
- * Cooperative yield gate. Sleeps for at least {@link YieldGateOptions.sleepMs}
73
- * but at most once every {@link YieldGateOptions.intervalMs}; hot-path callers
74
- * invoke it freely and only the slow path actually sleeps.
75
- *
76
- * The clock and sleep are injectable so tests drive the gate logic without
77
- * touching process-global `Date.now`/`scheduler.wait` — globals a concurrent
78
- * test file can restore mid-run, which previously made the shared gate flake.
79
- */
80
- export interface YieldGateOptions {
81
- now?: () => number;
82
- sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
83
- intervalMs?: number;
84
- sleepMs?: number;
85
- }
86
-
87
- export class YieldGate {
88
- #lastYieldAt = 0;
89
- readonly #now: () => number;
90
- readonly #sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
91
- readonly #intervalMs: number;
92
- readonly #sleepMs: number;
93
-
94
- constructor(opts: YieldGateOptions = {}) {
95
- this.#now = opts.now ?? (() => Date.now());
96
- this.#sleep = opts.sleep ?? sleepAtLeast;
97
- this.#intervalMs = opts.intervalMs ?? YIELD_INTERVAL_MS;
98
- this.#sleepMs = opts.sleepMs ?? YIELD_SLEEP_MS;
99
- }
100
-
101
- async yieldIfDue(signal?: AbortSignal): Promise<void> {
102
- const now = this.#now();
103
- const elapsed = now - this.#lastYieldAt;
104
- // `elapsed < 0` means the wall clock moved backward relative to the last
105
- // yield (NTP step, fake-timer test, or a stale future timestamp left by
106
- // another caller): treat it as due and re-anchor rather than gate forever.
107
- if (elapsed >= 0 && elapsed < this.#intervalMs) return;
108
- await this.#sleep(this.#sleepMs, signal);
109
- this.#lastYieldAt = this.#now();
110
- }
111
- }
112
-
113
- /**
114
- * Process-wide gate shared by all hot-path callers so tight loops collectively
115
- * respect the interval rather than each sleeping independently.
116
- */
117
- const sharedYieldGate = new YieldGate();
118
-
119
- /**
120
- * Yield to the Bun event loop, sleeping for at least 20 ms — but at most once
121
- * every {@link YIELD_INTERVAL_MS} across all callers.
122
- */
123
- export function yieldIfDue(): Promise<void> {
124
- return sharedYieldGate.yieldIfDue();
125
- }
126
-
127
- // ---------------------------------------------------------------------------
128
- // ExponentialYield — retained for bash-executor long waits
129
- // ---------------------------------------------------------------------------
130
-
131
- const EXP_DEFAULT_MIN_MS = 20;
132
- const EXP_DEFAULT_MAX_MS = 10_000;
133
- const EXP_DEFAULT_MULTIPLIER = 2;
134
-
135
- export class ExponentialYield {
136
- #currentMs: number;
137
- readonly #minMs: number;
138
- readonly #maxMs: number;
139
- readonly #multiplier: number;
140
-
141
- constructor(opts?: { minMs?: number; maxMs?: number; multiplier?: number }) {
142
- this.#minMs = opts?.minMs ?? EXP_DEFAULT_MIN_MS;
143
- this.#maxMs = opts?.maxMs ?? EXP_DEFAULT_MAX_MS;
144
- this.#multiplier = opts?.multiplier ?? EXP_DEFAULT_MULTIPLIER;
145
- this.#currentMs = this.#minMs;
146
- }
147
-
148
- notifyActivity(): void {
149
- this.#currentMs = this.#minMs;
150
- }
151
-
152
- async sleep(signal?: AbortSignal): Promise<number> {
153
- const ms = this.#currentMs;
154
- await sleepAtLeast(ms, signal);
155
- this.#currentMs = Math.min(this.#currentMs * this.#multiplier, this.#maxMs);
156
- return ms;
157
- }
158
-
159
- /**
160
- * Race `racers` against an exponentially-backed-off cooperative yield.
161
- * The losing sleep is cancelled as soon as a racer settles, so no stray
162
- * timers keep the event loop alive past the racer's resolution.
163
- */
164
- async race<T>(racers: Array<Promise<T>>): Promise<T> {
165
- const racer = Promise.race(racers);
166
- const controller = new AbortController();
167
- try {
168
- const yieldMarker = Symbol("exp-yield");
169
- for (;;) {
170
- const result = await Promise.race<T | typeof yieldMarker>([
171
- racer,
172
- this.sleep(controller.signal).then(() => yieldMarker as T | typeof yieldMarker),
173
- ]);
174
- if (result !== yieldMarker) {
175
- this.notifyActivity();
176
- return result;
177
- }
178
- }
179
- } finally {
180
- controller.abort();
181
- }
182
- }
183
- }